From 5e56cc560e6394c646643ed3760877bb9778eaa5 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Thu, 3 Dec 2026 09:31:02 -0500 Subject: [PATCH 1/3] fix(mcp): Keep the tool error and its feedback hint when the error message is read-only An aborted `fetch` throws a `DOMException`, whose `message` has only a getter, so adding the hint threw a `TypeError` that replaced the tool's error. The hint is now set as an own property, and values that can't take one (strings, plain objects, frozen errors) are rethrown as a new error with the hint. --- packages/mcp/src/errorHints.ts | 62 ++++++++++++++++++++++++---- packages/mcp/test/errorHints.test.ts | 61 +++++++++++++++++++++++++++ 2 files changed, 115 insertions(+), 8 deletions(-) diff --git a/packages/mcp/src/errorHints.ts b/packages/mcp/src/errorHints.ts index 96d2d1734ee6..a68ea9b66f70 100644 --- a/packages/mcp/src/errorHints.ts +++ b/packages/mcp/src/errorHints.ts @@ -1,5 +1,5 @@ import type { Event, EventHint } from '@sentry/core'; -import { fill, getGlobalScope, isObjectLike } from '@sentry/core'; +import { fill, getGlobalScope, isError, isObjectLike } from '@sentry/core'; import type { RegisteredFeedbackTool } from './feedback'; import { formatFeedbackHint, isFeedbackAvailable, isFeedbackToolVisible, withFeedbackTool } from './feedback'; @@ -185,18 +185,64 @@ async function callWithHint( return { ...result, content: [...result.content, { type: 'text', text: hint }] }; } 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}`; + throw addHintToError(error, name, hint, shouldHint); + } +} + +/** + * Returns what a failed tool call rethrows. That is the thrown error with the hint in its message, or a new error + * with the hint when the thrown value can't take one (a string, a plain object, a frozen error). + * `wrapMcpServerWithSentry` captures the thrown value inside this wrapper, so only the client sees the new error. + */ +function addHintToError(thrown: unknown, name: string, hint: string, shouldHint: ErrorHintFilter): unknown { + try { + const failure = toError(thrown); + if (!shouldHint(name, failure)) { + return thrown; } - throw error; + const message = originalMessages.get(failure) ?? failure.message; + const hinted = `${message}\n\n${hint}`; + if (failure === thrown && setMessage(failure, hinted)) { + originalMessages.set(failure, message); + + return failure; + } + + return Object.assign(new Error(hinted), { cause: thrown }); + } catch { + // A throwing `message` getter, `toString` or filter must not replace the tool's error. + return thrown; + } +} + +/** + * 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; + } + + return Object.assign(new Error(String(thrown)), isObjectLike(thrown) ? thrown : undefined, { cause: thrown }); +} + +/** + * Sets `message` as an own property, since `DOMException` and some error subclasses only have a getter for it. + * Returns false when the error can't take it, e.g. when it is frozen. + */ +function setMessage(error: Error, message: string): boolean { + try { + Object.defineProperty(error, 'message', { value: message, writable: true, configurable: true }); + + return true; + } catch { + return false; } } function mentions(failure: Error | ToolErrorResult, text: string): boolean { - if (failure instanceof Error) { + if (isError(failure)) { return failure.message.includes(text); } @@ -221,7 +267,7 @@ function addRestoreMessageProcessor(): void { function restoreOriginalMessage(event: Event, hint: EventHint): Event { const error = hint.originalException; - const original = error instanceof Error ? originalMessages.get(error) : undefined; + const original = isError(error) ? originalMessages.get(error) : undefined; if (original === undefined) { return event; } diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index 2599415e11de..a395a20b4e83 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -120,6 +120,67 @@ describe.each(['executor', 'handler', 'callback'] as const)('error hints (tool % expect(event.exception?.values?.[0]?.value).toBe('Upstream returned 500'); }); + it('adds the hint to errors whose message has only a getter, like an aborted fetch', async () => { + const server = createServer(callbackKey); + const error = new DOMException('This operation was aborted', 'AbortError'); + addFeedbackTool(server); + server.registerTool('aborted', {}, () => { + throw error; + }); + + await expect(server.call('aborted')).rejects.toBe(error); + expect(error.message).toBe(`This operation was aborted\n\n${HINT}`); + + const event = runEventProcessors({ exception: { values: [{ type: 'Error', value: error.message }] } }, error); + expect(event.exception?.values?.[0]?.value).toBe('This operation was aborted'); + }); + + it('throws a new error with the hint when the thrown value cannot take one', async () => { + const server = createServer(callbackKey); + const frozen = Object.freeze(new Error('Upstream returned 500')); + addFeedbackTool(server); + server.registerTool('frozen', {}, () => { + throw frozen; + }); + server.registerTool('string', {}, () => { + throw 'boom'; + }); + + await expect(server.call('frozen')).rejects.toMatchObject({ + message: `Upstream returned 500\n\n${HINT}`, + cause: frozen, + }); + await expect(server.call('string')).rejects.toMatchObject({ message: `boom\n\n${HINT}`, cause: 'boom' }); + expect(frozen.message).toBe('Upstream returned 500'); + }); + + it('reads the status of thrown non-Error objects', async () => { + const server = createServer(callbackKey); + const notFound = { status: 404, message: 'Not found' }; + addFeedbackTool(server); + server.registerTool('not-found', {}, () => { + throw notFound; + }); + + await expect(server.call('not-found')).rejects.toBe(notFound); + }); + + it('rethrows the original error when reading its message throws', async () => { + const server = createServer(callbackKey); + const error = new Error('Upstream returned 500'); + Object.defineProperty(error, 'message', { + get() { + throw new Error('no message'); + }, + }); + addFeedbackTool(server); + server.registerTool('broken', {}, () => { + throw error; + }); + + await expect(server.call('broken')).rejects.toBe(error); + }); + it('does not add the hint to the feedback tool itself', async () => { const server = createServer(callbackKey); addFeedbackTool(server); From 400d470ba238cac1a804584b996475e525556703 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Thu, 3 Dec 2026 09:40:14 -0500 Subject: [PATCH 2/3] fix(mcp): Add the feedback hint to the SDK's error result instead of the thrown error The hint now goes into the error result the MCP SDK builds from a thrown error, by wrapping its `tools/call` request handler, so the error itself is never modified. This also hints when the SDK rejects a tool's output against its `outputSchema`. --- .../node-express-mcp-v1/tests/mcp.test.ts | 5 +- .../node-express-mcp-v2/tests/mcp.test.ts | 5 +- packages/mcp/README.md | 7 +- packages/mcp/src/errorHints.ts | 137 +++++++-------- packages/mcp/test/errorHints.test.ts | 164 ++++++++++-------- 5 files changed, 171 insertions(+), 147 deletions(-) diff --git a/dev-packages/e2e-tests/test-applications/node-express-mcp-v1/tests/mcp.test.ts b/dev-packages/e2e-tests/test-applications/node-express-mcp-v1/tests/mcp.test.ts index 6c192d29222b..3bd4421ed339 100644 --- a/dev-packages/e2e-tests/test-applications/node-express-mcp-v1/tests/mcp.test.ts +++ b/dev-packages/e2e-tests/test-applications/node-express-mcp-v1/tests/mcp.test.ts @@ -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`.', }, ]); }); diff --git a/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/tests/mcp.test.ts b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/tests/mcp.test.ts index 382b8d951ff7..e17a5b1adb51 100644 --- a/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/tests/mcp.test.ts +++ b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/tests/mcp.test.ts @@ -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`.', }, ]); }); diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 50395f953480..024bbd2b7866 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -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, diff --git a/packages/mcp/src/errorHints.ts b/packages/mcp/src/errorHints.ts index a68ea9b66f70..5fb59dc5a11a 100644 --- a/packages/mcp/src/errorHints.ts +++ b/packages/mcp/src/errorHints.ts @@ -1,5 +1,4 @@ -import type { Event, EventHint } from '@sentry/core'; -import { fill, getGlobalScope, isError, isObjectLike } from '@sentry/core'; +import { fill, isError, isObjectLike } from '@sentry/core'; import type { RegisteredFeedbackTool } from './feedback'; import { formatFeedbackHint, isFeedbackAvailable, isFeedbackToolVisible, withFeedbackTool } from './feedback'; @@ -23,10 +22,12 @@ 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(); const wrappedTools = new WeakSet(); const hintCallbacks = new WeakSet(); -let processorAdded = false; +const hintRequestHandlers = new WeakSet(); +// What the tool callback did in a `tools/call` request, keyed by the request's abort signal. The SDK hands the callback +// the request context, but v2 copies it for multi-round calls, so the signal is the one object both sides share. +const callOutcomes = new WeakMap(); /** * The default `errorHints` filter. Skips upstream HTTP 4xx and JSON-RPC client errors, which are not the server's to fix. @@ -58,8 +59,8 @@ 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. + * A thrown error is left untouched: the hint goes into the error result the MCP SDK builds from it, by wrapping the + * SDK's `tools/call` request handler. Does nothing without a server. */ export function addErrorHints( feedbackTool: RegisteredFeedbackTool, @@ -70,8 +71,6 @@ export function addErrorHints( return; } - addRestoreMessageProcessor(); - const feedbackToolName = feedbackTool.name; const filterFailure: ErrorHintFilter = typeof errorHints === 'function' ? errorHints : (_toolName, failure) => shouldHintFeedback(failure); @@ -99,6 +98,7 @@ export function addErrorHints( wrap(name, tool); } } + wrapToolCallHandler(server, hint, shouldHint); for (const method of ['registerTool', 'tool']) { if (typeof server[method] !== 'function') { @@ -110,6 +110,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; }; @@ -145,8 +147,11 @@ function wrapRegisteredTool( } const wrapped = function (this: unknown, ...args: unknown[]): Promise { + // 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, () => - callWithHint(() => original.apply(this, args), toolName, hint, shouldHint), + callWithHint(() => original.apply(this, args), toolName, hint, shouldHint, signal), ); }; hintCallbacks.add(wrapped); @@ -176,44 +181,80 @@ async function callWithHint( name: string, hint: string, shouldHint: ErrorHintFilter, + signal: object | undefined, ): Promise { try { const result = await call(); + if (signal && !isErrorResult(result)) { + // The SDK can still reject it, against the tool's output schema. + callOutcomes.set(signal, { returned: true }); + } if (!isErrorResult(result) || !shouldHint(name, result)) { return result; } return { ...result, content: [...result.content, { type: 'text', text: hint }] }; } catch (error) { - throw addHintToError(error, name, hint, shouldHint); + if (signal) { + callOutcomes.set(signal, { thrown: error }); + } + + throw error; } } /** - * Returns what a failed tool call rethrows. That is the thrown error with the hint in its message, or a new error - * with the hint when the thrown value can't take one (a string, a plain object, a frozen error). - * `wrapMcpServerWithSentry` captures the thrown value inside this wrapper, so only the client sees the new error. + * Wraps the SDK's `tools/call` request handler, which turns a thrown tool error into an error result, so the hint is + * appended to that result. Also hints when the callback succeeded but the SDK rejected its output, a server bug. */ -function addHintToError(thrown: unknown, name: string, hint: string, shouldHint: ErrorHintFilter): unknown { - try { - const failure = toError(thrown); - if (!shouldHint(name, failure)) { - return thrown; - } +function wrapToolCallHandler(server: Record, hint: string, shouldHint: ErrorHintFilter): void { + // Private in both MCP SDKs: the low-level server's request handlers by method. + const protocol = server['server']; + const handlers: unknown = isObjectLike(protocol) ? protocol['_requestHandlers'] : undefined; + const handler: unknown = handlers instanceof Map ? handlers.get('tools/call') : undefined; + if (!(handlers instanceof Map) || typeof handler !== 'function' || hintRequestHandlers.has(handler as ToolCallback)) { + return; + } - const message = originalMessages.get(failure) ?? failure.message; - const hinted = `${message}\n\n${hint}`; - if (failure === thrown && setMessage(failure, hinted)) { - originalMessages.set(failure, message); + const wrapped = async function (this: unknown, request: unknown, context: unknown): Promise { + 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; + const params = isObjectLike(request) ? request['params'] : undefined; + const name = isObjectLike(params) ? params['name'] : undefined; + if (!outcome || !isErrorResult(result) || typeof name !== 'string') { + return result; + } - return failure; + try { + const failure = 'thrown' in outcome ? toError(outcome.thrown) : result; + if (!shouldHint(name, failure)) { + return result; + } + } catch { + // A throwing `message` getter, `toString` or filter must not replace the tool's result. + return result; } - return Object.assign(new Error(hinted), { cause: thrown }); - } catch { - // A throwing `message` getter, `toString` or filter must not replace the tool's error. - return thrown; + return { ...result, content: [...result.content, { type: 'text', text: hint }] }; + }; + hintRequestHandlers.add(wrapped); + handlers.set('tools/call', wrapped); +} + +/** + * 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; } + + const mcpReq = context['mcpReq']; + const signal = isObjectLike(mcpReq) ? mcpReq['signal'] : context['signal']; + + return isObjectLike(signal) ? signal : undefined; } /** @@ -227,20 +268,6 @@ function toError(thrown: unknown): Error { return Object.assign(new Error(String(thrown)), isObjectLike(thrown) ? thrown : undefined, { cause: thrown }); } -/** - * Sets `message` as an own property, since `DOMException` and some error subclasses only have a getter for it. - * Returns false when the error can't take it, e.g. when it is frozen. - */ -function setMessage(error: Error, message: string): boolean { - try { - Object.defineProperty(error, 'message', { value: message, writable: true, configurable: true }); - - return true; - } catch { - return false; - } -} - function mentions(failure: Error | ToolErrorResult, text: string): boolean { if (isError(failure)) { return failure.message.includes(text); @@ -254,29 +281,3 @@ function mentions(failure: Error | ToolErrorResult, text: string): boolean { function isErrorResult(result: unknown): result is ToolErrorResult { return isObjectLike(result) && result['isError'] === true && Array.isArray(result['content']); } - -function addRestoreMessageProcessor(): void { - if (processorAdded) { - return; - } - - processorAdded = true; - // The global scope applies to every client, including one created by a later `Sentry.init()`. - getGlobalScope().addEventProcessor(restoreOriginalMessage); -} - -function restoreOriginalMessage(event: Event, hint: EventHint): Event { - const error = hint.originalException; - const original = isError(error) ? originalMessages.get(error) : undefined; - if (original === undefined) { - return event; - } - - for (const exception of event.exception?.values ?? []) { - if (exception.value === (error as Error).message) { - exception.value = original; - } - } - - return event; -} diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index a395a20b4e83..9db3d8898edf 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -1,5 +1,4 @@ -import type { Event, EventProcessor } from '@sentry/core'; -import { getClient, getGlobalScope, withScope } from '@sentry/core'; +import { getClient, withScope } from '@sentry/core'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { addFeedbackTool } from '../src/addFeedbackTool'; import type { ToolErrorResult } from '../src/errorHints'; @@ -16,14 +15,45 @@ const HINT = type Callback = (...args: unknown[]) => unknown; +type CallbackKey = 'executor' | 'handler' | 'callback'; + // Mirrors where each MCP SDK keeps a registered tool's callback: `executor` in v2, `handler` in v1, and `callback` in -// v1 before 1.24.0. -function createServer(callbackKey: 'executor' | 'handler' | 'callback') { - const _registeredTools: Record> = {}; +// v1 before 1.24.0. Like the SDKs, the `tools/call` handler is set with the first tool, runs the callback with the +// request context, and turns a thrown error into an error result. +function createServer(callbackKey: CallbackKey) { + const _registeredTools: Record> = {}; + const _requestHandlers = new Map(); + const toolCallHandler = async (request: unknown, context: unknown): Promise => { + const { name, arguments: args } = (request as { params: { name: string; arguments?: Record } }) + .params; + const tool = _registeredTools[name]!; + try { + if (tool.requiredInput && !args?.[tool.requiredInput as string]) { + throw new Error(`Input validation error: Invalid arguments for tool ${name}`); + } + const result = await (tool[callbackKey] as Callback)(args, context); + if (tool.requiresStructuredContent && !(result as { structuredContent?: unknown }).structuredContent) { + throw new Error(`Output validation error: Tool ${name} has an output schema but no structured content`); + } + + return result; + } catch (error) { + return { + isError: true, + content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }], + }; + } + }; const server = { _registeredTools, - registerTool(name: string, _config: unknown, callback: Callback) { - const tool: Record = { + server: { _requestHandlers }, + registerTool( + name: string, + config: { requiredInput?: string; requiresStructuredContent?: boolean }, + callback: Callback, + ) { + const tool: Record = { + ...config, [callbackKey]: callback, // Like the SDKs, `update({ callback })` puts the new function under the same key update: (updates: unknown) => { @@ -34,23 +64,25 @@ function createServer(callbackKey: 'executor' | 'handler' | 'callback') { }, }; _registeredTools[name] = tool; - return tool; + if (!_requestHandlers.has('tools/call')) { + _requestHandlers.set('tools/call', toolCallHandler); + } + return tool as { update: Callback }; }, - call(name: string, ...args: unknown[]) { - return Promise.resolve(_registeredTools[name]![callbackKey]!(...args)); + call(name: string, args?: Record) { + const signal = new AbortController().signal; + // v1 passes `extra` with the signal, v2 passes `ctx` with it under `mcpReq` + const context = callbackKey === 'executor' ? { mcpReq: { signal } } : { signal }; + + return Promise.resolve(_requestHandlers.get('tools/call')!({ params: { name, arguments: args } }, context)); }, }; return server; } -function runEventProcessors(event: Event, originalException: unknown): Event { - const { eventProcessors } = getGlobalScope().getScopeData(); - - return eventProcessors.reduce( - (current, processor: EventProcessor) => processor(current, { originalException }) as Event, - event, - ); +function errorResult(...texts: string[]) { + return { isError: true, content: texts.map(text => ({ type: 'text', text })) }; } describe.each(['executor', 'handler', 'callback'] as const)('error hints (tool %s)', callbackKey => { @@ -105,7 +137,7 @@ describe.each(['executor', 'handler', 'callback'] as const)('error hints (tool % await expect(server.call('ok')).resolves.toEqual({ content: [{ type: 'text', text: 'done' }] }); }); - it('adds the hint to thrown errors and restores the original message on the Sentry event', async () => { + it('adds the hint to the error result built from a thrown error and leaves the error alone', async () => { const server = createServer(callbackKey); const error = new Error('Upstream returned 500'); addFeedbackTool(server); @@ -113,72 +145,70 @@ describe.each(['executor', 'handler', 'callback'] as const)('error hints (tool % throw error; }); - await expect(server.call('throws')).rejects.toBe(error); - expect(error.message).toBe(`Upstream returned 500\n\n${HINT}`); - - const event = runEventProcessors({ exception: { values: [{ type: 'Error', value: error.message }] } }, error); - expect(event.exception?.values?.[0]?.value).toBe('Upstream returned 500'); + await expect(server.call('throws')).resolves.toEqual(errorResult('Upstream returned 500', HINT)); + expect(error.message).toBe('Upstream returned 500'); }); - it('adds the hint to errors whose message has only a getter, like an aborted fetch', async () => { + it.each([ + ['an aborted fetch', new DOMException('This operation was aborted', 'AbortError'), 'This operation was aborted'], + ['a frozen error', Object.freeze(new Error('Upstream returned 500')), 'Upstream returned 500'], + ['a string', 'boom', 'boom'], + ])('adds the hint when the tool throws %s', async (_label, thrown, message) => { const server = createServer(callbackKey); - const error = new DOMException('This operation was aborted', 'AbortError'); addFeedbackTool(server); - server.registerTool('aborted', {}, () => { - throw error; + server.registerTool('throws', {}, () => { + throw thrown; }); - await expect(server.call('aborted')).rejects.toBe(error); - expect(error.message).toBe(`This operation was aborted\n\n${HINT}`); - - const event = runEventProcessors({ exception: { values: [{ type: 'Error', value: error.message }] } }, error); - expect(event.exception?.values?.[0]?.value).toBe('This operation was aborted'); + await expect(server.call('throws')).resolves.toEqual(errorResult(message, HINT)); }); - it('throws a new error with the hint when the thrown value cannot take one', async () => { + it('reads the status of thrown non-Error objects', async () => { const server = createServer(callbackKey); - const frozen = Object.freeze(new Error('Upstream returned 500')); addFeedbackTool(server); - server.registerTool('frozen', {}, () => { - throw frozen; - }); - server.registerTool('string', {}, () => { - throw 'boom'; + server.registerTool('not-found', {}, () => { + throw { status: 404, message: 'Not found' }; }); - await expect(server.call('frozen')).rejects.toMatchObject({ - message: `Upstream returned 500\n\n${HINT}`, - cause: frozen, - }); - await expect(server.call('string')).rejects.toMatchObject({ message: `boom\n\n${HINT}`, cause: 'boom' }); - expect(frozen.message).toBe('Upstream returned 500'); + await expect(server.call('not-found')).resolves.toEqual(errorResult('[object Object]')); }); - it('reads the status of thrown non-Error objects', async () => { + it('adds the hint when the SDK rejects the output of a tool, but not its input', async () => { const server = createServer(callbackKey); - const notFound = { status: 404, message: 'Not found' }; addFeedbackTool(server); - server.registerTool('not-found', {}, () => { - throw notFound; + server.registerTool('bad-output', { requiresStructuredContent: true }, () => ({ content: [] })); + server.registerTool('needs-input', { requiredInput: 'query' }, () => ({ content: [] })); + + await expect(server.call('bad-output')).resolves.toEqual( + errorResult('Output validation error: Tool bad-output has an output schema but no structured content', HINT), + ); + await expect(server.call('needs-input')).resolves.toEqual( + errorResult('Input validation error: Invalid arguments for tool needs-input'), + ); + }); + + it('adds the hint to thrown errors of tools registered before addFeedbackTool', async () => { + const server = createServer(callbackKey); + server.registerTool('throws', {}, () => { + throw new Error('Upstream returned 500'); }); + addFeedbackTool(server); - await expect(server.call('not-found')).rejects.toBe(notFound); + await expect(server.call('throws')).resolves.toEqual(errorResult('Upstream returned 500', HINT)); }); - it('rethrows the original error when reading its message throws', async () => { + it('leaves the error result alone when the errorHints filter throws', async () => { const server = createServer(callbackKey); - const error = new Error('Upstream returned 500'); - Object.defineProperty(error, 'message', { - get() { - throw new Error('no message'); + addFeedbackTool(server, { + errorHints: () => { + throw new Error('filter broke'); }, }); - addFeedbackTool(server); - server.registerTool('broken', {}, () => { - throw error; + server.registerTool('throws', {}, () => { + throw new Error('Upstream returned 500'); }); - await expect(server.call('broken')).rejects.toBe(error); + await expect(server.call('throws')).resolves.toEqual(errorResult('Upstream returned 500')); }); it('does not add the hint to the feedback tool itself', async () => { @@ -206,10 +236,8 @@ describe.each(['executor', 'handler', 'callback'] as const)('error hints (tool % throw upstreamDown; }); - await expect(server.call('rate-limited')).rejects.toBe(rateLimited); - await expect(server.call('upstream-down')).rejects.toBe(upstreamDown); - expect(rateLimited.message).toBe('Too many requests'); - expect(upstreamDown.message).toBe(`Bad gateway\n\n${HINT}`); + await expect(server.call('rate-limited')).resolves.toEqual(errorResult('Too many requests')); + await expect(server.call('upstream-down')).resolves.toEqual(errorResult('Bad gateway', HINT)); }); it('skips failures the errorHints filter rejects', async () => { @@ -221,8 +249,7 @@ describe.each(['executor', 'handler', 'callback'] as const)('error hints (tool % throw error; }); - await expect(server.call('custom')).rejects.toBe(error); - expect(error.message).toBe('query is required'); + await expect(server.call('custom')).resolves.toEqual(errorResult('query is required')); }); it('passes thrown errors and error results to the errorHints filter', async () => { @@ -243,7 +270,7 @@ describe.each(['executor', 'handler', 'callback'] as const)('error hints (tool % }); server.registerTool('returns', {}, () => returned); - await expect(server.call('throws')).rejects.toBe(thrown); + await server.call('throws'); await server.call('returns'); expect(failures).toEqual([thrown, returned]); @@ -357,10 +384,7 @@ describe.each(['executor', 'handler', 'callback'] as const)('error hints (tool % }); await expect(server.call('hinted-result')).resolves.toEqual(ownHint); - await expect(server.call('hinted-throw')).rejects.toBe(error); - expect(error.message).toBe( - "Upstream returned 500. If retrying does not help, report it to this server's team with `submit_feedback`.", - ); + await expect(server.call('hinted-throw')).resolves.toEqual(errorResult(error.message)); }); it('never modifies successful results, structured or not', async () => { From a8e8d9b251cb3c64303f775fa136dbefb9f0b4a8 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Thu, 3 Dec 2026 11:12:30 -0500 Subject: [PATCH 3/3] fix(mcp): Add every feedback hint in the tools/call wrapper Returned error results now get the hint in the same place as thrown errors and rejected output, after the SDK's own changes to the result. Before, the hint was added first, so MCP SDK v2 skipped the text it writes for non-object structuredContent and the error details never reached the client. The tool callback now only records what happened. --- packages/mcp/src/errorHints.ts | 80 +++++++++----------- packages/mcp/test/createFeedbackTool.test.ts | 48 ++++++++---- packages/mcp/test/errorHints.test.ts | 29 ++++++- 3 files changed, 93 insertions(+), 64 deletions(-) diff --git a/packages/mcp/src/errorHints.ts b/packages/mcp/src/errorHints.ts index 5fb59dc5a11a..8a6d9ae7c44b 100644 --- a/packages/mcp/src/errorHints.ts +++ b/packages/mcp/src/errorHints.ts @@ -25,9 +25,8 @@ const JSON_RPC_CLIENT_ERROR_CODES = new Set([-32700, -32600, -32601, -32602, -32 const wrappedTools = new WeakSet(); const hintCallbacks = new WeakSet(); const hintRequestHandlers = new WeakSet(); -// What the tool callback did in a `tools/call` request, keyed by the request's abort signal. The SDK hands the callback -// the request context, but v2 copies it for multi-round calls, so the signal is the one object both sides share. -const callOutcomes = new WeakMap(); +// Keyed by the request's abort signal: v2 copies the request context for multi-round calls, the signal survives. +const callOutcomes = new WeakMap(); /** * The default `errorHints` filter. Skips upstream HTTP 4xx and JSON-RPC client errors, which are not the server's to fix. @@ -59,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`. - * A thrown error is left untouched: the hint goes into the error result the MCP SDK builds from it, by wrapping the - * SDK's `tools/call` request handler. 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, @@ -87,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); } }; @@ -122,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; } @@ -150,9 +142,7 @@ function wrapRegisteredTool( // 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, () => - callWithHint(() => original.apply(this, args), toolName, hint, shouldHint, signal), - ); + return withFeedbackTool(feedbackTool, () => callAndRecord(() => original.apply(this, args), toolName, signal)); }; hintCallbacks.add(wrapped); tool[key] = wrapped; @@ -176,27 +166,20 @@ function wrapRegisteredTool( } } -async function callWithHint( - call: () => unknown, - name: string, - hint: string, - shouldHint: ErrorHintFilter, - signal: object | undefined, -): Promise { +/** + * 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 { try { const result = await call(); - if (signal && !isErrorResult(result)) { - // The SDK can still reject it, against the tool's output schema. - callOutcomes.set(signal, { returned: true }); - } - 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 (signal) { - callOutcomes.set(signal, { thrown: error }); + callOutcomes.set(signal, { name, thrown: error }); } throw error; @@ -204,15 +187,13 @@ async function callWithHint( } /** - * Wraps the SDK's `tools/call` request handler, which turns a thrown tool error into an error result, so the hint is - * appended to that result. Also hints when the callback succeeded but the SDK rejected its output, a server bug. + * 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, hint: string, shouldHint: ErrorHintFilter): void { - // Private in both MCP SDKs: the low-level server's request handlers by method. - const protocol = server['server']; - const handlers: unknown = isObjectLike(protocol) ? protocol['_requestHandlers'] : undefined; - const handler: unknown = handlers instanceof Map ? handlers.get('tools/call') : undefined; - if (!(handlers instanceof Map) || typeof handler !== 'function' || hintRequestHandlers.has(handler as ToolCallback)) { + const handlers = getRequestHandlers(server); + const handler: unknown = handlers?.get('tools/call'); + if (!handlers || typeof handler !== 'function' || hintRequestHandlers.has(handler as ToolCallback)) { return; } @@ -221,15 +202,14 @@ function wrapToolCallHandler(server: Record, hint: string, shou 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; - const params = isObjectLike(request) ? request['params'] : undefined; - const name = isObjectLike(params) ? params['name'] : undefined; - if (!outcome || !isErrorResult(result) || typeof name !== 'string') { + if (!outcome || !isErrorResult(result)) { return result; } try { - const failure = 'thrown' in outcome ? toError(outcome.thrown) : result; - if (!shouldHint(name, failure)) { + const failure = + 'thrown' in outcome ? toError(outcome.thrown) : isErrorResult(outcome.returned) ? outcome.returned : result; + if (!shouldHint(outcome.name, failure)) { return result; } } catch { @@ -237,12 +217,24 @@ function wrapToolCallHandler(server: Record, hint: string, shou return result; } - return { ...result, content: [...result.content, { type: 'text', text: hint }] }; + return withHint(result, hint); }; hintRequestHandlers.add(wrapped); handlers.set('tools/call', wrapped); } +function getRequestHandlers(server: Record): Map | 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 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. */ diff --git a/packages/mcp/test/createFeedbackTool.test.ts b/packages/mcp/test/createFeedbackTool.test.ts index ff670b2862b0..0cf3942d6a0e 100644 --- a/packages/mcp/test/createFeedbackTool.test.ts +++ b/packages/mcp/test/createFeedbackTool.test.ts @@ -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 = {}; + const _requestHandlers = new Map 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({ @@ -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 = {}; - 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 }); @@ -100,17 +121,12 @@ 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 = {}; - 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`."; @@ -118,13 +134,13 @@ describe('createFeedbackTool', () => { 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 }], }); @@ -132,7 +148,7 @@ describe('createFeedbackTool', () => { 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: [] }); }); diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index 9db3d8898edf..1cae6478dab4 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -17,9 +17,8 @@ type Callback = (...args: unknown[]) => unknown; type CallbackKey = 'executor' | 'handler' | 'callback'; -// Mirrors where each MCP SDK keeps a registered tool's callback: `executor` in v2, `handler` in v1, and `callback` in -// v1 before 1.24.0. Like the SDKs, the `tools/call` handler is set with the first tool, runs the callback with the -// request context, and turns a thrown error into an error result. +// Keeps the callback where each MCP SDK does: `executor` in v2, `handler` in v1, `callback` in v1 before 1.24.0. +// Mimics the SDK's `tools/call`: thrown errors become results, plus v2's text for non-object `structuredContent`. function createServer(callbackKey: CallbackKey) { const _registeredTools: Record> = {}; const _requestHandlers = new Map(); @@ -32,9 +31,19 @@ function createServer(callbackKey: CallbackKey) { throw new Error(`Input validation error: Invalid arguments for tool ${name}`); } const result = await (tool[callbackKey] as Callback)(args, context); - if (tool.requiresStructuredContent && !(result as { structuredContent?: unknown }).structuredContent) { + const { content, structuredContent } = result as { + content: Array<{ type: string }>; + structuredContent?: unknown; + }; + if (tool.requiresStructuredContent && !structuredContent) { throw new Error(`Output validation error: Tool ${name} has an output schema but no structured content`); } + if (Array.isArray(structuredContent) && !content.some(block => block.type === 'text')) { + return { + ...(result as object), + content: [...content, { type: 'text', text: JSON.stringify(structuredContent) }], + }; + } return result; } catch (error) { @@ -163,6 +172,18 @@ describe.each(['executor', 'handler', 'callback'] as const)('error hints (tool % await expect(server.call('throws')).resolves.toEqual(errorResult(message, HINT)); }); + it('adds the hint after the text the SDK writes for structuredContent', async () => { + const server = createServer(callbackKey); + addFeedbackTool(server); + server.registerTool('quota', {}, () => ({ + isError: true, + content: [], + structuredContent: ['quota exceeded', 'retry in 60s'], + })); + + await expect(server.call('quota')).resolves.toMatchObject(errorResult('["quota exceeded","retry in 60s"]', HINT)); + }); + it('reads the status of thrown non-Error objects', async () => { const server = createServer(callbackKey); addFeedbackTool(server);