diff --git a/internal/api/mcp_conformance_test.go b/internal/api/mcp_conformance_test.go index 4e9239532..e9d315977 100644 --- a/internal/api/mcp_conformance_test.go +++ b/internal/api/mcp_conformance_test.go @@ -76,6 +76,11 @@ func newMCPHTTPFixture(t *testing.T) *mcpHTTPFixture { f.state.e.ServeHTTP(w, r) })) t.Cleanup(f.server.Close) + t.Cleanup(func() { + for session := range f.app.MCP().Sessions() { + _ = session.Close() + } + }) // Release a stalled probe before Close waits for handlers if a cancellation // assertion fails. This is cleanup only; success requires ctx cancellation. t.Cleanup(func() { close(f.release) }) @@ -121,7 +126,7 @@ func modernMCPBody(method, params string) string { return fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":%q,"params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}},%s}}`, method, params) } -func (f *mcpHTTPFixture) request(t *testing.T, token, method, body, version, rpcMethod, name string) *http.Response { +func (f *mcpHTTPFixture) request(t *testing.T, token, method, body, version, rpcMethod, name string, sessionID ...string) *http.Response { t.Helper() r, err := http.NewRequestWithContext(t.Context(), method, f.server.URL+"/mcp", strings.NewReader(body)) if err != nil { @@ -133,6 +138,9 @@ func (f *mcpHTTPFixture) request(t *testing.T, token, method, body, version, rpc r.Header.Set("Accept", "application/json, text/event-stream") r.Header.Set("MCP-Protocol-Version", version) r.Header.Set("Mcp-Method", rpcMethod) + if len(sessionID) > 0 { + r.Header.Set("Mcp-Session-Id", sessionID[0]) + } if name != "" { r.Header.Set("Mcp-Name", name) } @@ -209,9 +217,9 @@ func TestMCPTrustedAndAbsentOriginsProceedWithAuthentication(t *testing.T) { } } -func TestMCPRejectsLegacyProtocolAndStreams(t *testing.T) { +func TestMCPRejectsUnsupportedProtocolsAndModernStreams(t *testing.T) { f := newMCPHTTPFixture(t) - for _, version := range []string{"2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25", "2027-01-01"} { + for _, version := range []string{"2027-01-01", "2099-01-01"} { t.Run(version, func(t *testing.T) { rpcBody := fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":%q,"io.modelcontextprotocol/clientCapabilities":{}}}}`, version) response := f.request(t, f.token, "POST", rpcBody, version, "server/discover", "") @@ -228,7 +236,7 @@ func TestMCPRejectsLegacyProtocolAndStreams(t *testing.T) { if err := json.Unmarshal(body.Error.Data, &data); err != nil { t.Fatal(err) } - if len(data.Supported) != 1 || data.Supported[0] != appmcp.ProtocolVersion || data.Requested != version { + if strings.Join(data.Supported, ",") != appmcp.ProtocolVersion+",2025-11-25,2025-06-18" || data.Requested != version { t.Fatalf("data=%+v", data) } }) @@ -239,15 +247,361 @@ func TestMCPRejectsLegacyProtocolAndStreams(t *testing.T) { t.Fatalf("%s status=%d headers=%v", method, response.StatusCode, response.Header) } } - for _, body := range []string{`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25"}}`, modernMCPBody("tools/call", `"name":"conformance_probe"`)} { - response := f.request(t, f.token, "POST", body, "", "tools/call", "conformance_probe") - if response.StatusCode != 400 { - t.Fatalf("headerless status=%d", response.StatusCode) + response := f.request(t, f.token, "POST", modernMCPBody("tools/call", `"name":"conformance_probe"`), "", "tools/call", "conformance_probe") + if response.StatusCode != 400 { + t.Fatalf("headerless modern status=%d", response.StatusCode) + } + response = f.request(t, f.token, "POST", modernMCPBody("initialize", `"protocolVersion":"2026-07-28"`), appmcp.ProtocolVersion, "initialize", "") + if response.StatusCode != 400 { + t.Fatalf("initialize with per-request metadata status=%d", response.StatusCode) + } +} + +func decodeMCPResponse(t *testing.T, response *http.Response, result any) *jsonrpc.Error { + t.Helper() + body, err := io.ReadAll(response.Body) + _ = response.Body.Close() + if err != nil { + t.Fatal(err) + } + if strings.HasPrefix(response.Header.Get("Content-Type"), "text/event-stream") { + for line := range strings.SplitSeq(string(body), "\n") { + if strings.HasPrefix(line, "data: ") { + body = []byte(strings.TrimPrefix(line, "data: ")) + break + } + } + } + var envelope struct { + Result json.RawMessage `json:"result"` + Error *jsonrpc.Error `json:"error"` + } + if err := json.Unmarshal(body, &envelope); err != nil { + t.Fatalf("status=%d body=%s: %v", response.StatusCode, body, err) + } + if envelope.Error == nil && result != nil { + if err := json.Unmarshal(envelope.Result, result); err != nil { + t.Fatal(err) + } + } + return envelope.Error +} + +func (f *mcpHTTPFixture) initializeLegacy(t *testing.T, token, version, capabilities string) (string, string) { + t.Helper() + body := fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":%q,"clientInfo":{"name":"legacy","version":"test"},"capabilities":%s}}`, version, capabilities) + response := f.request(t, token, "POST", body, "", "", "") + var initialized mcp.InitializeResult + if err := decodeMCPResponse(t, response, &initialized); err != nil || response.StatusCode != 200 { + t.Fatalf("initialize status=%d error=%v", response.StatusCode, err) + } + id := response.Header.Get("Mcp-Session-Id") + if id == "" { + t.Fatal("legacy initialize did not create a session") + } + response = f.request(t, token, "POST", `{"jsonrpc":"2.0","method":"notifications/initialized"}`, initialized.ProtocolVersion, "", "", id) + if response.StatusCode != http.StatusAccepted { + t.Fatalf("initialized status=%d", response.StatusCode) + } + return id, initialized.ProtocolVersion +} + +func TestMCPLegacySessionsNegotiateAndCall(t *testing.T) { + f := newMCPHTTPFixture(t) + for _, version := range []string{"2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05", "2099-01-01"} { + t.Run(version, func(t *testing.T) { + id, negotiated := f.initializeLegacy(t, f.token, version, "{}") + want := version + if version != "2025-06-18" { + want = "2025-11-25" + } + if negotiated != want { + t.Fatalf("negotiated=%s want=%s", negotiated, want) + } + response := f.request(t, f.token, "POST", `{"jsonrpc":"2.0","id":2,"method":"tools/list"}`, negotiated, "", "", id) + var tools mcp.ListToolsResult + if err := decodeMCPResponse(t, response, &tools); err != nil || len(tools.Tools) == 0 { + t.Fatalf("tools=%+v error=%v", tools, err) + } + response = f.request(t, f.token, "POST", `{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"conformance_probe","arguments":{}}}`, negotiated, "", "", id) + var called mcp.CallToolResult + if err := decodeMCPResponse(t, response, &called); err != nil || called.IsError || len(called.Content) != 1 || called.Content[0].(*mcp.TextContent).Text != "ok" { + t.Fatalf("call=%+v error=%v", called, err) + } + }) + } +} + +func TestMCPInitializeWithModernHeaderSelectsLegacySession(t *testing.T) { + for _, version := range []string{appmcp.ProtocolVersion, "2025-11-25"} { + t.Run(version, func(t *testing.T) { + for _, headers := range []struct{ method, name string }{ + {"initialize", ""}, + {"tools/call", "conformance_probe"}, + {"tools/call", "create_dashboard"}, + } { + f := newMCPHTTPFixture(t) + body := fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":%q,"clientInfo":{"name":"legacy","version":"test"},"capabilities":{}}}`, version) + response := f.request(t, f.token, "POST", body, appmcp.ProtocolVersion, headers.method, headers.name) + var initialized mcp.InitializeResult + if err := decodeMCPResponse(t, response, &initialized); err != nil || response.StatusCode != 200 || initialized.ProtocolVersion != "2025-11-25" { + t.Fatalf("initialize headers=%+v status=%d result=%+v error=%v", headers, response.StatusCode, initialized, err) + } + id := response.Header.Get("Mcp-Session-Id") + if id == "" { + t.Fatal("initialize with modern header did not create a legacy session") + } + if len(f.auth.toolLimiter.entries) != 0 { + t.Fatal("initialize consumed the tool budget") + } + response = f.request(t, f.token, "POST", `{"jsonrpc":"2.0","method":"notifications/initialized"}`, initialized.ProtocolVersion, "", "", id) + if response.StatusCode != http.StatusAccepted { + t.Fatalf("initialized status=%d", response.StatusCode) + } + response = f.request(t, f.token, "POST", `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"conformance_probe","arguments":{}}}`, initialized.ProtocolVersion, "", "", id) + var called mcp.CallToolResult + if err := decodeMCPResponse(t, response, &called); err != nil || response.StatusCode != 200 || called.IsError || f.calls.Load() != 1 { + t.Fatalf("call status=%d result=%+v error=%v", response.StatusCode, called, err) + } + response = f.request(t, f.token, "POST", `{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"create_dashboard","arguments":{}}}`, initialized.ProtocolVersion, "tools/list", "conformance_probe", id) + challenge := response.Header.Get("WWW-Authenticate") + if response.StatusCode != 403 || !strings.Contains(challenge, `error="insufficient_scope"`) || !strings.Contains(challenge, `scope="telemetry:read dashboard:manage"`) { + t.Fatalf("dashboard write status=%d challenge=%s", response.StatusCode, challenge) + } + } + }) + } +} + +func TestBrowserMCPRejectsInitializeWithModernHeader(t *testing.T) { + f := newMCPHTTPFixture(t) + user, err := f.state.users.GetByEmail("interop@example.com") + if err != nil { + t.Fatal(err) + } + cookie := f.state.login(t, user) + body := fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":%q,"capabilities":{},"clientInfo":{"name":"browser","version":"test"}}}`, appmcp.ProtocolVersion) + rec := serve(t, f.state.e, "POST", "/api/mcp", body, map[string]string{ + "Content-Type": "application/json", "Accept": "application/json, text/event-stream", "Fanout-Request": "1", + "MCP-Protocol-Version": appmcp.ProtocolVersion, "Mcp-Method": "initialize", + }, cookie) + if rec.Code != http.StatusBadRequest || rec.Header().Get("Mcp-Session-Id") != "" { + t.Fatalf("browser initialize status=%d headers=%v", rec.Code, rec.Header()) + } + for range f.app.MCP().Sessions() { + t.Fatal("browser initialize created a legacy session") + } +} + +func TestMCPLegacySessionIdentityAndTermination(t *testing.T) { + f := newMCPHTTPFixture(t) + id, version := f.initializeLegacy(t, f.token, "2025-11-25", "{}") + other := f.issueToken(t, "other@example.com", f.clientID) + for _, method := range []string{"POST", "GET", "DELETE"} { + response := f.request(t, other, method, `{"jsonrpc":"2.0","id":2,"method":"tools/list"}`, version, "", "", id) + if response.StatusCode != http.StatusForbidden { + t.Fatalf("%s with another user: status=%d", method, response.StatusCode) + } + } + response := f.request(t, f.token, "DELETE", "", version, "", "", id) + if response.StatusCode != http.StatusNoContent { + t.Fatalf("delete status=%d", response.StatusCode) + } + for _, id := range []string{id, "unknown-after-restart"} { + response := f.request(t, f.token, "POST", `{"jsonrpc":"2.0","id":2,"method":"tools/list"}`, version, "", "", id) + if response.StatusCode != http.StatusNotFound { + t.Fatalf("unknown session status=%d", response.StatusCode) + } + } + response = f.request(t, f.token, "POST", modernMCPBody("tools/call", `"name":"conformance_probe"`), appmcp.ProtocolVersion, "tools/call", "conformance_probe", id) + if response.StatusCode != 200 || response.Header.Get("Mcp-Session-Id") != "" { + t.Fatalf("modern read a legacy session: status=%d headers=%v", response.StatusCode, response.Header) + } +} + +func TestMCPAppsCapabilitiesAcrossEras(t *testing.T) { + f := newMCPHTTPFixture(t) + for _, version := range []string{"2025-11-25", "2025-06-18", "2099-01-01", appmcp.ProtocolVersion} { + for _, apps := range []bool{false, true} { + capabilities := "{}" + if apps { + capabilities = `{"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}}` + } + id, negotiated := "", version + body := `{"jsonrpc":"2.0","id":2,"method":"tools/list"}` + method := "" + if version == appmcp.ProtocolVersion { + body = fmt.Sprintf(`{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":%q,"io.modelcontextprotocol/clientCapabilities":%s}}}`, version, capabilities) + method = "tools/list" + } else { + id, negotiated = f.initializeLegacy(t, f.token, version, capabilities) + } + response := f.request(t, f.token, "POST", body, negotiated, method, "", id) + var listed mcp.ListToolsResult + if err := decodeMCPResponse(t, response, &listed); err != nil { + t.Fatal(err) + } + ui, helpers := false, 0 + for _, tool := range listed.Tools { + ui = ui || tool.Meta["ui"] != nil + if tool.Name == "query_panel_fragment" || tool.Name == "list_panel_exemplars" || tool.Name == "resolve_panel_variables" { + helpers++ + } + } + if ui != apps || apps && helpers != 3 || !apps && helpers != 0 { + t.Fatalf("version=%s apps=%v ui=%v helpers=%d", version, apps, ui, helpers) + } + if version != appmcp.ProtocolVersion { + opposite := "{}" + if !apps { + opposite = `{"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}}` + } + body = fmt.Sprintf(`{"jsonrpc":"2.0","id":3,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/clientCapabilities":%s}}}`, opposite) + response = f.request(t, f.token, "POST", body, negotiated, "", "", id) + if err := decodeMCPResponse(t, response, &listed); err != nil { + t.Fatal(err) + } + for _, tool := range listed.Tools { + if tool.Name == "query_telemetry" && (tool.Meta["ui"] != nil) != apps { + t.Fatalf("legacy request overrode initialized capabilities: version=%s apps=%v meta=%v", version, apps, tool.Meta) + } + } + } + } + } +} + +func TestMCPDashboardScopeAcrossEras(t *testing.T) { + f := newMCPHTTPFixture(t) + for _, version := range []string{"2025-11-25", "2025-06-18", appmcp.ProtocolVersion} { + id := "" + if version != appmcp.ProtocolVersion { + id, _ = f.initializeLegacy(t, f.token, version, "{}") + } + for _, name := range []string{"create_dashboard", "replace_dashboard", "edit_dashboard", "restore_dashboard_version"} { + body := fmt.Sprintf(`{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":%q,"arguments":{}}}`, name) + method, headerName := "", "" + if version == appmcp.ProtocolVersion { + body = modernMCPBody("tools/call", fmt.Sprintf(`"name":%q,"arguments":{}`, name)) + method, headerName = "tools/call", name + } + response := f.request(t, f.token, "POST", body, version, method, headerName, id) + challenge := response.Header.Get("WWW-Authenticate") + if response.StatusCode != 403 || !strings.Contains(challenge, `error="insufficient_scope"`) || !strings.Contains(challenge, `scope="telemetry:read dashboard:manage"`) || !strings.Contains(challenge, `resource_metadata="https://fanout.example.com/.well-known/oauth-protected-resource/mcp"`) { + t.Fatalf("%s %s: status=%d challenge=%s", version, name, response.StatusCode, challenge) + } + if version != appmcp.ProtocolVersion { + response = f.request(t, f.token, "POST", body, version, "tools/list", "conformance_probe", id) + if response.StatusCode != 403 { + t.Fatalf("legacy headers bypassed scope: status=%d", response.StatusCode) + } + } + } + } +} + +func TestMCPLegacyToolRateLimitAndClientIsolation(t *testing.T) { + f := newMCPHTTPFixture(t) + f.auth.toolLimiter.now = func() time.Time { return time.Unix(100000, 0) } + id, version := f.initializeLegacy(t, f.token, "2025-11-25", "{}") + body := `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"conformance_probe","arguments":{}}}` + for i := range mcpToolBurst { + // Legacy clients may send misleading modern headers; the body is authoritative. + response := f.request(t, f.token, "POST", body, version, "tools/list", "other_probe", id) + _, _ = io.Copy(io.Discard, response.Body) + _ = response.Body.Close() + if response.StatusCode != 200 { + t.Fatalf("call %d status=%d", i, response.StatusCode) } } - response := f.request(t, f.token, "POST", modernMCPBody("initialize", `"protocolVersion":"2026-07-28"`), appmcp.ProtocolVersion, "initialize", "") - if response.StatusCode != 404 { - t.Fatalf("modern initialize status=%d", response.StatusCode) + response := f.request(t, f.token, "POST", body, version, "", "", id) + if response.StatusCode != 429 || response.Header.Get("Retry-After") != "1" || f.calls.Load() != mcpToolBurst { + t.Fatalf("status=%d retry=%s executed=%d", response.StatusCode, response.Header.Get("Retry-After"), f.calls.Load()) + } + response = f.request(t, f.token, "POST", modernMCPBody("tools/call", `"name":"conformance_probe"`), appmcp.ProtocolVersion, "tools/call", "conformance_probe") + if response.StatusCode != 429 { + t.Fatalf("modern did not share legacy budget: status=%d", response.StatusCode) + } + other := f.issueToken(t, "other@example.com", f.clientID) + otherID, _ := f.initializeLegacy(t, other, version, "{}") + response = f.request(t, other, "POST", body, version, "", "", otherID) + if response.StatusCode != 200 { + t.Fatalf("other user status=%d", response.StatusCode) + } + user, err := f.state.users.GetByEmail("interop@example.com") + if err != nil { + t.Fatal(err) + } + clientID := registerOAuthClient(t, f.state.e).ClientID + pair, err := f.auth.store.IssueTokenPair(t.Context(), clientID, user.ID, mcpReadScope, testMCPResource) + if err != nil { + t.Fatal(err) + } + otherID, _ = f.initializeLegacy(t, pair.AccessToken, version, "{}") + response = f.request(t, pair.AccessToken, "POST", body, version, "", "", otherID) + if response.StatusCode != 200 { + t.Fatalf("other OAuth client status=%d", response.StatusCode) + } +} + +func TestMCPLegacySessionLimitAndReclamation(t *testing.T) { + f := newMCPHTTPFixture(t) + var first string + for range 8 { + id, _ := f.initializeLegacy(t, f.token, "2025-11-25", "{}") + if first == "" { + first = id + } + } + response := f.request(t, f.token, "POST", `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"overflow","version":"test"}}}`, "", "", "") + if err := decodeMCPResponse(t, response, nil); err == nil || !strings.Contains(err.Message, "session limit") { + t.Fatalf("overflow error=%v", err) + } + other := f.issueToken(t, "other@example.com", f.clientID) + f.initializeLegacy(t, other, "2025-11-25", "{}") + user, err := f.state.users.GetByEmail("interop@example.com") + if err != nil { + t.Fatal(err) + } + clientID := registerOAuthClient(t, f.state.e).ClientID + pair, err := f.auth.store.IssueTokenPair(t.Context(), clientID, user.ID, mcpReadScope, testMCPResource) + if err != nil { + t.Fatal(err) + } + f.initializeLegacy(t, pair.AccessToken, "2025-11-25", "{}") + response = f.request(t, f.token, "POST", modernMCPBody("tools/call", `"name":"conformance_probe"`), appmcp.ProtocolVersion, "tools/call", "conformance_probe") + if response.StatusCode != 200 || response.Header.Get("Mcp-Session-Id") != "" { + t.Fatalf("modern consumed sessions: status=%d headers=%v", response.StatusCode, response.Header) + } + response = f.request(t, f.token, "DELETE", "", "2025-11-25", "", "", first) + if response.StatusCode != http.StatusNoContent { + t.Fatalf("delete status=%d", response.StatusCode) + } + f.initializeLegacy(t, f.token, "2025-11-25", "{}") +} + +func TestMCPRejectsLegacyBatchesAndOversizedBodies(t *testing.T) { + f := newMCPHTTPFixture(t) + id, version := f.initializeLegacy(t, f.token, "2025-11-25", "{}") + call := `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"conformance_probe","arguments":{}}}` + for _, version := range []string{"", version} { + response := f.request(t, f.token, "POST", "["+call+"]", version, "", "", id) + if response.StatusCode != 400 || f.calls.Load() != 0 { + t.Fatalf("batch version=%q status=%d executed=%d", version, response.StatusCode, f.calls.Load()) + } + } + response := f.request(t, f.token, "POST", call+strings.Repeat(" ", int(mcp.DefaultMaxRequestBodyBytes)), version, "", "", id) + if response.StatusCode != http.StatusRequestEntityTooLarge || f.calls.Load() != 0 { + t.Fatalf("oversized status=%d executed=%d", response.StatusCode, f.calls.Load()) + } +} + +func TestMCPUnauthenticatedChallengeNamesReadScope(t *testing.T) { + f := newMCPHTTPFixture(t) + response := f.request(t, "", "POST", "", "", "", "") + challenge := response.Header.Get("WWW-Authenticate") + if response.StatusCode != 401 || !strings.Contains(challenge, `scope="telemetry:read"`) || !strings.Contains(challenge, `resource_metadata="https://fanout.example.com/.well-known/oauth-protected-resource/mcp"`) { + t.Fatalf("status=%d challenge=%s", response.StatusCode, challenge) } } diff --git a/internal/api/mcp_policy.go b/internal/api/mcp_policy.go index 1424c5b0d..c30f59c76 100644 --- a/internal/api/mcp_policy.go +++ b/internal/api/mcp_policy.go @@ -1,6 +1,7 @@ package api import ( + "encoding/json" "math" "net" "net/http" @@ -10,7 +11,9 @@ import ( "sync" "time" + appmcp "github.com/labstack/fanout/internal/mcp" mcpgoauth "github.com/modelcontextprotocol/go-sdk/auth" + "github.com/modelcontextprotocol/go-sdk/jsonrpc" "golang.org/x/time/rate" ) @@ -107,7 +110,12 @@ func (l *mcpToolLimiter) allow(key mcpToolKey) (bool, int) { func (l *mcpToolLimiter) protect(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { info := mcpgoauth.TokenInfoFromContext(r.Context()) - if info != nil && r.Method == http.MethodPost && r.Header.Get("Mcp-Method") == "tools/call" { + method, _, err := mcpRequestMethodAndName(r) + if err != nil { + appmcp.WriteHTTPMessageError(w, err) + return + } + if info != nil && method == "tools/call" { client, _ := info.Extra["client_id"].(string) if allowed, retry := l.allow(mcpToolKey{info.UserID, client}); !allowed { // MCP 2026-07-28 server/tools#security-considerations requires @@ -121,3 +129,29 @@ func (l *mcpToolLimiter) protect(next http.Handler) http.Handler { next.ServeHTTP(w, r) }) } + +func mcpRequestMethodAndName(r *http.Request) (string, string, error) { + if r.Method != http.MethodPost { + return "", "", nil + } + message, err := appmcp.ReadHTTPMessage(r) + if err != nil { + return "", "", err + } + request, ok := message.(*jsonrpc.Request) + if !ok { + return "", "", nil + } + method, name := r.Header.Get("Mcp-Method"), r.Header.Get("Mcp-Name") + // Initialize selects legacy semantics regardless of headers. Only other + // modern requests have their headers checked against the body by the SDK. + if request.Method != "initialize" && r.Header.Get("MCP-Protocol-Version") >= appmcp.ProtocolVersion && method != "" && (method != "tools/call" || name != "") { + return method, name, nil + } + name = "" + var params map[string]json.RawMessage + if json.Unmarshal(request.Params, ¶ms) == nil { + _ = json.Unmarshal(params["name"], &name) + } + return request.Method, name, nil +} diff --git a/internal/api/oauth.go b/internal/api/oauth.go index 990307660..ba7fcfab7 100644 --- a/internal/api/oauth.go +++ b/internal/api/oauth.go @@ -92,7 +92,11 @@ func (h *MCPAuthorization) ProtectMCP(next http.Handler) http.Handler { next.ServeHTTP(w, r) return } - requiredScope := requiredMCPToolScope(r) + requiredScope, err := requiredMCPToolScope(r) + if err != nil { + appmcp.WriteHTTPMessageError(w, err) + return + } requiredScopes := []string{mcpReadScope} if requiredScope != "" && requiredScope != mcpReadScope { requiredScopes = append(requiredScopes, requiredScope) @@ -112,6 +116,7 @@ func (h *MCPAuthorization) ProtectMCP(next http.Handler) http.Handler { }) protected := mcpgoauth.RequireBearerToken(h.verifyMCPToken, &mcpgoauth.RequireBearerTokenOptions{ ResourceMetadataURL: h.metadataURL, + Scopes: []string{mcpReadScope}, })(scopeChecked) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !strings.EqualFold(strings.TrimSpace(r.Host), h.allowedHost) { @@ -122,13 +127,12 @@ func (h *MCPAuthorization) ProtectMCP(next http.Handler) http.Handler { }) } -func requiredMCPToolScope(r *http.Request) string { - // HTTPHandler requires the modern protocol; the SDK checks these headers - // against its decoded request before dispatch, including notifications. - if r.Method != http.MethodPost || r.Header.Get("Mcp-Method") != "tools/call" { - return "" +func requiredMCPToolScope(r *http.Request) (string, error) { + method, name, err := mcpRequestMethodAndName(r) + if err != nil || method != "tools/call" { + return "", err } - return appmcp.RequiredToolScope(r.Header.Get("Mcp-Name")) + return appmcp.RequiredToolScope(name), nil } // ProtectBrowserMCP adapts an already-authenticated browser session to the @@ -162,6 +166,17 @@ func (h *MCPAuthorization) ProtectBrowserMCP(sessions *appauth.BrowserSessions, if user == nil { return echo.NewHTTPError(http.StatusUnauthorized, "not authenticated") } + if c.Request().Header.Get("MCP-Protocol-Version") < appmcp.ProtocolVersion { + return echo.NewHTTPError(http.StatusBadRequest, "browser MCP requires the modern protocol") + } + method, _, err := mcpRequestMethodAndName(c.Request()) + if err != nil { + appmcp.WriteHTTPMessageError(c.Response(), err) + return nil + } + if method == "initialize" { + return echo.NewHTTPError(http.StatusBadRequest, "browser MCP requires the modern protocol") + } ctx := context.WithValue(c.Request().Context(), browserMCPUserContextKey{}, *user) request := c.Request().Clone(ctx) request.Header.Set("Authorization", "Bearer "+browserMCPSessionBearer) diff --git a/internal/api/oauth_test.go b/internal/api/oauth_test.go index 0645bc543..3603b1904 100644 --- a/internal/api/oauth_test.go +++ b/internal/api/oauth_test.go @@ -17,6 +17,7 @@ import ( "github.com/labstack/fanout/internal/auth" "github.com/labstack/fanout/internal/config" + appmcp "github.com/labstack/fanout/internal/mcp" appstore "github.com/labstack/fanout/internal/store" mcpgoauth "github.com/modelcontextprotocol/go-sdk/auth" ) @@ -271,9 +272,11 @@ func TestBrowserMCPUsesSessionWithoutWeakeningRemoteMCP(t *testing.T) { t.Fatalf("browser MCP without CSRF proof = %d %s, want 403", csrfResponse.Code, csrfResponse.Body.String()) } - browser := serve(t, e, http.MethodPost, "/api/mcp", "", map[string]string{ - "Authorization": "Bearer attacker-controlled", - "Fanout-Request": "1", + browser := serve(t, e, http.MethodPost, "/api/mcp", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`, map[string]string{ + "Authorization": "Bearer attacker-controlled", + "Fanout-Request": "1", + "MCP-Protocol-Version": appmcp.ProtocolVersion, + "Mcp-Method": "tools/list", }, cookie) if browser.Code != http.StatusNoContent { t.Fatalf("session browser MCP = %d %s", browser.Code, browser.Body.String()) diff --git a/internal/mcp/http.go b/internal/mcp/http.go new file mode 100644 index 000000000..9fb7c342f --- /dev/null +++ b/internal/mcp/http.go @@ -0,0 +1,88 @@ +package mcp + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "sync" + "time" + + "github.com/modelcontextprotocol/go-sdk/jsonrpc" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +const ( + // Legacy sessions expire after 10 idle minutes; each user/OAuth-client pair + // may keep eight live sessions. Modern requests never enter this accounting. + legacySessionTimeout = 10 * time.Minute + legacySessionLimit = 8 +) + +// ReadHTTPMessage preserves the body for the SDK and excludes JSON-RPC batches. +func ReadHTTPMessage(r *http.Request) (jsonrpc.Message, error) { + if r.Body == nil { + return nil, io.EOF + } + body, err := io.ReadAll(http.MaxBytesReader(nil, r.Body, mcp.DefaultMaxRequestBodyBytes)) + if err != nil { + return nil, err + } + _ = r.Body.Close() + r.Body = io.NopCloser(bytes.NewReader(body)) + return jsonrpc.DecodeMessage(body) +} + +func WriteHTTPMessageError(w http.ResponseWriter, err error) { + status := http.StatusBadRequest + var tooLarge *http.MaxBytesError + if errors.As(err, &tooLarge) { + status = http.StatusRequestEntityTooLarge + } + http.Error(w, http.StatusText(status), status) +} + +func limitLegacySessions(server *mcp.Server) mcp.Middleware { + type principal struct{ user, client string } + var mu sync.Mutex + sessions := make(map[*mcp.ServerSession]principal) + return func(next mcp.MethodHandler) mcp.MethodHandler { + return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) { + if method != "initialize" { + return next(ctx, method, req) + } + session, ok := req.GetSession().(*mcp.ServerSession) + extra := req.GetExtra() + if !ok || session == nil || session.ID() == "" || extra == nil || extra.TokenInfo == nil { + return next(ctx, method, req) + } + info := extra.TokenInfo + client, _ := info.Extra["client_id"].(string) + key := principal{info.UserID, client} + mu.Lock() + defer mu.Unlock() + live := make(map[*mcp.ServerSession]bool) + count := 0 + for session := range server.Sessions() { + live[session] = true + if owner, exists := sessions[session]; exists && owner == key { + count++ + } + } + for session := range sessions { + if !live[session] { + delete(sessions, session) + } + } + if count >= legacySessionLimit { + return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidRequest, Message: "legacy session limit exceeded"} + } + result, err := next(ctx, method, req) + if err == nil { + sessions[session] = key + } + return result, err + } + } +} diff --git a/internal/mcp/server.go b/internal/mcp/server.go index 20d875678..0abd41749 100644 --- a/internal/mcp/server.go +++ b/internal/mcp/server.go @@ -27,6 +27,8 @@ const mcpUIExtension = "io.modelcontextprotocol/ui" const ProtocolVersion = "2026-07-28" +var supportedProtocolVersions = []string{ProtocolVersion, "2025-11-25", "2025-06-18"} + const staticCatalogTTLMs = 5 * 60 * 1000 const serverInstructions = "Start with get_observability_overview for system health, use get_intelligence_snapshot for the latest precomputed anomalies and log patterns, get_service_topology for direct dependency edges (use this preset once for a service map; do not repeat the same map with query_telemetry), get_service_dependencies for bounded upstream or downstream reachability from a service, get_service_performance for latency, errors and slow operations across HTTP, gRPC and consumers, inspect_trace for one trace, and search_logs for application events. Treat schema, timestamps, provenance, and bounded time windows as authoritative. Dashboard tools are scoped to the authenticated user. For a custom chart in chat, use query_telemetry with one v1 panel; every chart view returns a dashboard fragment rendered by the shared panel renderer. Do not present empty results; state no matching data findings in the answer and prefer the signal a service actually has. Dashboards contain only panels that return data; text panels are exempt. To build a dashboard, read get_telemetry_schema, draft panels, run preview_panels until every non-text panel returns data, then create_dashboard. To change one, get_dashboard first and use edit_dashboard; replace only for a redesign the user asked for." @@ -119,7 +121,7 @@ func newServer(queries Observability, dashboards *dashboard.Service, panels *pan Name: "fanout", Title: "Fanout Observability", Version: version, - }, &mcp.ServerOptions{SupportedProtocolVersions: []string{ProtocolVersion}, Instructions: serverInstructions, Capabilities: &mcp.ServerCapabilities{ + }, &mcp.ServerOptions{SupportedProtocolVersions: supportedProtocolVersions, Instructions: serverInstructions, Capabilities: &mcp.ServerCapabilities{ Extensions: map[string]any{ mcpUIExtension: map[string]any{"mimeTypes": []string{mcpAppMIME}}, }, @@ -140,7 +142,7 @@ func newServer(queries Observability, dashboards *dashboard.Service, panels *pan s.registerPanelTools() s.registerDashboardTools() s.registerAppResources() - s.mcp.AddReceivingMiddleware(normalizeToolErrors, recoverToolPanic, addStaticCacheHints, filterMCPAppToolMetadata, s.validateToolArguments) + s.mcp.AddReceivingMiddleware(limitLegacySessions(s.mcp), normalizeToolErrors, recoverToolPanic, addStaticCacheHints, filterMCPAppToolMetadata, s.validateToolArguments) return s } @@ -276,11 +278,25 @@ func filterMCPAppToolMetadata(next mcp.MethodHandler) mcp.MethodHandler { func clientSupportsMCPApps(req mcp.Request) bool { request, ok := req.(interface { ClientCapabilities() *mcp.ClientCapabilities + ProtocolVersion() string }) if !ok { return false } capabilities := request.ClientCapabilities() + legacy := request.ProtocolVersion() < ProtocolVersion + if extra := req.GetExtra(); extra != nil && extra.Header != nil { + legacy = extra.Header.Get("MCP-Protocol-Version") < ProtocolVersion + } + // The SDK prefers per-request capabilities even on legacy sessions; their + // declaration belongs to initialize, including when its version negotiated down. + if legacy { + if session, ok := req.GetSession().(*mcp.ServerSession); ok && session != nil { + if initialized := session.InitializeParams(); initialized != nil { + capabilities = initialized.Capabilities + } + } + } if capabilities == nil { return false } @@ -312,7 +328,7 @@ func (s *Server) HTTPHandler() http.Handler { // localhost Host heuristic because a legitimate local reverse proxy connects // over loopback while preserving the public Host (for example, // fanout.example.com); the heuristic otherwise rejects every browser MCP App. - handler := mcp.NewStreamableHTTPHandler( + modern := mcp.NewStreamableHTTPHandler( func(*http.Request) *mcp.Server { return s.mcp }, &mcp.StreamableHTTPOptions{ Stateless: true, @@ -320,25 +336,46 @@ func (s *Server) HTTPHandler() http.Handler { DisableLocalhostProtection: true, }, ) + legacy := mcp.NewStreamableHTTPHandler( + func(*http.Request) *mcp.Server { return s.mcp }, + &mcp.StreamableHTTPOptions{ + SessionTimeout: legacySessionTimeout, + DisableLocalhostProtection: true, + }, + ) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // SDK v1.8 still accepts headerless legacy initialize requests even - // with SupportedProtocolVersions narrowed. Require the modern header - // here and reject legacy versions with the modern error body. Modern - // version negotiation, body mirrors and metadata belong to the SDK. - version := r.Header.Get("MCP-Protocol-Version") - if r.Method == http.MethodPost && version < ProtocolVersion { - data, _ := json.Marshal(mcp.UnsupportedProtocolVersionData{Supported: []string{ProtocolVersion}, Requested: version}) - failure := &jsonrpc.Error{Code: mcp.CodeUnsupportedProtocolVersion, Message: "unsupported protocol version", Data: data} - if version == "" { - failure = &jsonrpc.Error{Code: mcp.CodeHeaderMismatch, Message: "MCP-Protocol-Version header is required"} + if r.Method == http.MethodPost { + // The SDK defaults headerless requests to 2025-03-26, which allows + // batches. Decode one message before entering that compatibility path. + message, err := ReadHTTPMessage(r) + if err != nil { + WriteHTTPMessageError(w, err) + return + } + if request, ok := message.(*jsonrpc.Request); ok { + if request.Method == "initialize" { + if r.Header.Get("MCP-Protocol-Version") >= ProtocolVersion { + // Initialize selects legacy semantics; the SDK otherwise + // rejects this header before negotiating the body version. + r = r.Clone(r.Context()) + r.Header.Del("MCP-Protocol-Version") + } + legacy.ServeHTTP(w, r) + return + } + var params map[string]json.RawMessage + var meta mcp.Meta + if json.Unmarshal(request.Params, ¶ms) == nil && json.Unmarshal(params["_meta"], &meta) == nil && meta[mcp.MetaKeyProtocolVersion] != nil { + modern.ServeHTTP(w, r) + return + } } - body, _ := jsonrpc.EncodeMessage(&jsonrpc.Response{Error: failure}) - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusBadRequest) - _, _ = w.Write(body) + } + if r.Header.Get("MCP-Protocol-Version") >= ProtocolVersion { + modern.ServeHTTP(w, r) return } - handler.ServeHTTP(w, r) + legacy.ServeHTTP(w, r) }) } diff --git a/site/src/content/docs/guides/connect-over-mcp.mdx b/site/src/content/docs/guides/connect-over-mcp.mdx index 73904f3e2..399b26ea3 100644 --- a/site/src/content/docs/guides/connect-over-mcp.mdx +++ b/site/src/content/docs/guides/connect-over-mcp.mdx @@ -64,10 +64,15 @@ Use your instance's public URL, then authorize the connection in your browser. ## Protocol -Fanout serves MCP protocol version `2026-07-28` over stateless Streamable -HTTP. Every request carries `MCP-Protocol-Version: 2026-07-28`; a request -without it, or with an earlier version, is rejected, and there are no -sessions or `initialize` handshake. Use a client that supports this version. +Fanout serves modern and legacy MCP clients concurrently over Streamable HTTP +on `/mcp`. Modern `2026-07-28` requests carry per-request metadata and +`MCP-Protocol-Version: 2026-07-28`, with no session or `initialize` handshake. +Legacy clients use `initialize` to negotiate `2025-11-25` or `2025-06-18` and +receive an `Mcp-Session-Id` bound to the authenticated user. Legacy sessions +expire after 10 idle minutes, with at most eight live sessions per user–OAuth +client pair. An expired session or a server restart requires re-initialization. +Versions `2025-03-26` and `2024-11-05` are not served. The browser's `/api/mcp` +route uses only the modern protocol. On `/mcp` and `/api/mcp`, an `Origin` header must exactly match the RFC 6454 serialization of `FANOUT_PUBLIC_URL`. Malformed or untrusted origins receive @@ -76,8 +81,8 @@ origins are accepted. Requests without `Origin` pass this check. `tools/call` requests are limited to 20 per second per user–OAuth client pair, with a burst of 100. Excess calls receive `429` with `Retry-After`. The in-process -agent is exempt. Client disconnects cancel in-flight tool calls, including DuckDB -queries. +agent is exempt. Modern client disconnects cancel in-flight tool calls, including +DuckDB queries. ## Scopes