Skip to content
Merged
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
7 changes: 6 additions & 1 deletion packages/mcp/src/mcp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -844,7 +844,12 @@ describe('MCP server wiring', () => {
const result = await searchTool.handler({ query: 'CAIU1234567' });

expect(result.isError).toBe(true);
expect(Sentry.captureException).toHaveBeenCalledWith(expect.any(Error));
expect(Sentry.captureException).toHaveBeenCalledWith(
expect.any(Error),
expect.objectContaining({
tags: expect.objectContaining({ 'mcp.tool': 'search_container' }),
}),
);
const captured = vi.mocked(Sentry.captureException).mock.calls[0]?.[0];
expect(captured).toBeInstanceOf(Error);
expect((captured as Error).message).not.toContain('internal.example');
Expand Down
57 changes: 56 additions & 1 deletion packages/mcp/src/sentry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ import { createServer, type Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import * as Sentry from '@sentry/node';
import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
import { buildSentryOptions, scrubSensitiveRequestData } from './sentry.js';
import {
buildSentryOptions,
captureMcpException,
scrubSensitiveRequestData,
} from './sentry.js';

const SECRET_VALUES = [
'AUTH-SENTINEL-0000',
Expand Down Expand Up @@ -206,4 +210,55 @@ describe('Sentry event pipeline', () => {
expect(sent).not.toContain(value);
}
});

it('sends a tool failure with its class, status and tool, but not its text', async () => {
sentEnvelopes.length = 0;
const upstream = Object.assign(
new Error(
'Upstream 503 at https://internal.example/v2?token=secret-token',
),
{ name: 'UpstreamError', status: 503 },
);
captureMcpException(upstream, {
tool: 'get_container',
credentialType: 'user',
});
await Sentry.flush(2000);

const event = sentEnvelopes
.map((envelope) => JSON.parse(envelope)[1][0][1])
.find((item) => item.exception);
expect(event.exception.values[0]).toMatchObject({
type: 'UpstreamError',
value: 'The Terminal49 upstream request could not be completed.',
});
expect(event.tags).toMatchObject({
'error.class': 'UpstreamError',
'upstream.status_code': '503',
'mcp.tool': 'get_container',
'mcp.credential_type': 'user',
});
expect(event.fingerprint).toEqual(['mcp-error', 'UpstreamError', '503']);
const sent = sentEnvelopes.join('\n');
expect(sent).not.toContain('internal.example');
expect(sent).not.toContain('secret-token');
});

it('leaves out a status that is not an HTTP status', async () => {
sentEnvelopes.length = 0;
captureMcpException(
Object.assign(new Error('odd'), { name: 'NetworkError', status: 'x' }),
);
await Sentry.flush(2000);

const event = sentEnvelopes
.map((envelope) => JSON.parse(envelope)[1][0][1])
.find((item) => item.exception);
expect(event.tags).not.toHaveProperty('upstream.status_code');
expect(event.fingerprint).toEqual([
'mcp-error',
'NetworkError',
'no-status',
]);
});
});
46 changes: 44 additions & 2 deletions packages/mcp/src/sentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,35 @@ export function instrumentMcpServer<TServer extends McpServer>(
});
}

