Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/contributing/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -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):**

Expand Down
40 changes: 39 additions & 1 deletion packages/mcp-core/src/server.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { McpServer } from "@modelcontextprotocol/server";
import {
McpServer,
WebStandardStreamableHTTPServerTransport,
} from "@modelcontextprotocol/server";
import {
type Span,
captureException,
Expand Down Expand Up @@ -241,6 +244,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,
});
Comment on lines +252 to +254

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High severity and reachable issue identified in your code:
Line 251 has a potentially vulnerable usage of @modelcontextprotocol/server, possibly introducing a high severity vulnerability.

ℹ️ Why this is reachable

A reachable issue is a possible security risk because your project actually executes the vulnerable code. This issue is reachable because your code calls vulnerable code in this version of @modelcontextprotocol/server.
Affected versions of @modelcontextprotocol/hono, @modelcontextprotocol/node, @modelcontextprotocol/sdk, and @modelcontextprotocol/server are vulnerable to Allocation of Resources Without Limits or Throttling. The MCP TypeScript SDK Streamable HTTP server transports and HTTP handlers (StreamableHTTPServerTransport, WebStandardStreamableHTTPServerTransport, NodeStreamableHTTPServerTransport, createMcpHandler, isLegacyRequest, legacyStatelessFallback, toNodeHandler/toWebRequest, createMcpHonoApp) read POST request bodies without a size limit and dispatch JSON-RPC batches of unbounded length. An unauthenticated remote client can exhaust server memory with an oversized body or block other clients with a very long batch, causing denial of service.

References: GHSA

To resolve this comment:
Upgrade this dependency to at least version 2.1.0 at pnpm-lock.yaml.

💬 Ignore this finding

To ignore this, reply with:

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

You can view more details on this finding in the Semgrep AppSec Platform here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Context for a maintainer to triage this (I'm not dismissing it): the flagged line is test-only code in packages/mcp-core/src/server.test.ts. That package resolves @modelcontextprotocol/server from the catalog to 2.4.0 (pnpm-lock.yaml importers), which is above the fixed 2.1.0. The @modelcontextprotocol/server@2.0.0 lockfile entry the finding points to is a transitive dependency of @mastra/core, already on main, and this PR doesn't change the lockfile. Bumping or overriding that transitive copy would be a separate dependency change, so I've left it out of this PR.

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: `<org>-token`, refreshed
Expand Down
9 changes: 8 additions & 1 deletion packages/mcp-core/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,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,
Expand Down Expand Up @@ -333,6 +334,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) {
Expand Down
63 changes: 63 additions & 0 deletions packages/mcp-core/src/telem/sentry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
});
54 changes: 52 additions & 2 deletions packages/mcp-core/src/telem/sentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
Loading