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
Original file line number Diff line number Diff line change
Expand Up @@ -169,11 +169,10 @@ test('auto-instruments a legacy MCP SDK v1 server (no manual wrap)', async ({ ba

expect(result.isError).toBe(true);
expect(result.content).toEqual([
{ type: 'text', text: expect.stringContaining('intentional error for span status testing') },
{
type: 'text',
text: expect.stringContaining(
'intentional error for span status testing\n\nIf this keeps failing after you adjust your request, report it to the Echo-V1 team with `submit_feedback`.',
),
text: 'If this keeps failing after you adjust your request, report it to the Echo-V1 team with `submit_feedback`.',
},
]);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,11 +205,10 @@ test('auto-instruments a stable MCP SDK v2 server (no manual wrap)', async ({ ba

expect(result.isError).toBe(true);
expect(result.content).toEqual([
{ type: 'text', text: expect.stringContaining('intentional error for span status testing') },
{
type: 'text',
text: expect.stringContaining(
'intentional error for span status testing\n\nIf this keeps failing after you adjust your request, report it to the Echo-V2 team with `submit_feedback`.',
),
text: 'If this keeps failing after you adjust your request, report it to the Echo-V2 team with `submit_feedback`.',
},
]);
});
Expand Down
7 changes: 4 additions & 3 deletions packages/mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,10 @@ your errors yourself. For a handler of your own, use `captureAgentFeedback`.
### Pointing agents at the tool

Agents that are stuck rarely go looking for a feedback tool, so `addFeedbackTool` also adds a hint to the errors of
your other tools: "If this keeps failing after you adjust your request, report it to this server's team with `submit_feedback`." Thrown errors
get the hint in their message, and Sentry still records the original message. Error results get it as an extra text
block, so `structuredContent` is never touched. Successful results are never modified, and errors that already mention
your other tools: "If this keeps failing after you adjust your request, report it to this server's team with `submit_feedback`." The hint is
an extra text block in the error result, whether the tool returned it, threw, or returned output that fails its
`outputSchema`. Thrown errors are not modified, so Sentry records them as they are, and `structuredContent` is never
touched. Successful results are never modified, and errors that already mention
the feedback tool don't get a second hint.

By default, `shouldHintFeedback` skips failures that are not yours to fix: upstream HTTP 4xx errors (bad input, auth,
Expand Down
151 changes: 95 additions & 56 deletions packages/mcp/src/errorHints.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { Event, EventHint } from '@sentry/core';
import { fill, getGlobalScope, isObjectLike } from '@sentry/core';
import { fill, isError, isObjectLike } from '@sentry/core';
import type { RegisteredFeedbackTool } from './feedback';
import { formatFeedbackHint, isFeedbackAvailable, isFeedbackToolVisible, withFeedbackTool } from './feedback';

Expand All @@ -23,10 +22,11 @@ type ToolCallback = (...args: unknown[]) => unknown;
// Client errors per the MCP conventions; mirrors `isJsonRpcServerError` in `@sentry/core`'s MCP integration.
const JSON_RPC_CLIENT_ERROR_CODES = new Set([-32700, -32600, -32601, -32602, -32002]);

const originalMessages = new WeakMap<Error, string>();
const wrappedTools = new WeakSet<object>();
const hintCallbacks = new WeakSet<ToolCallback>();
let processorAdded = false;
const hintRequestHandlers = new WeakSet<ToolCallback>();
// Keyed by the request's abort signal: v2 copies the request context for multi-round calls, the signal survives.
const callOutcomes = new WeakMap<object, { name: string } & ({ thrown: unknown } | { returned: unknown })>();

/**
* The default `errorHints` filter. Skips upstream HTTP 4xx and JSON-RPC client errors, which are not the server's to fix.
Expand Down Expand Up @@ -58,8 +58,7 @@ export function shouldHintFeedback(failure: unknown): boolean {
/**
* Wraps every other tool on the server, registered before or after, so `feedbackHint` inside their calls uses this
* feedback tool, and adds the feedback hint to their errors unless `errorHints` is `false`.
* Thrown errors carry it in their message because MCP SDKs build the error result from the message alone;
* an event processor restores the original message for Sentry. Does nothing without a server.
* The hint goes into the error result the client gets; thrown errors are not modified. Does nothing without a server.
*/
export function addErrorHints(
feedbackTool: RegisteredFeedbackTool,
Expand All @@ -70,8 +69,6 @@ export function addErrorHints(
return;
}

addRestoreMessageProcessor();

const feedbackToolName = feedbackTool.name;
const filterFailure: ErrorHintFilter =
typeof errorHints === 'function' ? errorHints : (_toolName, failure) => shouldHintFeedback(failure);
Expand All @@ -88,7 +85,7 @@ export function addErrorHints(
const hint = formatFeedbackHint(feedbackToolName, feedbackTool.recipient);
const wrap = (name: unknown, tool: unknown): void => {
if (typeof name === 'string' && name !== feedbackToolName) {
wrapRegisteredTool(name, tool, feedbackTool, hint, shouldHint);
wrapRegisteredTool(name, tool, feedbackTool);
}
};

Expand All @@ -99,6 +96,7 @@ export function addErrorHints(
wrap(name, tool);
}
}
wrapToolCallHandler(server, hint, shouldHint);

for (const method of ['registerTool', 'tool']) {
if (typeof server[method] !== 'function') {
Expand All @@ -110,6 +108,8 @@ export function addErrorHints(
const registered = original.call(this, name, ...rest);
const tools = server['_registeredTools'];
wrap(name, registered ?? (isObjectLike(tools) && typeof name === 'string' ? tools[name] : undefined));
// The SDK sets its `tools/call` handler when the first tool is registered.
wrapToolCallHandler(server, hint, shouldHint);

return registered;
};
Expand All @@ -120,13 +120,7 @@ export function addErrorHints(
// MCP SDK v2 calls a registered tool's `executor`, v1 calls its `handler` (`callback` before 1.24.0).
const TOOL_CALLBACK_KEYS = ['executor', 'handler', 'callback'] as const;

function wrapRegisteredTool(
name: string,
tool: unknown,
feedbackTool: RegisteredFeedbackTool,
hint: string,
shouldHint: ErrorHintFilter,
): void {
function wrapRegisteredTool(name: string, tool: unknown, feedbackTool: RegisteredFeedbackTool): void {
if (!isObjectLike(tool) || wrappedTools.has(tool)) {
return;
}
Expand All @@ -145,9 +139,10 @@ function wrapRegisteredTool(
}

const wrapped = function (this: unknown, ...args: unknown[]): Promise<unknown> {
return withFeedbackTool(feedbackTool, () =>
callWithHint(() => original.apply(this, args), toolName, hint, shouldHint),
);
// The SDK passes the request context last, after the arguments when the tool has an input schema.
const signal = getRequestSignal(args[args.length - 1]);

return withFeedbackTool(feedbackTool, () => callAndRecord(() => original.apply(this, args), toolName, signal));
};
hintCallbacks.add(wrapped);
tool[key] = wrapped;
Expand All @@ -171,66 +166,110 @@ function wrapRegisteredTool(
}
}

async function callWithHint(
call: () => unknown,
name: string,
hint: string,
shouldHint: ErrorHintFilter,
): Promise<unknown> {
/**
* Runs a tool callback and records what it did, for the `tools/call` wrapper that adds the hint.
*/
async function callAndRecord(call: () => unknown, name: string, signal: object | undefined): Promise<unknown> {
try {
const result = await call();
if (!isErrorResult(result) || !shouldHint(name, result)) {
return result;
if (signal) {
callOutcomes.set(signal, { name, returned: result });
}

return { ...result, content: [...result.content, { type: 'text', text: hint }] };
return result;
} catch (error) {
if (error instanceof Error && shouldHint(name, error)) {
const message = originalMessages.get(error) ?? error.message;
originalMessages.set(error, message);
error.message = `${message}\n\n${hint}`;
if (signal) {
callOutcomes.set(signal, { name, thrown: error });
}

throw error;
}
}

function mentions(failure: Error | ToolErrorResult, text: string): boolean {
if (failure instanceof Error) {
return failure.message.includes(text);
/**
* Wraps the SDK's `tools/call` handler, so every error result the client gets ends with the hint. Appending after the
* SDK keeps its own changes to the result, such as its text for `structuredContent`.
*/
function wrapToolCallHandler(server: Record<string, unknown>, hint: string, shouldHint: ErrorHintFilter): void {
const handlers = getRequestHandlers(server);
const handler: unknown = handlers?.get('tools/call');
if (!handlers || typeof handler !== 'function' || hintRequestHandlers.has(handler as ToolCallback)) {
return;
}

return failure.content.some(
block => isObjectLike(block) && typeof block['text'] === 'string' && block['text'].includes(text),
);
const wrapped = async function (this: unknown, request: unknown, context: unknown): Promise<unknown> {
const result = await (handler as ToolCallback).call(this, request, context);
const signal = getRequestSignal(context);
// Only calls whose callback ran: input validation and unknown tools are the client's to fix.
const outcome = signal ? callOutcomes.get(signal) : undefined;
if (!outcome || !isErrorResult(result)) {
return result;
}

try {
const failure =
'thrown' in outcome ? toError(outcome.thrown) : isErrorResult(outcome.returned) ? outcome.returned : result;
if (!shouldHint(outcome.name, failure)) {
return result;
}
} catch {
// A throwing `message` getter, `toString` or filter must not replace the tool's result.
return result;
}

return withHint(result, hint);
};
hintRequestHandlers.add(wrapped);
handlers.set('tools/call', wrapped);
}

function isErrorResult(result: unknown): result is ToolErrorResult {
return isObjectLike(result) && result['isError'] === true && Array.isArray(result['content']);
function getRequestHandlers(server: Record<string, unknown>): Map<string, unknown> | undefined {
const protocol = server['server'];
// Private in both MCP SDKs.
const handlers: unknown = isObjectLike(protocol) ? protocol['_requestHandlers'] : undefined;

return handlers instanceof Map ? handlers : undefined;
}

function addRestoreMessageProcessor(): void {
if (processorAdded) {
return;
function withHint(result: ToolErrorResult, hint: string): ToolErrorResult {
return { ...result, content: [...result.content, { type: 'text', text: hint }] };
}

/**
* Returns the abort signal of the request a tool call belongs to: `extra.signal` in MCP SDK v1, `ctx.mcpReq.signal` in v2.
*/
function getRequestSignal(context: unknown): object | undefined {
if (!isObjectLike(context)) {
return undefined;
}

processorAdded = true;
// The global scope applies to every client, including one created by a later `Sentry.init()`.
getGlobalScope().addEventProcessor(restoreOriginalMessage);
const mcpReq = context['mcpReq'];
const signal = isObjectLike(mcpReq) ? mcpReq['signal'] : context['signal'];

return isObjectLike(signal) ? signal : undefined;
}

function restoreOriginalMessage(event: Event, hint: EventHint): Event {
const error = hint.originalException;
const original = error instanceof Error ? originalMessages.get(error) : undefined;
if (original === undefined) {
return event;
/**
* Turns a thrown non-Error into an Error for the `errorHints` filter, keeping fields like `status` and `code` it reads.
*/
function toError(thrown: unknown): Error {
if (isError(thrown)) {
return thrown;
}

for (const exception of event.exception?.values ?? []) {
if (exception.value === (error as Error).message) {
exception.value = original;
}
return Object.assign(new Error(String(thrown)), isObjectLike(thrown) ? thrown : undefined, { cause: thrown });
}

function mentions(failure: Error | ToolErrorResult, text: string): boolean {
if (isError(failure)) {
return failure.message.includes(text);
}

return event;
return failure.content.some(
block => isObjectLike(block) && typeof block['text'] === 'string' && block['text'].includes(text),
);
}

function isErrorResult(result: unknown): result is ToolErrorResult {
return isObjectLike(result) && result['isError'] === true && Array.isArray(result['content']);
}
48 changes: 32 additions & 16 deletions packages/mcp/test/createFeedbackTool.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,32 @@ const report = {
description: 'No p95 tool.',
} as const;

type Handler = (...args: never[]) => unknown;

// Like the MCP SDKs: the `tools/call` handler is set with the first tool and passes the request context on.
function createServer() {
const tools: Record<string, { handler: Handler; enabled?: boolean }> = {};
const _requestHandlers = new Map<string, (request: { params: { name: string } }, context: unknown) => unknown>();
const server = {
_registeredTools: tools,
server: { _requestHandlers },
registerTool: (name: string, _config: unknown, handler: Handler) => {
tools[name] = { handler };
if (!_requestHandlers.has('tools/call')) {
_requestHandlers.set('tools/call', (request, context) =>
tools[request.params.name]!.handler(undefined as never, context as never),
);
}

return tools[name];
},
call: (name: string) =>
_requestHandlers.get('tools/call')!({ params: { name } }, { signal: new AbortController().signal }),
};

return { server, tools };
}

describe('createFeedbackTool', () => {
beforeEach(() => {
vi.mocked(getClient).mockReturnValue({
Expand Down Expand Up @@ -79,12 +105,7 @@ describe('createFeedbackTool', () => {
])(
"adds error hints to the server's other tools when given the server (errorHints: %s)",
async (errorHints, hinted) => {
type Handler = (...args: never[]) => unknown;
const tools: Record<string, { handler: Handler }> = {};
const server = {
_registeredTools: tools,
registerTool: (name: string, _config: unknown, handler: Handler) => (tools[name] = { handler }),
};
const { server } = createServer();
const failed = { isError: true, content: [{ type: 'text', text: 'Upstream returned 500.' }] };

const tool = createFeedbackTool({ serverName: 'Orders', server, errorHints });
Expand All @@ -100,39 +121,34 @@ describe('createFeedbackTool', () => {
},
]
: failed.content;
expect(await tools['search']!.handler()).toEqual({ ...failed, content });
expect(await server.call('search')).toEqual({ ...failed, content });
},
);

it('adds no hints while the tool is not registered or is disabled on the server', async () => {
type Handler = (...args: never[]) => unknown;
const tools: Record<string, { handler: Handler; enabled?: boolean }> = {};
const server = {
_registeredTools: tools,
registerTool: (name: string, _config: unknown, handler: Handler) => (tools[name] = { handler }),
};
const { server, tools } = createServer();
const failed = { isError: true, content: [{ type: 'text', text: 'Upstream returned 500.' }] };
const hint =
"If this keeps failing after you adjust your request, report it to this server's team with `submit_feedback`.";

const tool = createFeedbackTool({ server });
server.registerTool('search', {}, () => failed);

expect(await tools['search']!.handler()).toEqual(failed);
expect(await server.call('search')).toEqual(failed);
expect(feedbackHint()).toBe('');
expect(withFeedbackHint({ content: [] })).toEqual({ content: [] });

server.registerTool(tool.name, tool.config, tool.handler);

expect(await tools['search']!.handler()).toEqual({
expect(await server.call('search')).toEqual({
...failed,
content: [...failed.content, { type: 'text', text: hint }],
});
expect(feedbackHint()).toBe(hint);

tools[tool.name]!.enabled = false;

expect(await tools['search']!.handler()).toEqual(failed);
expect(await server.call('search')).toEqual(failed);
expect(feedbackHint()).toBe('');
expect(withFeedbackHint({ content: [] })).toEqual({ content: [] });
});
Expand Down
Loading
Loading