export function captureMcpException(error: unknown): void {
/** Where a reported failure happened. Every value is a fixed identifier. */
export interface McpExceptionContext {
tool?: string;
credentialType?: string;
}

function httpStatusOf(error: unknown): number | undefined {
const status =
error && typeof error === 'object'
? (error as { status?: unknown }).status
: undefined;
return typeof status === 'number' &&
Number.isInteger(status) &&
status >= 100 &&
status <= 599
? status
: undefined;
}

/**
* Reports a failure under a fixed message, so no upstream text, URL or token
* reaches Sentry. The error class, the upstream HTTP status and the tool are
* tags, and the class and status set the fingerprint: every report has the
* same message and stack, so without it Sentry merges unrelated failures.
*/
export function captureMcpException(
error: unknown,
context: McpExceptionContext = {},
): void {
if (Sentry.isInitialized()) {
const safeError = new Error(
'The Terminal49 upstream request could not be completed.',
Expand All @@ -175,7 +203,21 @@ export function captureMcpException(error: unknown): void {
safeError.name = /^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/.test(name)
? name
: 'Error';
Sentry.captureException(safeError);
const status = httpStatusOf(error);
const tags: Record<string, string> = { 'error.class': safeError.name };
if (status !== undefined) tags['upstream.status_code'] = String(status);
if (context.tool) tags['mcp.tool'] = context.tool;
if (context.credentialType) {
tags['mcp.credential_type'] = context.credentialType;
}
Sentry.captureException(safeError, {
tags,
fingerprint: [
'mcp-error',
safeError.name,
status === undefined ? 'no-status' : String(status),
],
});
}
}

Expand Down
52 changes: 46 additions & 6 deletions packages/mcp/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
TrackContainerError,
} from './tools/track-container.js';
import { executeSearchContainer } from './tools/search-container.js';
import { httpStatus, ToolInputError } from './tools/soft-results.js';
import {
executeGetShipmentDetails,
shipmentDetailsSchema,
Expand Down Expand Up @@ -997,8 +998,50 @@ const CONFIRMED_WRITE_CLAUSE: Record<ConfirmationScope, string> = {
const APPROVAL_CHANNELS =
'On a client that can ask the user (form elicitation), the client shows the user the preview and asks them to confirm, and the tool writes only on their yes; never pass confirmation_token there. On any other client, the first call returns the preview with a confirmation_token: show the preview to the user, and call again with the same arguments and the token only after the user approves it in this turn.';

/**
* Terminal49 answers with these statuses when the caller's input or the
* caller's own credential is at fault: invalid or expired key, no access, no
* such record, invalid input. 408 and 429 are absent on purpose: they are
* about load, not the caller.
*/
const CALLER_ERROR_STATUSES: ReadonlySet<number> = new Set([
400, 401, 403, 404, 409, 410, 422,
]);

/**
* Whether a tool failure is the caller's to fix, and so stays out of Sentry.
* The tool still returns it as a tool error and the operator log records it;
* Sentry is for faults the server can fix.
*
* A 401 counts as the caller's only when the caller supplied the credential
* Terminal49 rejected. The gateway itself resolves a `user` credential (a
* WorkOS grant) and configures a `shared_token`, so a 401 for either means
* the gateway and the API disagree about a credential, which is a fault.
*/
function isCallerError(
error: unknown,
credentialType: McpCredentialType,
): boolean {
if (
error instanceof ContainerCheckDigitError ||
error instanceof TrackContainerError ||
error instanceof ToolInputError
) {
return true;
}
// The SDK's HTTP errors carry the response status; an error with none
// (network, timeout, a bug) never reached a Terminal49 answer.
const status = httpStatus(error);
if (status === undefined || !CALLER_ERROR_STATUSES.has(status)) return false;
if (status === 401) {
return credentialType === 'api_key' || credentialType === 'agent';
}
return true;
}

function wrapTool<TArgs>(
toolName: string,
credentialType: McpCredentialType,
handler: (args: TArgs, ctx: ServerContext) => Promise<unknown>,
buildResourceLinks?: (result: unknown, args: TArgs) => ResourceLinkContent[],
): (
Expand Down Expand Up @@ -1040,12 +1083,8 @@ function wrapTool<TArgs>(
};
} catch (error) {
const err = error as Error;
const isExpectedTrackingError =
toolName === 'track_container' &&
(error instanceof ContainerCheckDigitError ||
error instanceof TrackContainerError);
if (!isExpectedTrackingError) {
captureMcpException(error);
if (!isCallerError(error, credentialType)) {
captureMcpException(error, { tool: toolName, credentialType });
await flushMcpEvents();
}
// Log the real error for operators; never echo internal messages (which
Expand Down Expand Up @@ -1366,6 +1405,7 @@ export function createTerminal49McpServer(
// resolve that conditional type while InputArgs is still generic.
wrapTool(
definition.name,
session.credentialType,
(args: StandardSchemaWithJSON.InferOutput<InputArgs>, ctx) =>
handler(
args,
Expand Down
Loading
Loading