From 43a33d51f574d3a500cf7e2b2bf8b98ed91234b6 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:14:16 +0000 Subject: [PATCH] fix(mcp): Stop reporting rejected client requests as Sentry issues The MCP SDK's Streamable HTTP transport answers malformed requests (missing Accept media type, wrong Content-Type, unparseable body, unsupported protocol version) with a 4xx and reports each one through transport.onerror. Sentry's MCP server integration captures every onerror call as an unhandled error, and server.onerror sent it to logIssue as well, so client mistakes became high-priority issues. Classify these rejections once, drop the integration's copy in sentryBeforeSend, and log them as warnings in server.onerror. Other transport errors still create issues, and app.server.response keeps counting the 4xx responses by client family. Fixes MCP-SERVER-GFB Co-Authored-By: bete <28983162+betegon@users.noreply.github.com> --- docs/contributing/error-handling.md | 1 + packages/mcp-core/src/server.test.ts | 48 ++++++++++++++++- packages/mcp-core/src/server.ts | 9 +++- packages/mcp-core/src/telem/sentry.test.ts | 63 ++++++++++++++++++++++ packages/mcp-core/src/telem/sentry.ts | 54 ++++++++++++++++++- 5 files changed, 170 insertions(+), 5 deletions(-) diff --git a/docs/contributing/error-handling.md b/docs/contributing/error-handling.md index 0995057b9..7d8db5a47 100644 --- a/docs/contributing/error-handling.md +++ b/docs/contributing/error-handling.md @@ -68,6 +68,7 @@ ApiError (base class) - `ConfigurationError` (except HTTP transport, which notifies operators once via `logIssue` with a generic user message) - `LLMProviderError` - `APICallError` from the upstream AI provider (converted to `LLMProviderError` / logged as warnings) +- MCP transport rejections of malformed client requests, such as a missing `Accept` media type (406), a wrong `Content-Type` (415), or an unparseable body (400). `server.onerror` logs them as warnings and `sentryBeforeSend` drops the copy that Sentry's MCP server integration captures. The `app.server.response` metric still counts these responses by status and client family. **System Errors (Should be captured by Sentry):** diff --git a/packages/mcp-core/src/server.test.ts b/packages/mcp-core/src/server.test.ts index c3f7c8034..157945fc5 100644 --- a/packages/mcp-core/src/server.test.ts +++ b/packages/mcp-core/src/server.test.ts @@ -1,7 +1,16 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; -import { McpServer } from "@modelcontextprotocol/server"; -import { type Span, getClient, setUser, startSpan } from "@sentry/core"; +import { + McpServer, + WebStandardStreamableHTTPServerTransport, +} from "@modelcontextprotocol/server"; +import { + type Span, + captureException, + getClient, + setUser, + startSpan, +} from "@sentry/core"; import { createDefaultEvent, eventFixture, @@ -234,6 +243,41 @@ describe("buildServer", () => { }); }); + describe("transport errors", () => { + // MCP-SERVER-GFB: clients that omit text/event-stream from Accept got a + // 406 and also created a Sentry issue. + it("does not create an issue when the transport rejects a request", async () => { + const server = buildServer({ context: baseContext }); + const transport = new WebStandardStreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + }); + await server.connect(transport); + const response = await transport.handleRequest( + new Request("http://localhost/mcp", { + method: "POST", + headers: { + Accept: "application/json", + "Content-Type": "application/json", + }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "ping" }), + }), + ); + await server.close(); + + expect(response.status).toBe(406); + expect(captureException).not.toHaveBeenCalled(); + }); + + it("creates an issue for unexpected transport errors", () => { + const server = buildServer({ context: baseContext }); + const error = new Error("Failed to send response: socket closed"); + + server.server.onerror?.(error); + + expect(captureException).toHaveBeenCalledWith(error, expect.anything()); + }); + }); + describe("credential routing", () => { /** * A router with one account per organization: `-token`, refreshed diff --git a/packages/mcp-core/src/server.ts b/packages/mcp-core/src/server.ts index 0e2ee6e25..c5cd5130d 100644 --- a/packages/mcp-core/src/server.ts +++ b/packages/mcp-core/src/server.ts @@ -45,7 +45,8 @@ import { recordToolFailure, } from "./internal/error-handling"; import type { Skill } from "./skills"; -import { type LogIssueOptions, logIssue } from "./telem/logging"; +import { type LogIssueOptions, logIssue, logWarn } from "./telem/logging"; +import { isTransportClientRejection } from "./telem/sentry"; import { executeToolHandler, getAvailableTools, @@ -332,6 +333,12 @@ export function buildServer({ }, }; + // The transport already answered a malformed client request with a 4xx. + if (isTransportClientRejection(error)) { + logWarn(error, transportLogOptions); + return; + } + logIssue(error, transportLogOptions); }; for (const { name, config, handler } of registrations) { diff --git a/packages/mcp-core/src/telem/sentry.test.ts b/packages/mcp-core/src/telem/sentry.test.ts index 8d5e636c1..f4b4b9485 100644 --- a/packages/mcp-core/src/telem/sentry.test.ts +++ b/packages/mcp-core/src/telem/sentry.test.ts @@ -201,4 +201,67 @@ describe("sentry", () => { expect(result.message).toBe("Deep nesting test"); }); }); + + describe("MCP transport client rejections", () => { + // Shape of the events Sentry's MCP server integration captures from + // `transport.onerror` (MCP-SERVER-GFB). + function transportErrorEvent( + type: string, + value: string, + errorType = "transport", + ): SentryEvent { + return { + exception: { + values: [ + { + type, + value, + mechanism: { + type: "auto.ai.mcp_server", + handled: false, + data: { error_type: errorType }, + }, + }, + ], + }, + }; + } + + it.each([ + [ + "Error", + "Not Acceptable: Client must accept both application/json and text/event-stream", + ], + [ + "Error", + "Unsupported Media Type: Content-Type must be application/json", + ], + [ + "Error", + "Bad Request: Unsupported protocol version: 2024-01-01 (supported versions: 2025-11-25, 2025-06-18)", + ], + [ + "SyntaxError", + "Expected property name or '}' in JSON at position 1 (line 1 column 2)", + ], + ])("drops the rejected request %s: %s", (type, value) => { + expect(sentryBeforeSend(transportErrorEvent(type, value), {})).toBeNull(); + }); + + it("keeps other transport errors", () => { + const event = transportErrorEvent("Error", "Error replaying events"); + + expect(sentryBeforeSend(event, {})).toEqual(event); + }); + + it("keeps rejection messages that did not come from the transport", () => { + const event = transportErrorEvent( + "Error", + "Bad Request: something the server did", + "handler_execution", + ); + + expect(sentryBeforeSend(event, {})).toEqual(event); + }); + }); }); diff --git a/packages/mcp-core/src/telem/sentry.ts b/packages/mcp-core/src/telem/sentry.ts index dc2036b7c..cd2c0590d 100644 --- a/packages/mcp-core/src/telem/sentry.ts +++ b/packages/mcp-core/src/telem/sentry.ts @@ -88,11 +88,61 @@ function scrubValue(value: unknown, depth = 0): [unknown, boolean, string[]] { return [value, false, []]; } +// The MCP SDK's Streamable HTTP transport reports each request it rejects +// through `transport.onerror`, then answers the client with a 4xx. Each +// rejection message starts with the HTTP reason phrase of that 4xx +// (for example "Not Acceptable:" for a missing Accept media type). A +// `SyntaxError` is the request body failing `JSON.parse` (400). +const TRANSPORT_CLIENT_REJECTION_PREFIXES = [ + "Not Acceptable:", + "Unsupported Media Type:", + "Payload Too Large:", + "Bad Request:", + "Invalid Request:", +]; + /** - * Sentry beforeSend hook that scrubs sensitive data from events - * and applies custom fingerprinting for specific error types. + * Whether a transport error is the MCP SDK rejecting a malformed client + * request with a 4xx. These are client mistakes, not server faults, so they + * must not create Sentry issues. + */ +export function isTransportClientRejection(error: { + name?: string; + message?: string; +}): boolean { + if (error.name === "SyntaxError") { + return true; + } + const message = error.message ?? ""; + return TRANSPORT_CLIENT_REJECTION_PREFIXES.some((prefix) => + message.startsWith(prefix), + ); +} + +// Sentry's MCP server integration captures every `transport.onerror` call as +// an unhandled exception with this mechanism, before our own handler runs. +function isCapturedTransportClientRejection(exception: any): boolean { + const mechanism = exception?.mechanism; + return ( + mechanism?.type === "auto.ai.mcp_server" && + mechanism.data?.error_type === "transport" && + isTransportClientRejection({ + name: exception.type, + message: exception.value, + }) + ); +} + +/** + * Sentry beforeSend hook that drops MCP transport rejections of malformed + * client requests, scrubs sensitive data from events, and applies custom + * fingerprinting for specific error types. */ export function sentryBeforeSend(event: any, _hint: any): any { + if (event?.exception?.values?.some(isCapturedTransportClientRejection)) { + return null; + } + // Custom fingerprinting for AI SDK API call errors. // These errors share the same stack trace but have different messages // (e.g., "Country, region, or territory not supported", temperature issues).