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 96d2d1734ee6..8a6d9ae7c44b 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, 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,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(); const wrappedTools = new WeakSet(); const hintCallbacks = new WeakSet(); -let processorAdded = false; +const hintRequestHandlers = new WeakSet(); +// 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. @@ -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, @@ -70,8 +69,6 @@ export function addErrorHints( return; } - addRestoreMessageProcessor(); - const feedbackToolName = feedbackTool.name; const filterFailure: ErrorHintFilter = typeof errorHints === 'function' ? errorHints : (_toolName, failure) => shouldHintFeedback(failure); @@ -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); } }; @@ -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') { @@ -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; }; @@ -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; } @@ -145,9 +139,10 @@ function wrapRegisteredTool( } const wrapped = function (this: unknown, ...args: unknown[]): Promise { - 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; @@ -171,66 +166,110 @@ function wrapRegisteredTool( } } -async function callWithHint( - call: () => unknown, - name: string, - hint: string, - shouldHint: ErrorHintFilter, -): 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 (!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, 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 { + 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): 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 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']); } 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 2599415e11de..1cae6478dab4 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,54 @@ const HINT = type Callback = (...args: unknown[]) => unknown; -// 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> = {}; +type CallbackKey = 'executor' | 'handler' | 'callback'; + +// 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(); + 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); + 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) { + 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 +73,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 +146,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,11 +154,82 @@ 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}`); + await expect(server.call('throws')).resolves.toEqual(errorResult('Upstream returned 500', HINT)); + expect(error.message).toBe('Upstream returned 500'); + }); - const event = runEventProcessors({ exception: { values: [{ type: 'Error', value: error.message }] } }, error); - expect(event.exception?.values?.[0]?.value).toBe('Upstream returned 500'); + 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); + addFeedbackTool(server); + server.registerTool('throws', {}, () => { + throw thrown; + }); + + 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); + server.registerTool('not-found', {}, () => { + throw { status: 404, message: 'Not found' }; + }); + + await expect(server.call('not-found')).resolves.toEqual(errorResult('[object Object]')); + }); + + it('adds the hint when the SDK rejects the output of a tool, but not its input', async () => { + const server = createServer(callbackKey); + addFeedbackTool(server); + 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('throws')).resolves.toEqual(errorResult('Upstream returned 500', HINT)); + }); + + it('leaves the error result alone when the errorHints filter throws', async () => { + const server = createServer(callbackKey); + addFeedbackTool(server, { + errorHints: () => { + throw new Error('filter broke'); + }, + }); + server.registerTool('throws', {}, () => { + throw new Error('Upstream returned 500'); + }); + + await expect(server.call('throws')).resolves.toEqual(errorResult('Upstream returned 500')); }); it('does not add the hint to the feedback tool itself', async () => { @@ -145,10 +257,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 () => { @@ -160,8 +270,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 () => { @@ -182,7 +291,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]); @@ -296,10 +405,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 () => {