From c8318d9d078937e063242b9a5637154de182a8b7 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Mon, 30 Nov 2026 11:34:37 -0500 Subject: [PATCH 01/34] feat(mcp): Add a feedback tool for MCP servers --- .github/REVIEWERS | 2 + .../node-express-mcp-v1/package.json | 1 + .../node-express-mcp-v1/src/mcp.ts | 3 + .../node-express-mcp-v1/tests/mcp.test.ts | 61 ++++- .../node-express-mcp-v2/package.json | 1 + .../node-express-mcp-v2/src/mcp.ts | 3 + .../node-express-mcp-v2/tests/mcp.test.ts | 61 ++++- packages/mcp/README.md | 62 ++++- packages/mcp/package.json | 6 +- packages/mcp/src/addFeedbackTool.ts | 109 +++++++++ packages/mcp/src/debug-build.ts | 8 + packages/mcp/src/feedback.ts | 229 ++++++++++++++++++ packages/mcp/src/index.ts | 18 +- packages/mcp/test/addFeedbackTool.test.ts | 87 +++++++ packages/mcp/test/feedback.test.ts | 146 +++++++++++ packages/mcp/vitest.config.ts | 1 - pnpm-lock.yaml | 3 + 17 files changed, 795 insertions(+), 6 deletions(-) create mode 100644 packages/mcp/src/addFeedbackTool.ts create mode 100644 packages/mcp/src/debug-build.ts create mode 100644 packages/mcp/src/feedback.ts create mode 100644 packages/mcp/test/addFeedbackTool.test.ts create mode 100644 packages/mcp/test/feedback.test.ts diff --git a/.github/REVIEWERS b/.github/REVIEWERS index d4805a82c2bc..e37446f5a61d 100644 --- a/.github/REVIEWERS +++ b/.github/REVIEWERS @@ -49,6 +49,7 @@ /packages/core/src/server-runtime-client.ts @getsentry/team-javascript-sdks-server /packages/core/src/integrations/http/ @getsentry/team-javascript-sdks-server /packages/core/src/integrations/mcp-server/ @getsentry/team-javascript-sdks-server +/packages/mcp/ @getsentry/team-javascript-sdks-server /dev-packages/e2e-tests/test-applications/node-*/ @getsentry/team-javascript-sdks-server /dev-packages/e2e-tests/test-applications/bun-*/ @getsentry/team-javascript-sdks-server /dev-packages/e2e-tests/test-applications/deno/ @getsentry/team-javascript-sdks-server @@ -125,6 +126,7 @@ +/packages/server-utils/src/orchestrion/config/openai-compatible.ts @RulaKhaled +/packages/cloudflare/src/instrumentations/agents/ @RulaKhaled +/packages/core/src/integrations/mcp-server/ @RulaKhaled ++/packages/mcp/ @RulaKhaled +/packages/core/src/integrations/conversationId.ts @RulaKhaled +/packages/core/src/tracing/spans/extractGenAiSpans.ts @RulaKhaled +/packages/core/test/lib/tracing/spans/extractGenAiSpans.test.ts @RulaKhaled diff --git a/dev-packages/e2e-tests/test-applications/node-express-mcp-v1/package.json b/dev-packages/e2e-tests/test-applications/node-express-mcp-v1/package.json index dc23a20a86a7..8e17240a05ea 100644 --- a/dev-packages/e2e-tests/test-applications/node-express-mcp-v1/package.json +++ b/dev-packages/e2e-tests/test-applications/node-express-mcp-v1/package.json @@ -12,6 +12,7 @@ }, "dependencies": { "@modelcontextprotocol/sdk": "^1.26.0", + "@sentry/mcp": "file:../../packed/sentry-mcp-packed.tgz", "@sentry/node": "file:../../packed/sentry-node-packed.tgz", "@types/express": "^4.17.21", "@types/node": "^18.19.1", diff --git a/dev-packages/e2e-tests/test-applications/node-express-mcp-v1/src/mcp.ts b/dev-packages/e2e-tests/test-applications/node-express-mcp-v1/src/mcp.ts index c1a9dfea3622..e39f80222d62 100644 --- a/dev-packages/e2e-tests/test-applications/node-express-mcp-v1/src/mcp.ts +++ b/dev-packages/e2e-tests/test-applications/node-express-mcp-v1/src/mcp.ts @@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto'; import express from 'express'; import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js'; import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; +import { addFeedbackTool } from '@sentry/mcp'; import { z } from 'zod'; const mcpRouter = express.Router(); @@ -51,6 +52,8 @@ server.registerTool('always-error', {}, async () => { throw new Error('intentional error for span status testing'); }); +addFeedbackTool(server, { serverName: 'Echo-V1' }); + const transports: Record = {}; mcpRouter.post('/mcp', async (req, res) => { 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 0e34722b1243..754a0a3772c2 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 @@ -1,5 +1,5 @@ import { expect, test } from '@playwright/test'; -import { waitForStreamedSpan, getSpanOp } from '@sentry-internal/test-utils'; +import { waitForEnvelopeItem, waitForStreamedSpan, getSpanOp } from '@sentry-internal/test-utils'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; @@ -96,5 +96,64 @@ test('auto-instruments a legacy MCP SDK v1 server (no manual wrap)', async ({ ba expect(toolSegment?.status).toEqual('error'); }); + await test.step('lists the tool with its input schema', async () => { + const { tools } = await client.listTools(); + const feedbackTool = tools.find(tool => tool.name === 'submit_feedback'); + + expect(feedbackTool?.description).toContain('Report friction with the Echo-V1 MCP server'); + expect(feedbackTool?.inputSchema).toMatchObject({ + type: 'object', + properties: { + kind: { enum: ['missing', 'broken', 'confusing', 'idea'] }, + impact: { enum: ['blocked', 'worked_around', 'friction'] }, + }, + required: expect.arrayContaining(['task', 'kind', 'impact', 'description']), + }); + }); + + await test.step('sends a report as user feedback', async () => { + const feedbackPromise = waitForEnvelopeItem('node-express-mcp-v1', item => item[0].type === 'feedback'); + + const result = await client.callTool({ + name: 'submit_feedback', + arguments: { + task: 'echo a message', + kind: 'broken', + impact: 'worked_around', + description: 'echo dropped the trailing newline. Token Bearer abc.def leaked.', + toolName: 'echo', + }, + }); + + expect(result.isError).toBeFalsy(); + expect(result.content).toEqual([ + { type: 'text', text: expect.stringMatching(/^Feedback sent \(ID [0-9a-f]{32}\)\.$/) }, + ]); + + const [, feedback] = await feedbackPromise; + expect(feedback).toMatchObject({ + type: 'feedback', + contexts: { + feedback: { + source: 'mcp_agent', + name: 'MCP agent (test-client-v1)', + message: + 'Task: echo a message\nTool: echo\n\necho dropped the trailing newline. Token Bearer [REDACTED_TOKEN] leaked.', + }, + }, + tags: { 'feedback.kind': 'broken', 'feedback.impact': 'worked_around', 'feedback.tool': 'echo' }, + }); + }); + + await test.step('rejects filler reports', async () => { + const result = await client.callTool({ + name: 'submit_feedback', + arguments: { task: 'echo a message', kind: 'idea', impact: 'friction', description: 'N/A' }, + }); + + expect(result.isError).toBe(true); + expect(result.content).toEqual([{ type: 'text', text: expect.stringContaining('`description` is a placeholder') }]); + }); + await client.close(); }); diff --git a/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/package.json b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/package.json index c7b312c9654f..94bebf526166 100644 --- a/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/package.json +++ b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/package.json @@ -16,6 +16,7 @@ "@cfworker/json-schema": "^4.0.0", "@modelcontextprotocol/node": "^2.0.0", "@modelcontextprotocol/server": "^2.0.0", + "@sentry/mcp": "file:../../packed/sentry-mcp-packed.tgz", "@sentry/node": "file:../../packed/sentry-node-packed.tgz", "@types/express": "^4.17.21", "@types/node": "^18.19.1", diff --git a/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/src/mcp.ts b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/src/mcp.ts index 86076f743d62..a00baef2281b 100644 --- a/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/src/mcp.ts +++ b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/src/mcp.ts @@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto'; import express from 'express'; import { McpServer, ResourceTemplate } from '@modelcontextprotocol/server'; import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node'; +import { addFeedbackTool } from '@sentry/mcp'; import { z } from 'zod'; const mcpRouter = express.Router(); @@ -55,6 +56,8 @@ server.registerTool('always-error', {}, async () => { throw new Error('intentional error for span status testing'); }); +addFeedbackTool(server, { serverName: 'Echo-V2' }); + const transports: Record = {}; mcpRouter.post('/mcp', async (req, res) => { 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 826821dca3af..d5c8fbeddc6f 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 @@ -1,5 +1,5 @@ import { expect, test } from '@playwright/test'; -import { waitForStreamedSpan, getSpanOp } from '@sentry-internal/test-utils'; +import { waitForEnvelopeItem, waitForStreamedSpan, getSpanOp } from '@sentry-internal/test-utils'; import { Client } from '@modelcontextprotocol/client'; import { StreamableHTTPClientTransport } from '@modelcontextprotocol/client'; @@ -132,5 +132,64 @@ test('auto-instruments a stable MCP SDK v2 server (no manual wrap)', async ({ ba expect(toolSegment?.status).toEqual('error'); }); + await test.step('lists the tool with its input schema', async () => { + const { tools } = await client.listTools(); + const feedbackTool = tools.find(tool => tool.name === 'submit_feedback'); + + expect(feedbackTool?.description).toContain('Report friction with the Echo-V2 MCP server'); + expect(feedbackTool?.inputSchema).toMatchObject({ + type: 'object', + properties: { + kind: { enum: ['missing', 'broken', 'confusing', 'idea'] }, + impact: { enum: ['blocked', 'worked_around', 'friction'] }, + }, + required: expect.arrayContaining(['task', 'kind', 'impact', 'description']), + }); + }); + + await test.step('sends a report as user feedback', async () => { + const feedbackPromise = waitForEnvelopeItem('node-express-mcp-v2', item => item[0].type === 'feedback'); + + const result = await client.callTool({ + name: 'submit_feedback', + arguments: { + task: 'echo a message', + kind: 'broken', + impact: 'worked_around', + description: 'echo dropped the trailing newline. Token Bearer abc.def leaked.', + toolName: 'echo', + }, + }); + + expect(result.isError).toBeFalsy(); + expect(result.content).toEqual([ + { type: 'text', text: expect.stringMatching(/^Feedback sent \(ID [0-9a-f]{32}\)\.$/) }, + ]); + + const [, feedback] = await feedbackPromise; + expect(feedback).toMatchObject({ + type: 'feedback', + contexts: { + feedback: { + source: 'mcp_agent', + name: 'MCP agent (test-client-v2)', + message: + 'Task: echo a message\nTool: echo\n\necho dropped the trailing newline. Token Bearer [REDACTED_TOKEN] leaked.', + }, + }, + tags: { 'feedback.kind': 'broken', 'feedback.impact': 'worked_around', 'feedback.tool': 'echo' }, + }); + }); + + await test.step('rejects filler reports', async () => { + const result = await client.callTool({ + name: 'submit_feedback', + arguments: { task: 'echo a message', kind: 'idea', impact: 'friction', description: 'N/A' }, + }); + + expect(result.isError).toBe(true); + expect(result.content).toEqual([{ type: 'text', text: expect.stringContaining('`description` is a placeholder') }]); + }); + await client.close(); }); diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 5416ed791613..d96ed1e60fbc 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -10,4 +10,64 @@ # Sentry Helpers for MCP Servers -Helpers for MCP servers instrumented with a Sentry SDK. Not released yet. +[![npm version](https://img.shields.io/npm/v/@sentry/mcp.svg)](https://www.npmjs.com/package/@sentry/mcp) +[![npm dm](https://img.shields.io/npm/dm/@sentry/mcp.svg)](https://www.npmjs.com/package/@sentry/mcp) +[![npm dt](https://img.shields.io/npm/dt/@sentry/mcp.svg)](https://www.npmjs.com/package/@sentry/mcp) + +Helpers for MCP servers instrumented with a Sentry SDK. Works with `@modelcontextprotocol/sdk` v1 and +`@modelcontextprotocol/server` v2. + +## Feedback tool + +`addFeedbackTool` registers a tool that lets agents report friction with your server's tools: a missing tool, a tool +that failed, a confusing tool, or an idea. Each report is sent to Sentry as User Feedback, tagged with `feedback.kind`, +`feedback.impact` and `feedback.tool`, and linked to the trace of the tool call. + +```js +import * as Sentry from '@sentry/node'; +import { McpServer } from '@modelcontextprotocol/server'; +import { addFeedbackTool } from '@sentry/mcp'; + +const server = Sentry.wrapMcpServerWithSentry(new McpServer({ name: 'acme', version: '1.0.0' })); + +addFeedbackTool(server, { serverName: 'Acme' }); +``` + +The tool is called `submit_feedback` unless you pass `name`. It is not registered when Sentry has no DSN. + +### Registering the tool yourself + +If your server registers tools through its own catalog, use the parts instead: + +```js +import { captureAgentFeedback, feedbackInputSchema, getFeedbackToolDescription } from '@sentry/mcp'; + +server.registerTool( + 'submit_feedback', + { description: getFeedbackToolDescription({ serverName: 'Acme' }), inputSchema: feedbackInputSchema }, + args => { + const result = captureAgentFeedback(args, { clientName: 'cursor' }); + + return result.ok + ? { content: [{ type: 'text', text: 'Feedback sent.' }] } + : { isError: true, content: [{ type: 'text', text: result.error }] }; + }, +); +``` + +### Pointing agents at the tool + +Agents that are stuck rarely go looking for a feedback tool. Append `feedbackHint` to errors that likely come from a bug +in your server: + +```js +return { + isError: true, + content: [{ type: 'text', text: `Upstream returned 500. ${feedbackHint('If this keeps failing')}` }], +}; +``` + +## Support + +- [Report a bug](https://github.com/getsentry/sentry-javascript/issues/new/choose) +- [Contributing](https://github.com/getsentry/sentry-javascript/blob/develop/CONTRIBUTING.md) diff --git a/packages/mcp/package.json b/packages/mcp/package.json index b01c7f175957..af75a4ef7e17 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -29,8 +29,12 @@ "dependencies": { "@sentry/core": "11.21.0" }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + }, "devDependencies": { - "@sentry-internal/rollup-utils": "11.21.0" + "@sentry-internal/rollup-utils": "11.21.0", + "zod": "^4.6.7" }, "scripts": { "build": "pnpm run \"/^build:(transpile|types)$/\"", diff --git a/packages/mcp/src/addFeedbackTool.ts b/packages/mcp/src/addFeedbackTool.ts new file mode 100644 index 000000000000..65c3ffa826c7 --- /dev/null +++ b/packages/mcp/src/addFeedbackTool.ts @@ -0,0 +1,109 @@ +import { debug } from '@sentry/core'; +import { DEBUG_BUILD } from './debug-build'; +import type { AgentFeedback, FeedbackToolDescriptionOptions } from './feedback'; +import { + captureAgentFeedback, + DEFAULT_FEEDBACK_TOOL_NAME, + feedbackInputSchema, + getFeedbackToolDescription, + isFeedbackAvailable, +} from './feedback'; + +type ToolResult = { + content: Array<{ type: 'text'; text: string }>; + isError?: boolean; +}; + +// The parts of `McpServer` we use. The public parameter is `object`, like `wrapMcpServerWithSentry`, +// so a server from any MCP SDK version is accepted. +interface McpServerLike { + registerTool?: ( + name: string, + config: Record, + handler: (args: AgentFeedback) => ToolResult, + ) => unknown; + tool?: ( + name: string, + description: string, + inputSchema: Record, + handler: (args: AgentFeedback) => ToolResult, + ) => unknown; + server?: { getClientVersion?: () => { name?: string } | undefined }; +} + +/** + * Options for `addFeedbackTool`. + */ +export interface AddFeedbackToolOptions extends FeedbackToolDescriptionOptions { + /** + * Name of the tool. Defaults to `submit_feedback`. + */ + name?: string; + /** + * Replaces the default tool description. + */ + description?: string; + /** + * Extra scrubbing applied to each report's message. See `captureAgentFeedback`. + */ + scrub?: (message: string) => string; +} + +/** + * Registers a tool on an MCP server that lets agents report friction with the server's tools. + * Reports are sent to Sentry as User Feedback, tagged with `feedback.kind`, `feedback.impact` and `feedback.tool`. + * + * The tool is not registered when Sentry has no DSN, since it could not deliver anything. + * + * @example + * ```ts + * const server = Sentry.wrapMcpServerWithSentry(new McpServer({ name: 'acme', version: '1.0.0' })); + * addFeedbackTool(server, { serverName: 'Acme' }); + * ``` + */ +export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptions = {}): void { + const server = mcpServer as McpServerLike; + + if (!isFeedbackAvailable()) { + DEBUG_BUILD && debug.log('[MCP] Not registering the feedback tool because Sentry has no DSN.'); + return; + } + + const name = options.name ?? DEFAULT_FEEDBACK_TOOL_NAME; + const description = options.description ?? getFeedbackToolDescription(options); + + const handler = (args: AgentFeedback): ToolResult => { + const result = captureAgentFeedback(args, { + clientName: server.server?.getClientVersion?.()?.name, + scrub: options.scrub, + }); + + if (!result.ok) { + return { isError: true, content: [{ type: 'text', text: result.error }] }; + } + + return { content: [{ type: 'text', text: `Feedback sent (ID ${result.feedbackId}).` }] }; + }; + + if (typeof server.registerTool === 'function') { + server.registerTool( + name, + { + title: 'Submit Feedback', + description, + inputSchema: feedbackInputSchema, + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, + }, + handler, + ); + return; + } + + if (typeof server.tool === 'function') { + server.tool(name, description, feedbackInputSchema, handler); + return; + } + + DEBUG_BUILD && + debug.warn('[MCP] Could not register the feedback tool: the server has no `registerTool` or `tool` method.'); +} diff --git a/packages/mcp/src/debug-build.ts b/packages/mcp/src/debug-build.ts new file mode 100644 index 000000000000..60aa50940582 --- /dev/null +++ b/packages/mcp/src/debug-build.ts @@ -0,0 +1,8 @@ +declare const __DEBUG_BUILD__: boolean; + +/** + * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code. + * + * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking. + */ +export const DEBUG_BUILD = __DEBUG_BUILD__; diff --git a/packages/mcp/src/feedback.ts b/packages/mcp/src/feedback.ts new file mode 100644 index 000000000000..402b9ffab572 --- /dev/null +++ b/packages/mcp/src/feedback.ts @@ -0,0 +1,229 @@ +import type { Scope } from '@sentry/core'; +import { captureFeedback, getClient, getCombinedScopeData, getCurrentScope, getIsolationScope } from '@sentry/core'; +import * as z from 'zod/v4'; + +/** + * The tool name `addFeedbackTool` registers when no other name is given. + */ +export const DEFAULT_FEEDBACK_TOOL_NAME = 'submit_feedback'; + +// Sentry rejects User Feedback messages longer than 4096 code points. Slicing +// UTF-16 units keeps us at or under that. +const MAX_FEEDBACK_MESSAGE_LENGTH = 4096; + +// Filler that agents have sent instead of a real report, compared after +// lowercasing and dropping everything but letters and digits. +const PLACEHOLDER_DESCRIPTIONS = new Set([ + '', + 'na', + 'none', + 'noop', + 'null', + 'placeholder', + 'tbd', + 'test', + 'todo', + 'undefined', +]); + +const SCRUB_PATTERNS: Array<[RegExp, string]> = [ + [/\bsk-[a-zA-Z0-9]{48}\b/g, '[REDACTED_OPENAI_KEY]'], + [/\bBearer\s+[a-zA-Z0-9\-._~+/]+={0,}/g, 'Bearer [REDACTED_TOKEN]'], + [/\bsntrys_[a-zA-Z0-9_]+\b/g, '[REDACTED_SENTRY_TOKEN]'], + [/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, '[REDACTED_EMAIL]'], +]; + +/** + * The arguments an agent passes to the feedback tool. + */ +export interface AgentFeedback { + task: string; + kind: 'missing' | 'broken' | 'confusing' | 'idea'; + impact: 'blocked' | 'worked_around' | 'friction'; + description: string; + toolName?: string; +} + +/** + * Input schema of the feedback tool, as a zod raw shape. Pass it as `inputSchema` to `registerTool`. + */ +export const feedbackInputSchema = { + task: z.string().trim().min(1).max(200).describe('A short phrase naming what the user asked you to do.'), + kind: z + .enum(['missing', 'broken', 'confusing', 'idea']) + .describe( + 'missing: no tool could do it; broken: a tool failed or returned something wrong; confusing: a tool or its docs were unclear; idea: a suggestion.', + ), + impact: z + .enum(['blocked', 'worked_around', 'friction']) + .describe( + 'blocked: you could not finish; worked_around: you finished another way; friction: you finished, but it was harder than it should be.', + ), + description: z + .string() + .trim() + .min(1) + .max(4096) + .describe('What you tried, including tool calls and any error, and what went wrong.'), + toolName: z.string().trim().max(100).optional().describe('The tool the feedback is about, if any.'), +}; + +/** + * Options for `getFeedbackToolDescription`. + */ +export interface FeedbackToolDescriptionOptions { + /** + * Name of the MCP server, used in the description so the agent knows where the report goes. + * Without it the description says "this MCP server". + */ + serverName?: string; +} + +/** + * Returns the description of the feedback tool. It tells the agent to report only friction + * with this server's tools, at most once per task. + */ +export function getFeedbackToolDescription(options: FeedbackToolDescriptionOptions = {}): string { + const server = options.serverName ? `the ${options.serverName} MCP server` : 'this MCP server'; + + return ( + `Report friction with ${server} to its maintainers: a missing tool, a tool that failed or returned wrong data, a confusing tool, or an idea. ` + + `Call it at most once per task, only when one of its tools was missing, failed, or got in the way. ` + + 'Skip it if the task went fine or did not need this server; never use it to log progress or to test it. ' + + 'Do not include secrets or personal data.' + ); +} + +/** + * Options for `captureAgentFeedback`. + */ +export interface CaptureAgentFeedbackOptions { + /** + * Name of the agent client that sent the report, for example `cursor`. Shown as the feedback's name. + */ + clientName?: string; + /** + * ID of the user the agent acts for. Defaults to the user set on the scope. + * Left out of the feedback's name when `dataCollection.userInfo` is `false`. + */ + userId?: string; + /** + * Extra scrubbing applied to the message after the built-in token and email scrubbing. + * Feedback events do not go through `beforeSend`, so this is the place to remove sensitive data. + */ + scrub?: (message: string) => string; + /** + * Scope to capture the feedback on. Defaults to the current scope. + */ + scope?: Scope; +} + +/** + * Result of `captureAgentFeedback`. + */ +export type CaptureAgentFeedbackResult = { ok: true; feedbackId: string } | { ok: false; error: string }; + +/** + * Whether the feedback tool can deliver reports, which needs a Sentry client with a DSN. + */ +export function isFeedbackAvailable(): boolean { + return !!getClient()?.getDsn(); +} + +/** + * Sends a report the agent made through the feedback tool to Sentry as User Feedback. + * + * Returns an error for the agent instead when the description is filler, such as `test` or `N/A`. + */ +export function captureAgentFeedback( + feedback: AgentFeedback, + options: CaptureAgentFeedbackOptions = {}, +): CaptureAgentFeedbackResult { + if (isPlaceholder(feedback.description)) { + return { + ok: false, + error: + '`description` is a placeholder. Describe what you tried and what went wrong, or skip this tool if there is nothing to report.', + }; + } + + const lines = [`Task: ${feedback.task}`]; + if (feedback.toolName) { + lines.push(`Tool: ${feedback.toolName}`); + } + lines.push('', feedback.description); + + let message = scrubSensitiveText(lines.join('\n')); + if (options.scrub) { + message = options.scrub(message); + } + + const scope = options.scope ?? getCurrentScope(); + const feedbackId = captureFeedback( + { + source: 'mcp_agent', + name: getFeedbackName(options, scope), + message: message.slice(0, MAX_FEEDBACK_MESSAGE_LENGTH), + tags: { + 'feedback.kind': feedback.kind, + 'feedback.impact': feedback.impact, + ...(feedback.toolName ? { 'feedback.tool': feedback.toolName } : {}), + }, + }, + {}, + scope, + ); + + return { ok: true, feedbackId }; +} + +/** + * Options for `feedbackHint`. + */ +export interface FeedbackHintOptions { + /** + * Name of the registered feedback tool. Defaults to `submit_feedback`. + */ + toolName?: string; + /** + * Whether the agent can call the feedback tool. Defaults to `isFeedbackAvailable()`. + */ + available?: boolean; +} + +/** + * Returns a sentence to append to a tool error that likely comes from a bug in the server, + * pointing the agent at the feedback tool. Returns an empty string when the tool is not available, + * so the agent is never told about a tool it cannot call. + * + * @param condition - When the agent should report it, e.g. "If this keeps failing". + */ +export function feedbackHint(condition: string, options: FeedbackHintOptions = {}): string { + const available = options.available ?? isFeedbackAvailable(); + if (!available) { + return ''; + } + + return `${condition}, report it to this server's maintainers with \`${options.toolName ?? DEFAULT_FEEDBACK_TOOL_NAME}\`.`; +} + +function isPlaceholder(text: string): boolean { + return PLACEHOLDER_DESCRIPTIONS.has(text.toLowerCase().replace(/[^\p{L}\p{N}]/gu, '')); +} + +function scrubSensitiveText(text: string): string { + return SCRUB_PATTERNS.reduce((scrubbed, [pattern, replacement]) => scrubbed.replace(pattern, replacement), text); +} + +// The feedback list shows "Anonymous User" without a name, so name the agent and, +// when user info may be collected, the user it acts for. +function getFeedbackName(options: CaptureAgentFeedbackOptions, scope: Scope): string { + const agent = options.clientName ? `MCP agent (${options.clientName})` : 'MCP agent'; + if (!getClient()?.getDataCollectionOptions().userInfo) { + return agent; + } + + const userId = options.userId ?? getCombinedScopeData(getIsolationScope(), scope).user.id; + + return userId ? `${agent} for user ${userId}` : agent; +} diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index cb0ff5c3b541..49f63c49b8a5 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -1 +1,17 @@ -export {}; +export { addFeedbackTool } from './addFeedbackTool'; +export type { AddFeedbackToolOptions } from './addFeedbackTool'; +export { + captureAgentFeedback, + DEFAULT_FEEDBACK_TOOL_NAME, + feedbackHint, + feedbackInputSchema, + getFeedbackToolDescription, + isFeedbackAvailable, +} from './feedback'; +export type { + AgentFeedback, + CaptureAgentFeedbackOptions, + CaptureAgentFeedbackResult, + FeedbackHintOptions, + FeedbackToolDescriptionOptions, +} from './feedback'; diff --git a/packages/mcp/test/addFeedbackTool.test.ts b/packages/mcp/test/addFeedbackTool.test.ts new file mode 100644 index 000000000000..a3b1e74e6c9d --- /dev/null +++ b/packages/mcp/test/addFeedbackTool.test.ts @@ -0,0 +1,87 @@ +import { captureFeedback, getClient } from '@sentry/core'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { addFeedbackTool } from '../src/addFeedbackTool'; +import { feedbackInputSchema } from '../src/feedback'; + +vi.mock('@sentry/core', async importOriginal => { + const actual = await importOriginal>(); + return { ...actual, captureFeedback: vi.fn(() => 'event-id'), getClient: vi.fn() }; +}); + +const report = { + task: 'find slow endpoints', + kind: 'missing', + impact: 'blocked', + description: 'No p95 tool.', +} as const; + +describe('addFeedbackTool', () => { + beforeEach(() => { + vi.mocked(getClient).mockReturnValue({ + getDsn: () => ({}), + getDataCollectionOptions: () => ({ userInfo: true }), + } as unknown as ReturnType); + }); + + afterEach(() => { + vi.clearAllMocks(); + }); + + it('registers the tool with registerTool and sends reports', () => { + const registerTool = vi.fn(); + const server = { registerTool, server: { getClientVersion: () => ({ name: 'cursor' }) } }; + + addFeedbackTool(server, { serverName: 'Acme' }); + + expect(registerTool).toHaveBeenCalledWith( + 'submit_feedback', + expect.objectContaining({ + description: expect.stringContaining('the Acme MCP server'), + inputSchema: feedbackInputSchema, + }), + expect.any(Function), + ); + + const handler = registerTool.mock.lastCall![2]; + expect(handler(report)).toEqual({ content: [{ type: 'text', text: 'Feedback sent (ID event-id).' }] }); + expect(captureFeedback).toHaveBeenCalledWith( + expect.objectContaining({ name: 'MCP agent (cursor)' }), + {}, + expect.anything(), + ); + }); + + it('falls back to the legacy tool() method', () => { + const tool = vi.fn(); + + addFeedbackTool({ tool }, { name: 'submit_feedback_to_acme_team', description: 'Custom.' }); + + expect(tool).toHaveBeenCalledWith( + 'submit_feedback_to_acme_team', + 'Custom.', + feedbackInputSchema, + expect.any(Function), + ); + }); + + it('returns a tool error for filler reports', () => { + const registerTool = vi.fn(); + addFeedbackTool({ registerTool }); + + const handler = registerTool.mock.lastCall![2]; + expect(handler({ ...report, description: 'N/A' })).toEqual({ + isError: true, + content: [{ type: 'text', text: expect.stringContaining('`description` is a placeholder') }], + }); + expect(captureFeedback).not.toHaveBeenCalled(); + }); + + it('does not register the tool when Sentry has no DSN', () => { + vi.mocked(getClient).mockReturnValue(undefined); + const registerTool = vi.fn(); + + addFeedbackTool({ registerTool }); + + expect(registerTool).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/mcp/test/feedback.test.ts b/packages/mcp/test/feedback.test.ts new file mode 100644 index 000000000000..82198b20e5ab --- /dev/null +++ b/packages/mcp/test/feedback.test.ts @@ -0,0 +1,146 @@ +import { captureFeedback, getClient, getIsolationScope } from '@sentry/core'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { captureAgentFeedback, feedbackHint, getFeedbackToolDescription } from '../src/feedback'; + +vi.mock('@sentry/core', async importOriginal => { + const actual = await importOriginal>(); + return { ...actual, captureFeedback: vi.fn(() => 'event-id'), getClient: vi.fn() }; +}); + +function mockClient({ dsn = 'https://key@o1.ingest.sentry.io/1', userInfo = true } = {}): void { + vi.mocked(getClient).mockReturnValue({ + getDsn: () => (dsn ? {} : undefined), + getDataCollectionOptions: () => ({ userInfo }), + } as unknown as ReturnType); +} + +describe('captureAgentFeedback', () => { + beforeEach(() => { + mockClient(); + }); + + afterEach(() => { + vi.clearAllMocks(); + getIsolationScope().setUser(null); + }); + + it('sends scrubbed feedback tagged with kind, impact and tool', () => { + const result = captureAgentFeedback( + { + task: 'find slow endpoints', + kind: 'missing', + impact: 'blocked', + description: 'No tool returns p95 latency. Contact jane@example.com with Bearer abc.def', + toolName: 'search_traces', + }, + { clientName: 'opencode', userId: '123' }, + ); + + expect(result).toEqual({ ok: true, feedbackId: 'event-id' }); + expect(captureFeedback).toHaveBeenCalledWith( + { + source: 'mcp_agent', + name: 'MCP agent (opencode) for user 123', + message: + 'Task: find slow endpoints\nTool: search_traces\n\nNo tool returns p95 latency. Contact [REDACTED_EMAIL] with Bearer [REDACTED_TOKEN]', + tags: { 'feedback.kind': 'missing', 'feedback.impact': 'blocked', 'feedback.tool': 'search_traces' }, + }, + {}, + expect.anything(), + ); + }); + + it('applies the custom scrubber after the built-in one', () => { + captureAgentFeedback( + { task: 'read logs', kind: 'broken', impact: 'friction', description: 'Bucket s3://acme-prod failed' }, + { scrub: message => message.replace(/s3:\/\/\S+/g, '[REDACTED_PATH]') }, + ); + + expect(captureFeedback).toHaveBeenCalledWith( + expect.objectContaining({ message: 'Task: read logs\n\nBucket [REDACTED_PATH] failed' }), + {}, + expect.anything(), + ); + }); + + it('names the user from the scope when no user ID is passed', () => { + getIsolationScope().setUser({ id: '42' }); + + captureAgentFeedback({ task: 'x', kind: 'idea', impact: 'friction', description: 'Add p95 latency.' }); + + expect(captureFeedback).toHaveBeenCalledWith( + expect.objectContaining({ name: 'MCP agent for user 42' }), + {}, + expect.anything(), + ); + }); + + it('leaves the user out of the name when dataCollection.userInfo is false', () => { + mockClient({ userInfo: false }); + + captureAgentFeedback( + { task: 'x', kind: 'idea', impact: 'friction', description: 'Add p95 latency.' }, + { clientName: 'cursor', userId: '123' }, + ); + + expect(captureFeedback).toHaveBeenCalledWith( + expect.objectContaining({ name: 'MCP agent (cursor)' }), + {}, + expect.anything(), + ); + }); + + it.each(['placeholder', 'N/A', ' noop ', 'TODO.', 'test'])('rejects the filler description %j', description => { + const result = captureAgentFeedback({ task: 'x', kind: 'idea', impact: 'friction', description }); + + expect(result).toEqual({ ok: false, error: expect.stringContaining('`description` is a placeholder') }); + expect(captureFeedback).not.toHaveBeenCalled(); + }); + + it('caps the message at 4096 characters', () => { + captureAgentFeedback({ task: 'x', kind: 'idea', impact: 'friction', description: 'a'.repeat(5000) }); + + expect(captureFeedback).toHaveBeenCalledWith( + expect.objectContaining({ message: `Task: x\n\n${'a'.repeat(4096 - 'Task: x\n\n'.length)}` }), + {}, + expect.anything(), + ); + }); +}); + +describe('feedbackHint', () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it('points the agent at the feedback tool', () => { + mockClient(); + + expect(feedbackHint('If this keeps failing')).toBe( + "If this keeps failing, report it to this server's maintainers with `submit_feedback`.", + ); + expect(feedbackHint('If no tool can do this', { toolName: 'submit_feedback_to_acme_team' })).toBe( + "If no tool can do this, report it to this server's maintainers with `submit_feedback_to_acme_team`.", + ); + }); + + it('returns an empty string when Sentry has no DSN', () => { + mockClient({ dsn: '' }); + + expect(feedbackHint('If this keeps failing')).toBe(''); + }); +}); + +describe('getFeedbackToolDescription', () => { + it('names the server when given', () => { + expect(getFeedbackToolDescription({ serverName: 'Acme' })).toContain('Report friction with the Acme MCP server'); + expect(getFeedbackToolDescription()).toContain('Report friction with this MCP server'); + }); + + it('tells agents to call it only for problems with this server', () => { + const description = getFeedbackToolDescription(); + + expect(description).toContain('only when one of its tools was missing, failed, or got in the way'); + expect(description).toContain('never use it to log progress or to test it'); + }); +}); diff --git a/packages/mcp/vitest.config.ts b/packages/mcp/vitest.config.ts index 4ec2163ea11b..ed62557713c1 100644 --- a/packages/mcp/vitest.config.ts +++ b/packages/mcp/vitest.config.ts @@ -6,6 +6,5 @@ export default defineConfig({ test: { ...baseConfig.test, include: ['test/**/*.test.ts'], - passWithNoTests: true, }, }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 909af09e34b0..0c361ff88440 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1602,6 +1602,9 @@ importers: '@sentry-internal/rollup-utils': specifier: 11.21.0 version: link:../../dev-packages/rollup-utils + zod: + specifier: ^4.6.7 + version: 4.6.7 packages/nestjs: dependencies: From 30b2ac4a7efea108984552ab88c39103dde035f7 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Mon, 30 Nov 2026 11:39:41 -0500 Subject: [PATCH 02/34] chore(mcp): Route @sentry/mcp reviews to Abdelrahman, Jan and Rula --- .github/REVIEWERS | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/REVIEWERS b/.github/REVIEWERS index e37446f5a61d..d0629bdb1a90 100644 --- a/.github/REVIEWERS +++ b/.github/REVIEWERS @@ -49,7 +49,7 @@ /packages/core/src/server-runtime-client.ts @getsentry/team-javascript-sdks-server /packages/core/src/integrations/http/ @getsentry/team-javascript-sdks-server /packages/core/src/integrations/mcp-server/ @getsentry/team-javascript-sdks-server -/packages/mcp/ @getsentry/team-javascript-sdks-server +/packages/mcp/ @logaretm @JPeer264 @RulaKhaled /dev-packages/e2e-tests/test-applications/node-*/ @getsentry/team-javascript-sdks-server /dev-packages/e2e-tests/test-applications/bun-*/ @getsentry/team-javascript-sdks-server /dev-packages/e2e-tests/test-applications/deno/ @getsentry/team-javascript-sdks-server @@ -126,7 +126,6 @@ +/packages/server-utils/src/orchestrion/config/openai-compatible.ts @RulaKhaled +/packages/cloudflare/src/instrumentations/agents/ @RulaKhaled +/packages/core/src/integrations/mcp-server/ @RulaKhaled -+/packages/mcp/ @RulaKhaled +/packages/core/src/integrations/conversationId.ts @RulaKhaled +/packages/core/src/tracing/spans/extractGenAiSpans.ts @RulaKhaled +/packages/core/test/lib/tracing/spans/extractGenAiSpans.test.ts @RulaKhaled From 9658cbc4182bbaebe43cf1536540b6d572f08886 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Mon, 30 Nov 2026 12:08:08 -0500 Subject: [PATCH 03/34] feat(mcp): Point agents at the feedback tool from other tools' errors --- .../node-express-mcp-v1/tests/mcp.test.ts | 24 ++- .../node-express-mcp-v2/tests/mcp.test.ts | 24 ++- packages/mcp/README.md | 15 +- packages/mcp/src/addFeedbackTool.ts | 39 ++++- packages/mcp/src/errorHints.ts | 137 ++++++++++++++++++ packages/mcp/src/index.ts | 1 + packages/mcp/test/errorHints.test.ts | 124 ++++++++++++++++ 7 files changed, 352 insertions(+), 12 deletions(-) create mode 100644 packages/mcp/src/errorHints.ts create mode 100644 packages/mcp/test/errorHints.test.ts 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 754a0a3772c2..c9dc02eef983 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 @@ -1,5 +1,5 @@ import { expect, test } from '@playwright/test'; -import { waitForEnvelopeItem, waitForStreamedSpan, getSpanOp } from '@sentry-internal/test-utils'; +import { waitForEnvelopeItem, waitForError, waitForStreamedSpan, getSpanOp } from '@sentry-internal/test-utils'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; @@ -79,6 +79,11 @@ test('auto-instruments a legacy MCP SDK v1 server (no manual wrap)', async ({ ba }); await test.step('error tool sets span status to error', async () => { + // The feedback hint is added for the agent, but the Sentry error keeps the original message. + const errorPromise = waitForError( + 'node-express-mcp-v1', + event => event.exception?.values?.some(value => value.value?.startsWith('intentional error')) ?? false, + ); const toolSegmentPromise = waitForStreamedSpan( 'node-express-mcp-v1', segment => segment.is_segment && segment.name === 'tools/call always-error', @@ -94,6 +99,9 @@ test('auto-instruments a legacy MCP SDK v1 server (no manual wrap)', async ({ ba expect(toolSegment).toBeDefined(); expect(getSpanOp(toolSegment)).toEqual('mcp.server'); expect(toolSegment?.status).toEqual('error'); + + const error = await errorPromise; + expect(error.exception?.values?.at(-1)?.value).toBe('intentional error for span status testing'); }); await test.step('lists the tool with its input schema', async () => { @@ -155,5 +163,19 @@ test('auto-instruments a legacy MCP SDK v1 server (no manual wrap)', async ({ ba expect(result.content).toEqual([{ type: 'text', text: expect.stringContaining('`description` is a placeholder') }]); }); + await test.step('points the agent at the feedback tool on errors', async () => { + const result = await client.callTool({ name: 'always-error', arguments: {} }); + + expect(result.isError).toBe(true); + expect(result.content).toEqual([ + { + type: 'text', + text: expect.stringContaining( + "intentional error for span status testing\n\nIf this keeps failing, report it to this server's maintainers with `submit_feedback`.", + ), + }, + ]); + }); + await client.close(); }); 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 d5c8fbeddc6f..2981322bbecc 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 @@ -1,5 +1,5 @@ import { expect, test } from '@playwright/test'; -import { waitForEnvelopeItem, waitForStreamedSpan, getSpanOp } from '@sentry-internal/test-utils'; +import { waitForEnvelopeItem, waitForError, waitForStreamedSpan, getSpanOp } from '@sentry-internal/test-utils'; import { Client } from '@modelcontextprotocol/client'; import { StreamableHTTPClientTransport } from '@modelcontextprotocol/client'; @@ -115,6 +115,11 @@ test('auto-instruments a stable MCP SDK v2 server (no manual wrap)', async ({ ba }); await test.step('error tool sets span status to error', async () => { + // The feedback hint is added for the agent, but the Sentry error keeps the original message. + const errorPromise = waitForError( + 'node-express-mcp-v2', + event => event.exception?.values?.some(value => value.value?.startsWith('intentional error')) ?? false, + ); const toolSegmentPromise = waitForStreamedSpan( 'node-express-mcp-v2', segment => segment.is_segment && segment.name === 'tools/call always-error', @@ -130,6 +135,9 @@ test('auto-instruments a stable MCP SDK v2 server (no manual wrap)', async ({ ba expect(toolSegment).toBeDefined(); expect(getSpanOp(toolSegment)).toEqual('mcp.server'); expect(toolSegment?.status).toEqual('error'); + + const error = await errorPromise; + expect(error.exception?.values?.at(-1)?.value).toBe('intentional error for span status testing'); }); await test.step('lists the tool with its input schema', async () => { @@ -191,5 +199,19 @@ test('auto-instruments a stable MCP SDK v2 server (no manual wrap)', async ({ ba expect(result.content).toEqual([{ type: 'text', text: expect.stringContaining('`description` is a placeholder') }]); }); + await test.step('points the agent at the feedback tool on errors', async () => { + const result = await client.callTool({ name: 'always-error', arguments: {} }); + + expect(result.isError).toBe(true); + expect(result.content).toEqual([ + { + type: 'text', + text: expect.stringContaining( + "intentional error for span status testing\n\nIf this keeps failing, report it to this server's maintainers with `submit_feedback`.", + ), + }, + ]); + }); + await client.close(); }); diff --git a/packages/mcp/README.md b/packages/mcp/README.md index d96ed1e60fbc..329a942e6601 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -57,16 +57,19 @@ server.registerTool( ### Pointing agents at the tool -Agents that are stuck rarely go looking for a feedback tool. Append `feedbackHint` to errors that likely come from a bug -in your server: +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, report it to this server's maintainers with `submit_feedback`." Thrown errors +get the hint in their message, and Sentry still records the original message. + +Skip errors that are not bugs in your server, such as invalid input, or turn the hints off: ```js -return { - isError: true, - content: [{ type: 'text', text: `Upstream returned 500. ${feedbackHint('If this keeps failing')}` }], -}; +addFeedbackTool(server, { errorHints: (toolName, failure) => !(failure instanceof ValidationError) }); +addFeedbackTool(server, { errorHints: false }); ``` +If you register the tool yourself, append `feedbackHint('If this keeps failing')` to your own error messages. + ## Support - [Report a bug](https://github.com/getsentry/sentry-javascript/issues/new/choose) diff --git a/packages/mcp/src/addFeedbackTool.ts b/packages/mcp/src/addFeedbackTool.ts index 65c3ffa826c7..ee3497f591e8 100644 --- a/packages/mcp/src/addFeedbackTool.ts +++ b/packages/mcp/src/addFeedbackTool.ts @@ -1,5 +1,7 @@ import { debug } from '@sentry/core'; import { DEBUG_BUILD } from './debug-build'; +import type { ErrorHintFilter } from './errorHints'; +import { addErrorHints } from './errorHints'; import type { AgentFeedback, FeedbackToolDescriptionOptions } from './feedback'; import { captureAgentFeedback, @@ -47,12 +49,19 @@ export interface AddFeedbackToolOptions extends FeedbackToolDescriptionOptions { * Extra scrubbing applied to each report's message. See `captureAgentFeedback`. */ scrub?: (message: string) => string; + /** + * Whether failed calls to the server's other tools point the agent at the feedback tool. + * Pass a function to choose per failure, for example to skip input validation errors. + * Defaults to `true`. + */ + errorHints?: boolean | ErrorHintFilter; } /** * Registers a tool on an MCP server that lets agents report friction with the server's tools. * Reports are sent to Sentry as User Feedback, tagged with `feedback.kind`, `feedback.impact` and `feedback.tool`. * + * Errors from the server's other tools also tell the agent about the feedback tool, unless `errorHints` is `false`. * The tool is not registered when Sentry has no DSN, since it could not deliver anything. * * @example @@ -85,6 +94,27 @@ export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptio return { content: [{ type: 'text', text: `Feedback sent (ID ${result.feedbackId}).` }] }; }; + if (!registerTool(server, name, description, handler)) { + DEBUG_BUILD && + debug.warn('[MCP] Could not register the feedback tool: the server has no `registerTool` or `tool` method.'); + return; + } + + if (options.errorHints !== false) { + addErrorHints( + mcpServer as Record, + name, + typeof options.errorHints === 'function' ? options.errorHints : undefined, + ); + } +} + +function registerTool( + server: McpServerLike, + name: string, + description: string, + handler: (args: AgentFeedback) => ToolResult, +): boolean { if (typeof server.registerTool === 'function') { server.registerTool( name, @@ -96,14 +126,15 @@ export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptio }, handler, ); - return; + + return true; } if (typeof server.tool === 'function') { server.tool(name, description, feedbackInputSchema, handler); - return; + + return true; } - DEBUG_BUILD && - debug.warn('[MCP] Could not register the feedback tool: the server has no `registerTool` or `tool` method.'); + return false; } diff --git a/packages/mcp/src/errorHints.ts b/packages/mcp/src/errorHints.ts new file mode 100644 index 000000000000..d8056b6432c1 --- /dev/null +++ b/packages/mcp/src/errorHints.ts @@ -0,0 +1,137 @@ +import type { Event, EventHint } from '@sentry/core'; +import { fill, getGlobalScope, isObjectLike } from '@sentry/core'; +import { feedbackHint } from './feedback'; + +/** + * Decides whether a failed tool call points the agent at the feedback tool. + * `failure` is the error the tool threw, or the error result it returned. + */ +export type ErrorHintFilter = (toolName: string, failure: unknown) => boolean; + +type ToolCallback = (...args: unknown[]) => unknown; + +const HINT_CONDITION = 'If this keeps failing'; + +const originalMessages = new WeakMap(); +const wrappedTools = new WeakSet(); +let processorAdded = false; + +/** + * Adds a feedback hint to the errors of every tool on the server, the ones already registered + * and the ones registered later. The feedback tool itself is skipped. + * + * Thrown errors get the hint appended to their message, since MCP SDKs build the agent's error + * result from the message alone. An event processor puts the original message back on the + * Sentry event. + */ +export function addErrorHints( + server: Record, + feedbackToolName: string, + filter?: ErrorHintFilter, +): void { + addRestoreMessageProcessor(); + + const hint = feedbackHint(HINT_CONDITION, { toolName: feedbackToolName, available: true }); + const wrap = (name: unknown, tool: unknown): void => { + if (typeof name === 'string' && name !== feedbackToolName) { + wrapRegisteredTool(name, tool, hint, filter); + } + }; + + // Private in both MCP SDKs. `wrapMcpServerWithSentry` relies on the same map. + const registeredTools = server['_registeredTools']; + if (isObjectLike(registeredTools)) { + for (const [name, tool] of Object.entries(registeredTools)) { + wrap(name, tool); + } + } + + for (const method of ['registerTool', 'tool']) { + if (typeof server[method] !== 'function') { + continue; + } + + fill(server, method, (original: ToolCallback) => { + return function (this: unknown, name: unknown, ...rest: unknown[]): unknown { + const registered = original.call(this, name, ...rest); + const tools = server['_registeredTools']; + wrap(name, registered ?? (isObjectLike(tools) && typeof name === 'string' ? tools[name] : undefined)); + + return registered; + }; + }); + } +} + +// MCP SDK v2 calls a registered tool's `executor`, v1 calls its `handler`. +function wrapRegisteredTool(name: string, tool: unknown, hint: string, filter?: ErrorHintFilter): void { + if (!isObjectLike(tool) || wrappedTools.has(tool)) { + return; + } + + const key = + typeof tool['executor'] === 'function' ? 'executor' : typeof tool['handler'] === 'function' ? 'handler' : undefined; + if (!key) { + return; + } + + wrappedTools.add(tool); + const original = tool[key] as ToolCallback; + tool[key] = function (this: unknown, ...args: unknown[]): Promise { + return callWithHint(() => original.apply(this, args), name, hint, filter); + }; +} + +async function callWithHint( + call: () => unknown, + name: string, + hint: string, + filter?: ErrorHintFilter, +): Promise { + try { + const result = await call(); + if (!isErrorResult(result) || (filter && !filter(name, result))) { + return result; + } + + return { ...result, content: [...result.content, { type: 'text', text: hint }] }; + } catch (error) { + if (error instanceof Error && (!filter || filter(name, error))) { + const message = originalMessages.get(error) ?? error.message; + originalMessages.set(error, message); + error.message = `${message}\n\n${hint}`; + } + + throw error; + } +} + +function isErrorResult(result: unknown): result is { isError: true; content: unknown[] } { + 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 = error instanceof 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/src/index.ts b/packages/mcp/src/index.ts index 49f63c49b8a5..61c99879bcb3 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -1,5 +1,6 @@ export { addFeedbackTool } from './addFeedbackTool'; export type { AddFeedbackToolOptions } from './addFeedbackTool'; +export type { ErrorHintFilter } from './errorHints'; export { captureAgentFeedback, DEFAULT_FEEDBACK_TOOL_NAME, diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts new file mode 100644 index 000000000000..16141cc82596 --- /dev/null +++ b/packages/mcp/test/errorHints.test.ts @@ -0,0 +1,124 @@ +import type { Event, EventProcessor } from '@sentry/core'; +import { getClient, getGlobalScope } from '@sentry/core'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { addFeedbackTool } from '../src/addFeedbackTool'; + +vi.mock('@sentry/core', async importOriginal => { + const actual = await importOriginal>(); + return { ...actual, captureFeedback: vi.fn(() => 'event-id'), getClient: vi.fn() }; +}); + +const HINT = "If this keeps failing, report it to this server's maintainers with `submit_feedback`."; + +type Callback = (...args: unknown[]) => unknown; + +// Mirrors where each MCP SDK keeps a registered tool's callback: `executor` in v2, `handler` in v1. +function createServer(callbackKey: 'executor' | 'handler') { + const _registeredTools: Record> = {}; + const server = { + _registeredTools, + registerTool(name: string, _config: unknown, callback: Callback) { + _registeredTools[name] = { [callbackKey]: callback }; + return _registeredTools[name]; + }, + call(name: string, ...args: unknown[]) { + return Promise.resolve(_registeredTools[name]![callbackKey]!(...args)); + }, + }; + + 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, + ); +} + +describe.each(['executor', 'handler'] as const)('error hints (tool %s)', callbackKey => { + beforeEach(() => { + vi.mocked(getClient).mockReturnValue({ + getDsn: () => ({}), + getDataCollectionOptions: () => ({ userInfo: true }), + } as unknown as ReturnType); + }); + + it('appends the hint to error results of tools registered before and after', async () => { + const server = createServer(callbackKey); + const failed = () => ({ isError: true, content: [{ type: 'text', text: 'Upstream returned 500.' }] }); + server.registerTool('before', {}, failed); + + addFeedbackTool(server); + server.registerTool('after', {}, failed); + + for (const name of ['before', 'after']) { + await expect(server.call(name)).resolves.toEqual({ + isError: true, + content: [ + { type: 'text', text: 'Upstream returned 500.' }, + { type: 'text', text: HINT }, + ], + }); + } + }); + + it('leaves successful results alone', async () => { + const server = createServer(callbackKey); + addFeedbackTool(server); + server.registerTool('ok', {}, () => ({ content: [{ type: 'text', text: 'done' }] })); + + 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 () => { + const server = createServer(callbackKey); + const error = new Error('Upstream returned 500'); + addFeedbackTool(server); + server.registerTool('throws', {}, () => { + 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'); + }); + + it('does not add the hint to the feedback tool itself', async () => { + const server = createServer(callbackKey); + addFeedbackTool(server); + + const result = await server.call('submit_feedback', { + task: 'x', + kind: 'idea', + impact: 'friction', + description: 'N/A', + }); + expect(result).toEqual({ isError: true, content: [{ type: 'text', text: expect.not.stringContaining(HINT) }] }); + }); + + it('skips failures the errorHints filter rejects', async () => { + const server = createServer(callbackKey); + class ValidationError extends Error {} + const error = new ValidationError('query is required'); + addFeedbackTool(server, { errorHints: (_name, failure) => !(failure instanceof ValidationError) }); + server.registerTool('validates', {}, () => { + throw error; + }); + + await expect(server.call('validates')).rejects.toBe(error); + expect(error.message).toBe('query is required'); + }); + + it('does not wrap tools when errorHints is false', async () => { + const server = createServer(callbackKey); + addFeedbackTool(server, { errorHints: false }); + server.registerTool('failed', {}, () => ({ isError: true, content: [{ type: 'text', text: 'nope' }] })); + + await expect(server.call('failed')).resolves.toEqual({ isError: true, content: [{ type: 'text', text: 'nope' }] }); + }); +}); From 476d3846089645228ec86a806042a98f160b34c0 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Mon, 30 Nov 2026 13:08:32 -0500 Subject: [PATCH 04/34] feat(mcp): Skip upstream 4xx and protocol errors when hinting at the feedback tool --- packages/mcp/README.md | 9 ++++-- packages/mcp/src/addFeedbackTool.ts | 4 +-- packages/mcp/src/errorHints.ts | 46 ++++++++++++++++++++++++---- packages/mcp/src/index.ts | 1 + packages/mcp/test/errorHints.test.ts | 40 ++++++++++++++++++++++++ 5 files changed, 90 insertions(+), 10 deletions(-) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 329a942e6601..117344b58043 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -61,10 +61,15 @@ Agents that are stuck rarely go looking for a feedback tool, so `addFeedbackTool your other tools: "If this keeps failing, report it to this server's maintainers with `submit_feedback`." Thrown errors get the hint in their message, and Sentry still records the original message. -Skip errors that are not bugs in your server, such as invalid input, or turn the hints off: +By default, `shouldHintFeedback` skips failures that are not yours to fix: upstream HTTP 4xx errors (bad input, auth, +rate limits) and JSON-RPC protocol errors. Build on it to skip more, or turn the hints off: ```js -addFeedbackTool(server, { errorHints: (toolName, failure) => !(failure instanceof ValidationError) }); +import { addFeedbackTool, shouldHintFeedback } from '@sentry/mcp'; + +addFeedbackTool(server, { + errorHints: (toolName, failure) => shouldHintFeedback(failure) && !(failure instanceof ValidationError), +}); addFeedbackTool(server, { errorHints: false }); ``` diff --git a/packages/mcp/src/addFeedbackTool.ts b/packages/mcp/src/addFeedbackTool.ts index ee3497f591e8..113acc20f27b 100644 --- a/packages/mcp/src/addFeedbackTool.ts +++ b/packages/mcp/src/addFeedbackTool.ts @@ -51,8 +51,8 @@ export interface AddFeedbackToolOptions extends FeedbackToolDescriptionOptions { scrub?: (message: string) => string; /** * Whether failed calls to the server's other tools point the agent at the feedback tool. - * Pass a function to choose per failure, for example to skip input validation errors. - * Defaults to `true`. + * Defaults to `shouldHintFeedback`, which skips upstream HTTP 4xx and JSON-RPC protocol errors. + * Pass a function to choose per failure, or `false` to turn the hints off. */ errorHints?: boolean | ErrorHintFilter; } diff --git a/packages/mcp/src/errorHints.ts b/packages/mcp/src/errorHints.ts index d8056b6432c1..ef7db560e2f2 100644 --- a/packages/mcp/src/errorHints.ts +++ b/packages/mcp/src/errorHints.ts @@ -10,12 +10,45 @@ export type ErrorHintFilter = (toolName: string, failure: unknown) => boolean; type ToolCallback = (...args: unknown[]) => unknown; +// JSON-RPC reserves -32768 to -32000 for protocol errors, such as InvalidParams (-32602). +const JSON_RPC_ERROR_MIN = -32768; +const JSON_RPC_ERROR_MAX = -32000; + const HINT_CONDITION = 'If this keeps failing'; const originalMessages = new WeakMap(); const wrappedTools = new WeakSet(); let processorAdded = false; +/** + * The default `errorHints` filter. Returns `false` for failures that are not the server's to fix: + * upstream HTTP 4xx errors (bad input, auth, not found, rate limits) and JSON-RPC protocol errors. + * Everything else gets the hint, including failures it cannot classify. + * + * @example + * ```ts + * addFeedbackTool(server, { + * errorHints: (toolName, failure) => shouldHintFeedback(failure) && !(failure instanceof ValidationError), + * }); + * ``` + */ +export function shouldHintFeedback(failure: unknown): boolean { + if (!isObjectLike(failure)) { + return true; + } + + const response = failure['response']; + const status = + failure['status'] ?? failure['statusCode'] ?? (isObjectLike(response) ? response['status'] : undefined); + if (typeof status === 'number' && status >= 400 && status < 500) { + return false; + } + + const code = failure['code']; + + return !(typeof code === 'number' && code >= JSON_RPC_ERROR_MIN && code <= JSON_RPC_ERROR_MAX); +} + /** * Adds a feedback hint to the errors of every tool on the server, the ones already registered * and the ones registered later. The feedback tool itself is skipped. @@ -31,10 +64,11 @@ export function addErrorHints( ): void { addRestoreMessageProcessor(); + const shouldHint = filter ?? ((_toolName: string, failure: unknown) => shouldHintFeedback(failure)); const hint = feedbackHint(HINT_CONDITION, { toolName: feedbackToolName, available: true }); const wrap = (name: unknown, tool: unknown): void => { if (typeof name === 'string' && name !== feedbackToolName) { - wrapRegisteredTool(name, tool, hint, filter); + wrapRegisteredTool(name, tool, hint, shouldHint); } }; @@ -64,7 +98,7 @@ export function addErrorHints( } // MCP SDK v2 calls a registered tool's `executor`, v1 calls its `handler`. -function wrapRegisteredTool(name: string, tool: unknown, hint: string, filter?: ErrorHintFilter): void { +function wrapRegisteredTool(name: string, tool: unknown, hint: string, shouldHint: ErrorHintFilter): void { if (!isObjectLike(tool) || wrappedTools.has(tool)) { return; } @@ -78,7 +112,7 @@ function wrapRegisteredTool(name: string, tool: unknown, hint: string, filter?: wrappedTools.add(tool); const original = tool[key] as ToolCallback; tool[key] = function (this: unknown, ...args: unknown[]): Promise { - return callWithHint(() => original.apply(this, args), name, hint, filter); + return callWithHint(() => original.apply(this, args), name, hint, shouldHint); }; } @@ -86,17 +120,17 @@ async function callWithHint( call: () => unknown, name: string, hint: string, - filter?: ErrorHintFilter, + shouldHint: ErrorHintFilter, ): Promise { try { const result = await call(); - if (!isErrorResult(result) || (filter && !filter(name, result))) { + if (!isErrorResult(result) || !shouldHint(name, result)) { return result; } return { ...result, content: [...result.content, { type: 'text', text: hint }] }; } catch (error) { - if (error instanceof Error && (!filter || filter(name, 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}`; diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index 61c99879bcb3..770f193aa295 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -1,5 +1,6 @@ export { addFeedbackTool } from './addFeedbackTool'; export type { AddFeedbackToolOptions } from './addFeedbackTool'; +export { shouldHintFeedback } from './errorHints'; export type { ErrorHintFilter } from './errorHints'; export { captureAgentFeedback, diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index 16141cc82596..adec5ff65f25 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -2,6 +2,7 @@ import type { Event, EventProcessor } from '@sentry/core'; import { getClient, getGlobalScope } from '@sentry/core'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { addFeedbackTool } from '../src/addFeedbackTool'; +import { shouldHintFeedback } from '../src/errorHints'; vi.mock('@sentry/core', async importOriginal => { const actual = await importOriginal>(); @@ -101,6 +102,24 @@ describe.each(['executor', 'handler'] as const)('error hints (tool %s)', callbac expect(result).toEqual({ isError: true, content: [{ type: 'text', text: expect.not.stringContaining(HINT) }] }); }); + it('skips upstream 4xx errors by default but hints on 5xx', async () => { + const server = createServer(callbackKey); + const rateLimited = Object.assign(new Error('Too many requests'), { status: 429 }); + const upstreamDown = Object.assign(new Error('Bad gateway'), { status: 502 }); + addFeedbackTool(server); + server.registerTool('rate-limited', {}, () => { + throw rateLimited; + }); + server.registerTool('upstream-down', {}, () => { + 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}`); + }); + it('skips failures the errorHints filter rejects', async () => { const server = createServer(callbackKey); class ValidationError extends Error {} @@ -122,3 +141,24 @@ describe.each(['executor', 'handler'] as const)('error hints (tool %s)', callbac await expect(server.call('failed')).resolves.toEqual({ isError: true, content: [{ type: 'text', text: 'nope' }] }); }); }); + +describe('shouldHintFeedback', () => { + it.each([ + ['axios-style response status', { response: { status: 403 } }], + ['got-style statusCode', { statusCode: 404 }], + ['SDK-style status', Object.assign(new Error('Rate limited'), { status: 429 })], + ['JSON-RPC InvalidParams', Object.assign(new Error('Invalid params'), { code: -32602 })], + ])('skips %s', (_label, failure) => { + expect(shouldHintFeedback(failure)).toBe(false); + }); + + it.each([ + ['5xx status', Object.assign(new Error('Bad gateway'), { status: 502 })], + ['plain error', new Error('Cannot read properties of undefined')], + ['Node system error code', Object.assign(new Error('connect ECONNREFUSED'), { code: 'ECONNREFUSED' })], + ['error result', { isError: true, content: [{ type: 'text', text: 'Upstream returned 500.' }] }], + ['thrown string', 'boom'], + ])('hints on %s', (_label, failure) => { + expect(shouldHintFeedback(failure)).toBe(true); + }); +}); From dee4322ef9c66bbbb7686966111b7a200bbe0234 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Mon, 30 Nov 2026 13:19:44 -0500 Subject: [PATCH 05/34] feat(mcp): Let servers name who the feedback hint reports to --- packages/mcp/src/addFeedbackTool.ts | 5 +++++ packages/mcp/src/errorHints.ts | 3 ++- packages/mcp/src/feedback.ts | 8 +++++++- packages/mcp/test/errorHints.test.ts | 17 +++++++++++++++++ packages/mcp/test/feedback.test.ts | 8 ++++++++ 5 files changed, 39 insertions(+), 2 deletions(-) diff --git a/packages/mcp/src/addFeedbackTool.ts b/packages/mcp/src/addFeedbackTool.ts index 113acc20f27b..fa7cecd0995f 100644 --- a/packages/mcp/src/addFeedbackTool.ts +++ b/packages/mcp/src/addFeedbackTool.ts @@ -55,6 +55,10 @@ export interface AddFeedbackToolOptions extends FeedbackToolDescriptionOptions { * Pass a function to choose per failure, or `false` to turn the hints off. */ errorHints?: boolean | ErrorHintFilter; + /** + * Who the error hints tell the agent it reports to. Defaults to "this server's maintainers". + */ + recipient?: string; } /** @@ -104,6 +108,7 @@ export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptio addErrorHints( mcpServer as Record, name, + options.recipient, typeof options.errorHints === 'function' ? options.errorHints : undefined, ); } diff --git a/packages/mcp/src/errorHints.ts b/packages/mcp/src/errorHints.ts index ef7db560e2f2..773da6a6ecad 100644 --- a/packages/mcp/src/errorHints.ts +++ b/packages/mcp/src/errorHints.ts @@ -60,12 +60,13 @@ export function shouldHintFeedback(failure: unknown): boolean { export function addErrorHints( server: Record, feedbackToolName: string, + recipient: string | undefined, filter?: ErrorHintFilter, ): void { addRestoreMessageProcessor(); const shouldHint = filter ?? ((_toolName: string, failure: unknown) => shouldHintFeedback(failure)); - const hint = feedbackHint(HINT_CONDITION, { toolName: feedbackToolName, available: true }); + const hint = feedbackHint(HINT_CONDITION, { toolName: feedbackToolName, recipient, available: true }); const wrap = (name: unknown, tool: unknown): void => { if (typeof name === 'string' && name !== feedbackToolName) { wrapRegisteredTool(name, tool, hint, shouldHint); diff --git a/packages/mcp/src/feedback.ts b/packages/mcp/src/feedback.ts index 402b9ffab572..83b63bfa5f59 100644 --- a/packages/mcp/src/feedback.ts +++ b/packages/mcp/src/feedback.ts @@ -189,6 +189,10 @@ export interface FeedbackHintOptions { * Whether the agent can call the feedback tool. Defaults to `isFeedbackAvailable()`. */ available?: boolean; + /** + * Who the agent reports to. Defaults to "this server's maintainers". + */ + recipient?: string; } /** @@ -204,7 +208,9 @@ export function feedbackHint(condition: string, options: FeedbackHintOptions = { return ''; } - return `${condition}, report it to this server's maintainers with \`${options.toolName ?? DEFAULT_FEEDBACK_TOOL_NAME}\`.`; + const recipient = options.recipient ?? "this server's maintainers"; + + return `${condition}, report it to ${recipient} with \`${options.toolName ?? DEFAULT_FEEDBACK_TOOL_NAME}\`.`; } function isPlaceholder(text: string): boolean { diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index adec5ff65f25..c1cfdb56f744 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -66,6 +66,23 @@ describe.each(['executor', 'handler'] as const)('error hints (tool %s)', callbac } }); + it('names the recipient and tool name given to addFeedbackTool', async () => { + const server = createServer(callbackKey); + addFeedbackTool(server, { name: 'submit_feedback_to_acme_team', recipient: 'the Acme team' }); + server.registerTool('failed', {}, () => ({ isError: true, content: [{ type: 'text', text: 'nope' }] })); + + await expect(server.call('failed')).resolves.toEqual({ + isError: true, + content: [ + { type: 'text', text: 'nope' }, + { + type: 'text', + text: 'If this keeps failing, report it to the Acme team with `submit_feedback_to_acme_team`.', + }, + ], + }); + }); + it('leaves successful results alone', async () => { const server = createServer(callbackKey); addFeedbackTool(server); diff --git a/packages/mcp/test/feedback.test.ts b/packages/mcp/test/feedback.test.ts index 82198b20e5ab..a9cabcf287ca 100644 --- a/packages/mcp/test/feedback.test.ts +++ b/packages/mcp/test/feedback.test.ts @@ -124,6 +124,14 @@ describe('feedbackHint', () => { ); }); + it('names a custom recipient', () => { + mockClient(); + + expect(feedbackHint('If this keeps failing', { recipient: 'the Sentry MCP team' })).toBe( + 'If this keeps failing, report it to the Sentry MCP team with `submit_feedback`.', + ); + }); + it('returns an empty string when Sentry has no DSN', () => { mockClient({ dsn: '' }); From 020e43ebc58f9b9552fda76a03bf7f4501493c3f Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Mon, 30 Nov 2026 13:32:38 -0500 Subject: [PATCH 06/34] feat(mcp): Use one default feedback hint for all errors --- .../node-express-mcp-v1/tests/mcp.test.ts | 2 +- .../node-express-mcp-v2/tests/mcp.test.ts | 2 +- packages/mcp/README.md | 4 ++-- packages/mcp/src/errorHints.ts | 4 +--- packages/mcp/src/feedback.ts | 9 ++++++--- packages/mcp/test/errorHints.test.ts | 5 +++-- packages/mcp/test/feedback.test.ts | 12 ++++++------ 7 files changed, 20 insertions(+), 18 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 c9dc02eef983..a2f0d4a82702 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 @@ -171,7 +171,7 @@ test('auto-instruments a legacy MCP SDK v1 server (no manual wrap)', async ({ ba { type: 'text', text: expect.stringContaining( - "intentional error for span status testing\n\nIf this keeps failing, report it to this server's maintainers with `submit_feedback`.", + "intentional error for span status testing\n\nIf this keeps failing after you adjust your request, report it to this server's maintainers 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 2981322bbecc..5b6d710e11c5 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 @@ -207,7 +207,7 @@ test('auto-instruments a stable MCP SDK v2 server (no manual wrap)', async ({ ba { type: 'text', text: expect.stringContaining( - "intentional error for span status testing\n\nIf this keeps failing, report it to this server's maintainers with `submit_feedback`.", + "intentional error for span status testing\n\nIf this keeps failing after you adjust your request, report it to this server's maintainers with `submit_feedback`.", ), }, ]); diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 117344b58043..c4f19b224768 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -58,7 +58,7 @@ server.registerTool( ### 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, report it to this server's maintainers with `submit_feedback`." Thrown errors +your other tools: "If this keeps failing after you adjust your request, report it to this server's maintainers with `submit_feedback`." Thrown errors get the hint in their message, and Sentry still records the original message. By default, `shouldHintFeedback` skips failures that are not yours to fix: upstream HTTP 4xx errors (bad input, auth, @@ -73,7 +73,7 @@ addFeedbackTool(server, { addFeedbackTool(server, { errorHints: false }); ``` -If you register the tool yourself, append `feedbackHint('If this keeps failing')` to your own error messages. +If you register the tool yourself, append `feedbackHint()` to your own error messages. ## Support diff --git a/packages/mcp/src/errorHints.ts b/packages/mcp/src/errorHints.ts index 773da6a6ecad..a07b5a9077c3 100644 --- a/packages/mcp/src/errorHints.ts +++ b/packages/mcp/src/errorHints.ts @@ -14,8 +14,6 @@ type ToolCallback = (...args: unknown[]) => unknown; const JSON_RPC_ERROR_MIN = -32768; const JSON_RPC_ERROR_MAX = -32000; -const HINT_CONDITION = 'If this keeps failing'; - const originalMessages = new WeakMap(); const wrappedTools = new WeakSet(); let processorAdded = false; @@ -66,7 +64,7 @@ export function addErrorHints( addRestoreMessageProcessor(); const shouldHint = filter ?? ((_toolName: string, failure: unknown) => shouldHintFeedback(failure)); - const hint = feedbackHint(HINT_CONDITION, { toolName: feedbackToolName, recipient, available: true }); + const hint = feedbackHint({ toolName: feedbackToolName, recipient, available: true }); const wrap = (name: unknown, tool: unknown): void => { if (typeof name === 'string' && name !== feedbackToolName) { wrapRegisteredTool(name, tool, hint, shouldHint); diff --git a/packages/mcp/src/feedback.ts b/packages/mcp/src/feedback.ts index 83b63bfa5f59..37b70234de14 100644 --- a/packages/mcp/src/feedback.ts +++ b/packages/mcp/src/feedback.ts @@ -181,6 +181,10 @@ export function captureAgentFeedback( * Options for `feedbackHint`. */ export interface FeedbackHintOptions { + /** + * When the agent should report it. Defaults to "If this keeps failing after you adjust your request". + */ + condition?: string; /** * Name of the registered feedback tool. Defaults to `submit_feedback`. */ @@ -199,15 +203,14 @@ export interface FeedbackHintOptions { * Returns a sentence to append to a tool error that likely comes from a bug in the server, * pointing the agent at the feedback tool. Returns an empty string when the tool is not available, * so the agent is never told about a tool it cannot call. - * - * @param condition - When the agent should report it, e.g. "If this keeps failing". */ -export function feedbackHint(condition: string, options: FeedbackHintOptions = {}): string { +export function feedbackHint(options: FeedbackHintOptions = {}): string { const available = options.available ?? isFeedbackAvailable(); if (!available) { return ''; } + const condition = options.condition ?? 'If this keeps failing after you adjust your request'; const recipient = options.recipient ?? "this server's maintainers"; return `${condition}, report it to ${recipient} with \`${options.toolName ?? DEFAULT_FEEDBACK_TOOL_NAME}\`.`; diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index c1cfdb56f744..19e0ec17d4bd 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -9,7 +9,8 @@ vi.mock('@sentry/core', async importOriginal => { return { ...actual, captureFeedback: vi.fn(() => 'event-id'), getClient: vi.fn() }; }); -const HINT = "If this keeps failing, report it to this server's maintainers with `submit_feedback`."; +const HINT = + "If this keeps failing after you adjust your request, report it to this server's maintainers with `submit_feedback`."; type Callback = (...args: unknown[]) => unknown; @@ -77,7 +78,7 @@ describe.each(['executor', 'handler'] as const)('error hints (tool %s)', callbac { type: 'text', text: 'nope' }, { type: 'text', - text: 'If this keeps failing, report it to the Acme team with `submit_feedback_to_acme_team`.', + text: 'If this keeps failing after you adjust your request, report it to the Acme team with `submit_feedback_to_acme_team`.', }, ], }); diff --git a/packages/mcp/test/feedback.test.ts b/packages/mcp/test/feedback.test.ts index a9cabcf287ca..93cc7b9d3048 100644 --- a/packages/mcp/test/feedback.test.ts +++ b/packages/mcp/test/feedback.test.ts @@ -116,10 +116,10 @@ describe('feedbackHint', () => { it('points the agent at the feedback tool', () => { mockClient(); - expect(feedbackHint('If this keeps failing')).toBe( - "If this keeps failing, report it to this server's maintainers with `submit_feedback`.", + expect(feedbackHint()).toBe( + "If this keeps failing after you adjust your request, report it to this server's maintainers with `submit_feedback`.", ); - expect(feedbackHint('If no tool can do this', { toolName: 'submit_feedback_to_acme_team' })).toBe( + expect(feedbackHint({ condition: 'If no tool can do this', toolName: 'submit_feedback_to_acme_team' })).toBe( "If no tool can do this, report it to this server's maintainers with `submit_feedback_to_acme_team`.", ); }); @@ -127,15 +127,15 @@ describe('feedbackHint', () => { it('names a custom recipient', () => { mockClient(); - expect(feedbackHint('If this keeps failing', { recipient: 'the Sentry MCP team' })).toBe( - 'If this keeps failing, report it to the Sentry MCP team with `submit_feedback`.', + expect(feedbackHint({ recipient: 'the Sentry MCP team' })).toBe( + 'If this keeps failing after you adjust your request, report it to the Sentry MCP team with `submit_feedback`.', ); }); it('returns an empty string when Sentry has no DSN', () => { mockClient({ dsn: '' }); - expect(feedbackHint('If this keeps failing')).toBe(''); + expect(feedbackHint()).toBe(''); }); }); From 8542adf32ef53e39f8e08370b1bcdfc556ef15db Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Mon, 30 Nov 2026 14:12:51 -0500 Subject: [PATCH 07/34] feat(mcp): Use the SDK's own @sentry/core through an optional peer dependency --- packages/mcp/README.md | 3 +++ packages/mcp/package.json | 10 +++++++--- pnpm-lock.yaml | 7 +++---- scripts/bump-version.js | 12 ++++++++++-- scripts/bump-version.test.ts | 22 ++++++++++++++++++++++ 5 files changed, 45 insertions(+), 9 deletions(-) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index c4f19b224768..fe27197f6f3f 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -17,6 +17,9 @@ Helpers for MCP servers instrumented with a Sentry SDK. Works with `@modelcontextprotocol/sdk` v1 and `@modelcontextprotocol/server` v2. +It uses the `@sentry/core` your Sentry SDK already installs, so it works with any 11.x SDK. With Yarn Plug'n'Play, add +`@sentry/core` to your dependencies at the same version as your SDK. + ## Feedback tool `addFeedbackTool` registers a tool that lets agents report friction with your server's tools: a missing tool, a tool diff --git a/packages/mcp/package.json b/packages/mcp/package.json index af75a4ef7e17..f744124840e4 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -26,14 +26,18 @@ "publishConfig": { "access": "public" }, - "dependencies": { - "@sentry/core": "11.21.0" - }, "peerDependencies": { + "@sentry/core": "^11.0.0", "zod": "^3.25.0 || ^4.0.0" }, + "peerDependenciesMeta": { + "@sentry/core": { + "optional": true + } + }, "devDependencies": { "@sentry-internal/rollup-utils": "11.21.0", + "@sentry/core": "11.21.0", "zod": "^4.6.7" }, "scripts": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0c361ff88440..a053c03e68ec 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1594,14 +1594,13 @@ importers: version: link:../../dev-packages/rollup-utils packages/mcp: - dependencies: - '@sentry/core': - specifier: 11.21.0 - version: link:../core devDependencies: '@sentry-internal/rollup-utils': specifier: 11.21.0 version: link:../../dev-packages/rollup-utils + '@sentry/core': + specifier: 11.21.0 + version: link:../core zod: specifier: ^4.6.7 version: 4.6.7 diff --git a/scripts/bump-version.js b/scripts/bump-version.js index 7e9e208e1ab5..2f4fc7b6557a 100644 --- a/scripts/bump-version.js +++ b/scripts/bump-version.js @@ -16,9 +16,17 @@ function updateWorkspaceDeps(pkgPath, workspaceNames, newVersion, { bumpVersion if (!pkg[depType]) continue; for (const [dep, ver] of Object.entries(pkg[depType])) { - if (workspaceNames.has(dep) && !ver.startsWith('workspace:')) { - pkg[depType][dep] = newVersion; + if (!workspaceNames.has(dep) || ver.startsWith('workspace:')) { + continue; } + + // A peer range (e.g. `@sentry/mcp`'s `"@sentry/core": "^11.0.0"`) lets the package work with any SDK + // in that range, so only exact peer versions follow the release. + if (depType === 'peerDependencies' && !/^\d/.test(ver)) { + continue; + } + + pkg[depType][dep] = newVersion; } } diff --git a/scripts/bump-version.test.ts b/scripts/bump-version.test.ts index 46081a95d7a5..0fcbc32e72f6 100644 --- a/scripts/bump-version.test.ts +++ b/scripts/bump-version.test.ts @@ -118,6 +118,28 @@ describe('bump-version', () => { expect(browser.peerDependencies['@sentry/core']).toBe('10.1.0'); }); + it('keeps range peerDependencies on workspace packages', () => { + const rootDir = tracked( + setupFixture({ + packages: { + 'packages/core': { name: '@sentry/core', version: '10.0.0' }, + 'packages/mcp': { + name: '@sentry/mcp', + version: '10.0.0', + devDependencies: { '@sentry/core': '10.0.0' }, + peerDependencies: { '@sentry/core': '^10.0.0' }, + }, + }, + }), + ); + + bumpVersions(rootDir, '10.1.0'); + const mcp = readPackageJson(path.join(rootDir, 'packages/mcp')); + expect(mcp.version).toBe('10.1.0'); + expect(mcp.devDependencies['@sentry/core']).toBe('10.1.0'); + expect(mcp.peerDependencies['@sentry/core']).toBe('^10.0.0'); + }); + it('does not modify external (non-workspace) dependencies', () => { const rootDir = tracked( setupFixture({ From 2a8eee8516bc8a8da8e9395466725005b1364869 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Mon, 30 Nov 2026 14:22:45 -0500 Subject: [PATCH 08/34] fix(mcp): Only skip JSON-RPC client errors when hinting at the feedback tool --- packages/mcp/README.md | 2 +- packages/mcp/src/addFeedbackTool.ts | 2 +- packages/mcp/src/errorHints.ts | 11 ++++++----- packages/mcp/test/errorHints.test.ts | 4 ++++ 4 files changed, 12 insertions(+), 7 deletions(-) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index fe27197f6f3f..78cfcb8f3a3f 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -65,7 +65,7 @@ your other tools: "If this keeps failing after you adjust your request, report i get the hint in their message, and Sentry still records the original message. By default, `shouldHintFeedback` skips failures that are not yours to fix: upstream HTTP 4xx errors (bad input, auth, -rate limits) and JSON-RPC protocol errors. Build on it to skip more, or turn the hints off: +rate limits) and JSON-RPC client errors such as invalid params. Build on it to skip more, or turn the hints off: ```js import { addFeedbackTool, shouldHintFeedback } from '@sentry/mcp'; diff --git a/packages/mcp/src/addFeedbackTool.ts b/packages/mcp/src/addFeedbackTool.ts index fa7cecd0995f..5deed80a7f72 100644 --- a/packages/mcp/src/addFeedbackTool.ts +++ b/packages/mcp/src/addFeedbackTool.ts @@ -51,7 +51,7 @@ export interface AddFeedbackToolOptions extends FeedbackToolDescriptionOptions { scrub?: (message: string) => string; /** * Whether failed calls to the server's other tools point the agent at the feedback tool. - * Defaults to `shouldHintFeedback`, which skips upstream HTTP 4xx and JSON-RPC protocol errors. + * Defaults to `shouldHintFeedback`, which skips upstream HTTP 4xx and JSON-RPC client errors. * Pass a function to choose per failure, or `false` to turn the hints off. */ errorHints?: boolean | ErrorHintFilter; diff --git a/packages/mcp/src/errorHints.ts b/packages/mcp/src/errorHints.ts index a07b5a9077c3..ba47523f5df8 100644 --- a/packages/mcp/src/errorHints.ts +++ b/packages/mcp/src/errorHints.ts @@ -10,9 +10,10 @@ export type ErrorHintFilter = (toolName: string, failure: unknown) => boolean; type ToolCallback = (...args: unknown[]) => unknown; -// JSON-RPC reserves -32768 to -32000 for protocol errors, such as InvalidParams (-32602). -const JSON_RPC_ERROR_MIN = -32768; -const JSON_RPC_ERROR_MAX = -32000; +// The JSON-RPC codes the MCP conventions count as client errors: parse error, invalid request, method not +// found, invalid params and resource not found. Every other code, like InternalError (-32603), is the server's. +// 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(); @@ -20,7 +21,7 @@ let processorAdded = false; /** * The default `errorHints` filter. Returns `false` for failures that are not the server's to fix: - * upstream HTTP 4xx errors (bad input, auth, not found, rate limits) and JSON-RPC protocol errors. + * upstream HTTP 4xx errors (bad input, auth, not found, rate limits) and JSON-RPC client errors. * Everything else gets the hint, including failures it cannot classify. * * @example @@ -44,7 +45,7 @@ export function shouldHintFeedback(failure: unknown): boolean { const code = failure['code']; - return !(typeof code === 'number' && code >= JSON_RPC_ERROR_MIN && code <= JSON_RPC_ERROR_MAX); + return !(typeof code === 'number' && JSON_RPC_CLIENT_ERROR_CODES.has(code)); } /** diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index 19e0ec17d4bd..8641fe8755e8 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -166,12 +166,16 @@ describe('shouldHintFeedback', () => { ['got-style statusCode', { statusCode: 404 }], ['SDK-style status', Object.assign(new Error('Rate limited'), { status: 429 })], ['JSON-RPC InvalidParams', Object.assign(new Error('Invalid params'), { code: -32602 })], + ['JSON-RPC MethodNotFound', Object.assign(new Error('Method not found'), { code: -32601 })], + ['MCP ResourceNotFound', Object.assign(new Error('Resource not found'), { code: -32002 })], ])('skips %s', (_label, failure) => { expect(shouldHintFeedback(failure)).toBe(false); }); it.each([ ['5xx status', Object.assign(new Error('Bad gateway'), { status: 502 })], + ['JSON-RPC InternalError', Object.assign(new Error('Internal error'), { code: -32603 })], + ['server-defined JSON-RPC error', Object.assign(new Error('Server error'), { code: -32020 })], ['plain error', new Error('Cannot read properties of undefined')], ['Node system error code', Object.assign(new Error('connect ECONNREFUSED'), { code: 'ECONNREFUSED' })], ['error result', { isError: true, content: [{ type: 'text', text: 'Upstream returned 500.' }] }], From 493fe77ab246b64593cba78a354b74e7f64a45fa Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Mon, 30 Nov 2026 14:24:02 -0500 Subject: [PATCH 09/34] ref(mcp): Trim comments --- packages/mcp/src/addFeedbackTool.ts | 5 ++--- packages/mcp/src/errorHints.ts | 17 +++++------------ packages/mcp/src/feedback.ts | 23 ++++++++--------------- scripts/bump-version.js | 3 +-- 4 files changed, 16 insertions(+), 32 deletions(-) diff --git a/packages/mcp/src/addFeedbackTool.ts b/packages/mcp/src/addFeedbackTool.ts index 5deed80a7f72..40b146b58037 100644 --- a/packages/mcp/src/addFeedbackTool.ts +++ b/packages/mcp/src/addFeedbackTool.ts @@ -16,8 +16,7 @@ type ToolResult = { isError?: boolean; }; -// The parts of `McpServer` we use. The public parameter is `object`, like `wrapMcpServerWithSentry`, -// so a server from any MCP SDK version is accepted. +// The public parameter is `object`, like `wrapMcpServerWithSentry`, so any MCP SDK version's server is accepted. interface McpServerLike { registerTool?: ( name: string, @@ -66,7 +65,7 @@ export interface AddFeedbackToolOptions extends FeedbackToolDescriptionOptions { * Reports are sent to Sentry as User Feedback, tagged with `feedback.kind`, `feedback.impact` and `feedback.tool`. * * Errors from the server's other tools also tell the agent about the feedback tool, unless `errorHints` is `false`. - * The tool is not registered when Sentry has no DSN, since it could not deliver anything. + * The tool is not registered when Sentry has no DSN. * * @example * ```ts diff --git a/packages/mcp/src/errorHints.ts b/packages/mcp/src/errorHints.ts index ba47523f5df8..9102c01fd063 100644 --- a/packages/mcp/src/errorHints.ts +++ b/packages/mcp/src/errorHints.ts @@ -10,9 +10,7 @@ export type ErrorHintFilter = (toolName: string, failure: unknown) => boolean; type ToolCallback = (...args: unknown[]) => unknown; -// The JSON-RPC codes the MCP conventions count as client errors: parse error, invalid request, method not -// found, invalid params and resource not found. Every other code, like InternalError (-32603), is the server's. -// Mirrors `isJsonRpcServerError` in `@sentry/core`'s MCP integration. +// 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(); @@ -20,9 +18,7 @@ const wrappedTools = new WeakSet(); let processorAdded = false; /** - * The default `errorHints` filter. Returns `false` for failures that are not the server's to fix: - * upstream HTTP 4xx errors (bad input, auth, not found, rate limits) and JSON-RPC client errors. - * Everything else gets the hint, including failures it cannot classify. + * The default `errorHints` filter. Skips upstream HTTP 4xx and JSON-RPC client errors, which are not the server's to fix. * * @example * ```ts @@ -49,12 +45,9 @@ export function shouldHintFeedback(failure: unknown): boolean { } /** - * Adds a feedback hint to the errors of every tool on the server, the ones already registered - * and the ones registered later. The feedback tool itself is skipped. - * - * Thrown errors get the hint appended to their message, since MCP SDKs build the agent's error - * result from the message alone. An event processor puts the original message back on the - * Sentry event. + * Adds the feedback hint to the errors of every other tool on the server, registered before or after. + * 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. */ export function addErrorHints( server: Record, diff --git a/packages/mcp/src/feedback.ts b/packages/mcp/src/feedback.ts index 37b70234de14..826f08a6ab8d 100644 --- a/packages/mcp/src/feedback.ts +++ b/packages/mcp/src/feedback.ts @@ -7,12 +7,10 @@ import * as z from 'zod/v4'; */ export const DEFAULT_FEEDBACK_TOOL_NAME = 'submit_feedback'; -// Sentry rejects User Feedback messages longer than 4096 code points. Slicing -// UTF-16 units keeps us at or under that. +// Sentry rejects User Feedback messages over 4096 code points; slicing UTF-16 units stays under that. const MAX_FEEDBACK_MESSAGE_LENGTH = 4096; -// Filler that agents have sent instead of a real report, compared after -// lowercasing and dropping everything but letters and digits. +// Filler agents have sent instead of a real report. const PLACEHOLDER_DESCRIPTIONS = new Set([ '', 'na', @@ -73,15 +71,13 @@ export const feedbackInputSchema = { */ export interface FeedbackToolDescriptionOptions { /** - * Name of the MCP server, used in the description so the agent knows where the report goes. - * Without it the description says "this MCP server". + * Names the server in the description. Defaults to "this MCP server". */ serverName?: string; } /** - * Returns the description of the feedback tool. It tells the agent to report only friction - * with this server's tools, at most once per task. + * Returns the feedback tool's description. */ export function getFeedbackToolDescription(options: FeedbackToolDescriptionOptions = {}): string { const server = options.serverName ? `the ${options.serverName} MCP server` : 'this MCP server'; @@ -108,8 +104,7 @@ export interface CaptureAgentFeedbackOptions { */ userId?: string; /** - * Extra scrubbing applied to the message after the built-in token and email scrubbing. - * Feedback events do not go through `beforeSend`, so this is the place to remove sensitive data. + * Runs after the built-in token and email scrubbing. Feedback events skip `beforeSend`, so remove sensitive data here. */ scrub?: (message: string) => string; /** @@ -200,9 +195,8 @@ export interface FeedbackHintOptions { } /** - * Returns a sentence to append to a tool error that likely comes from a bug in the server, - * pointing the agent at the feedback tool. Returns an empty string when the tool is not available, - * so the agent is never told about a tool it cannot call. + * Returns the sentence that points the agent at the feedback tool, for tool errors. + * Empty when the tool is unavailable, so agents are never sent to a tool they cannot call. */ export function feedbackHint(options: FeedbackHintOptions = {}): string { const available = options.available ?? isFeedbackAvailable(); @@ -224,8 +218,7 @@ function scrubSensitiveText(text: string): string { return SCRUB_PATTERNS.reduce((scrubbed, [pattern, replacement]) => scrubbed.replace(pattern, replacement), text); } -// The feedback list shows "Anonymous User" without a name, so name the agent and, -// when user info may be collected, the user it acts for. +// Without a name, the feedback list shows "Anonymous User". function getFeedbackName(options: CaptureAgentFeedbackOptions, scope: Scope): string { const agent = options.clientName ? `MCP agent (${options.clientName})` : 'MCP agent'; if (!getClient()?.getDataCollectionOptions().userInfo) { diff --git a/scripts/bump-version.js b/scripts/bump-version.js index 2f4fc7b6557a..dd56b5ee11bf 100644 --- a/scripts/bump-version.js +++ b/scripts/bump-version.js @@ -20,8 +20,7 @@ function updateWorkspaceDeps(pkgPath, workspaceNames, newVersion, { bumpVersion continue; } - // A peer range (e.g. `@sentry/mcp`'s `"@sentry/core": "^11.0.0"`) lets the package work with any SDK - // in that range, so only exact peer versions follow the release. + // Range peers (like `@sentry/mcp`'s on `@sentry/core`) work with any SDK in range, so only exact peers follow the release. if (depType === 'peerDependencies' && !/^\d/.test(ver)) { continue; } From eefc1d7483846e359ee0ca7bf7e5d50f7d18918d Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Mon, 30 Nov 2026 14:29:47 -0500 Subject: [PATCH 10/34] docs(mcp): Mark @sentry/mcp as beta --- packages/mcp/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 78cfcb8f3a3f..c0d94d9d9322 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -17,6 +17,8 @@ Helpers for MCP servers instrumented with a Sentry SDK. Works with `@modelcontextprotocol/sdk` v1 and `@modelcontextprotocol/server` v2. +> NOTICE: This package is in beta state and may be subject to breaking changes. + It uses the `@sentry/core` your Sentry SDK already installs, so it works with any 11.x SDK. With Yarn Plug'n'Play, add `@sentry/core` to your dependencies at the same version as your SDK. From b7870927501b521047c837f937f003c01375dd91 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Mon, 30 Nov 2026 14:53:54 -0500 Subject: [PATCH 11/34] ref(mcp): Drop the recipient and scope options and the tool name export --- .../node-express-mcp-v1/tests/mcp.test.ts | 2 +- .../node-express-mcp-v2/tests/mcp.test.ts | 2 +- packages/mcp/src/addFeedbackTool.ts | 11 +++--- packages/mcp/src/feedback.ts | 32 ++++++----------- packages/mcp/src/index.ts | 1 - packages/mcp/test/addFeedbackTool.test.ts | 6 +--- packages/mcp/test/errorHints.test.ts | 6 ++-- packages/mcp/test/feedback.test.ts | 34 +++++-------------- 8 files changed, 32 insertions(+), 62 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 a2f0d4a82702..b8bb319e3a38 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 @@ -171,7 +171,7 @@ test('auto-instruments a legacy MCP SDK v1 server (no manual wrap)', async ({ ba { type: 'text', text: expect.stringContaining( - "intentional error for span status testing\n\nIf this keeps failing after you adjust your request, report it to this server's maintainers with `submit_feedback`.", + 'intentional error for span status testing\n\nIf this keeps failing after you adjust your request, report it to the Echo-V1 maintainers 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 5b6d710e11c5..e62e4f2bb335 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 @@ -207,7 +207,7 @@ test('auto-instruments a stable MCP SDK v2 server (no manual wrap)', async ({ ba { type: 'text', text: expect.stringContaining( - "intentional error for span status testing\n\nIf this keeps failing after you adjust your request, report it to this server's maintainers with `submit_feedback`.", + 'intentional error for span status testing\n\nIf this keeps failing after you adjust your request, report it to the Echo-V2 maintainers with `submit_feedback`.', ), }, ]); diff --git a/packages/mcp/src/addFeedbackTool.ts b/packages/mcp/src/addFeedbackTool.ts index 40b146b58037..8d5707fb18b8 100644 --- a/packages/mcp/src/addFeedbackTool.ts +++ b/packages/mcp/src/addFeedbackTool.ts @@ -36,6 +36,11 @@ interface McpServerLike { * Options for `addFeedbackTool`. */ export interface AddFeedbackToolOptions extends FeedbackToolDescriptionOptions { + /** + * Names the server in the tool description and in the error hints, which then say + * "report it to the {serverName} maintainers". Defaults to "this MCP server". + */ + serverName?: string; /** * Name of the tool. Defaults to `submit_feedback`. */ @@ -54,10 +59,6 @@ export interface AddFeedbackToolOptions extends FeedbackToolDescriptionOptions { * Pass a function to choose per failure, or `false` to turn the hints off. */ errorHints?: boolean | ErrorHintFilter; - /** - * Who the error hints tell the agent it reports to. Defaults to "this server's maintainers". - */ - recipient?: string; } /** @@ -107,7 +108,7 @@ export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptio addErrorHints( mcpServer as Record, name, - options.recipient, + options.serverName ? `the ${options.serverName} maintainers` : undefined, typeof options.errorHints === 'function' ? options.errorHints : undefined, ); } diff --git a/packages/mcp/src/feedback.ts b/packages/mcp/src/feedback.ts index 826f08a6ab8d..ec49cf8d87c6 100644 --- a/packages/mcp/src/feedback.ts +++ b/packages/mcp/src/feedback.ts @@ -1,4 +1,3 @@ -import type { Scope } from '@sentry/core'; import { captureFeedback, getClient, getCombinedScopeData, getCurrentScope, getIsolationScope } from '@sentry/core'; import * as z from 'zod/v4'; @@ -107,10 +106,6 @@ export interface CaptureAgentFeedbackOptions { * Runs after the built-in token and email scrubbing. Feedback events skip `beforeSend`, so remove sensitive data here. */ scrub?: (message: string) => string; - /** - * Scope to capture the feedback on. Defaults to the current scope. - */ - scope?: Scope; } /** @@ -153,21 +148,16 @@ export function captureAgentFeedback( message = options.scrub(message); } - const scope = options.scope ?? getCurrentScope(); - const feedbackId = captureFeedback( - { - source: 'mcp_agent', - name: getFeedbackName(options, scope), - message: message.slice(0, MAX_FEEDBACK_MESSAGE_LENGTH), - tags: { - 'feedback.kind': feedback.kind, - 'feedback.impact': feedback.impact, - ...(feedback.toolName ? { 'feedback.tool': feedback.toolName } : {}), - }, + const feedbackId = captureFeedback({ + source: 'mcp_agent', + name: getFeedbackName(options), + message: message.slice(0, MAX_FEEDBACK_MESSAGE_LENGTH), + tags: { + 'feedback.kind': feedback.kind, + 'feedback.impact': feedback.impact, + ...(feedback.toolName ? { 'feedback.tool': feedback.toolName } : {}), }, - {}, - scope, - ); + }); return { ok: true, feedbackId }; } @@ -219,13 +209,13 @@ function scrubSensitiveText(text: string): string { } // Without a name, the feedback list shows "Anonymous User". -function getFeedbackName(options: CaptureAgentFeedbackOptions, scope: Scope): string { +function getFeedbackName(options: CaptureAgentFeedbackOptions): string { const agent = options.clientName ? `MCP agent (${options.clientName})` : 'MCP agent'; if (!getClient()?.getDataCollectionOptions().userInfo) { return agent; } - const userId = options.userId ?? getCombinedScopeData(getIsolationScope(), scope).user.id; + const userId = options.userId ?? getCombinedScopeData(getIsolationScope(), getCurrentScope()).user.id; return userId ? `${agent} for user ${userId}` : agent; } diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index 770f193aa295..97305c068141 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -4,7 +4,6 @@ export { shouldHintFeedback } from './errorHints'; export type { ErrorHintFilter } from './errorHints'; export { captureAgentFeedback, - DEFAULT_FEEDBACK_TOOL_NAME, feedbackHint, feedbackInputSchema, getFeedbackToolDescription, diff --git a/packages/mcp/test/addFeedbackTool.test.ts b/packages/mcp/test/addFeedbackTool.test.ts index a3b1e74e6c9d..0853db797c94 100644 --- a/packages/mcp/test/addFeedbackTool.test.ts +++ b/packages/mcp/test/addFeedbackTool.test.ts @@ -44,11 +44,7 @@ describe('addFeedbackTool', () => { const handler = registerTool.mock.lastCall![2]; expect(handler(report)).toEqual({ content: [{ type: 'text', text: 'Feedback sent (ID event-id).' }] }); - expect(captureFeedback).toHaveBeenCalledWith( - expect.objectContaining({ name: 'MCP agent (cursor)' }), - {}, - expect.anything(), - ); + expect(captureFeedback).toHaveBeenCalledWith(expect.objectContaining({ name: 'MCP agent (cursor)' })); }); it('falls back to the legacy tool() method', () => { diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index 8641fe8755e8..4019e8b68cd3 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -67,9 +67,9 @@ describe.each(['executor', 'handler'] as const)('error hints (tool %s)', callbac } }); - it('names the recipient and tool name given to addFeedbackTool', async () => { + it('names the server and tool name given to addFeedbackTool', async () => { const server = createServer(callbackKey); - addFeedbackTool(server, { name: 'submit_feedback_to_acme_team', recipient: 'the Acme team' }); + addFeedbackTool(server, { name: 'submit_feedback_to_acme_team', serverName: 'Acme' }); server.registerTool('failed', {}, () => ({ isError: true, content: [{ type: 'text', text: 'nope' }] })); await expect(server.call('failed')).resolves.toEqual({ @@ -78,7 +78,7 @@ describe.each(['executor', 'handler'] as const)('error hints (tool %s)', callbac { type: 'text', text: 'nope' }, { type: 'text', - text: 'If this keeps failing after you adjust your request, report it to the Acme team with `submit_feedback_to_acme_team`.', + text: 'If this keeps failing after you adjust your request, report it to the Acme maintainers with `submit_feedback_to_acme_team`.', }, ], }); diff --git a/packages/mcp/test/feedback.test.ts b/packages/mcp/test/feedback.test.ts index 93cc7b9d3048..6fd0c12e009b 100644 --- a/packages/mcp/test/feedback.test.ts +++ b/packages/mcp/test/feedback.test.ts @@ -37,17 +37,13 @@ describe('captureAgentFeedback', () => { ); expect(result).toEqual({ ok: true, feedbackId: 'event-id' }); - expect(captureFeedback).toHaveBeenCalledWith( - { - source: 'mcp_agent', - name: 'MCP agent (opencode) for user 123', - message: - 'Task: find slow endpoints\nTool: search_traces\n\nNo tool returns p95 latency. Contact [REDACTED_EMAIL] with Bearer [REDACTED_TOKEN]', - tags: { 'feedback.kind': 'missing', 'feedback.impact': 'blocked', 'feedback.tool': 'search_traces' }, - }, - {}, - expect.anything(), - ); + expect(captureFeedback).toHaveBeenCalledWith({ + source: 'mcp_agent', + name: 'MCP agent (opencode) for user 123', + message: + 'Task: find slow endpoints\nTool: search_traces\n\nNo tool returns p95 latency. Contact [REDACTED_EMAIL] with Bearer [REDACTED_TOKEN]', + tags: { 'feedback.kind': 'missing', 'feedback.impact': 'blocked', 'feedback.tool': 'search_traces' }, + }); }); it('applies the custom scrubber after the built-in one', () => { @@ -58,8 +54,6 @@ describe('captureAgentFeedback', () => { expect(captureFeedback).toHaveBeenCalledWith( expect.objectContaining({ message: 'Task: read logs\n\nBucket [REDACTED_PATH] failed' }), - {}, - expect.anything(), ); }); @@ -68,11 +62,7 @@ describe('captureAgentFeedback', () => { captureAgentFeedback({ task: 'x', kind: 'idea', impact: 'friction', description: 'Add p95 latency.' }); - expect(captureFeedback).toHaveBeenCalledWith( - expect.objectContaining({ name: 'MCP agent for user 42' }), - {}, - expect.anything(), - ); + expect(captureFeedback).toHaveBeenCalledWith(expect.objectContaining({ name: 'MCP agent for user 42' })); }); it('leaves the user out of the name when dataCollection.userInfo is false', () => { @@ -83,11 +73,7 @@ describe('captureAgentFeedback', () => { { clientName: 'cursor', userId: '123' }, ); - expect(captureFeedback).toHaveBeenCalledWith( - expect.objectContaining({ name: 'MCP agent (cursor)' }), - {}, - expect.anything(), - ); + expect(captureFeedback).toHaveBeenCalledWith(expect.objectContaining({ name: 'MCP agent (cursor)' })); }); it.each(['placeholder', 'N/A', ' noop ', 'TODO.', 'test'])('rejects the filler description %j', description => { @@ -102,8 +88,6 @@ describe('captureAgentFeedback', () => { expect(captureFeedback).toHaveBeenCalledWith( expect.objectContaining({ message: `Task: x\n\n${'a'.repeat(4096 - 'Task: x\n\n'.length)}` }), - {}, - expect.anything(), ); }); }); From a56b941e3e0b27714ffd70221032bb27356d32ee Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Mon, 30 Nov 2026 15:05:33 -0500 Subject: [PATCH 12/34] fix(mcp): Check for a Sentry client when the feedback tool runs, not when it's added --- .../cloudflare-mcp-agent/package.json | 1 + .../cloudflare-mcp-agent/src/index.ts | 3 + .../tests/feedback.test.ts | 74 +++++++++++++++++++ .../cloudflare-mcp/package.json | 1 + .../cloudflare-mcp/src/index.ts | 3 + .../cloudflare-mcp/tests/feedback.test.ts | 50 +++++++++++++ packages/mcp/README.md | 3 +- packages/mcp/src/addFeedbackTool.ts | 11 ++- packages/mcp/src/errorHints.ts | 6 +- packages/mcp/src/feedback.ts | 2 +- packages/mcp/src/index.ts | 8 +- packages/mcp/test/addFeedbackTool.test.ts | 9 ++- packages/mcp/test/errorHints.test.ts | 9 +++ 13 files changed, 161 insertions(+), 19 deletions(-) create mode 100644 dev-packages/e2e-tests/test-applications/cloudflare-mcp-agent/tests/feedback.test.ts create mode 100644 dev-packages/e2e-tests/test-applications/cloudflare-mcp/tests/feedback.test.ts diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-mcp-agent/package.json b/dev-packages/e2e-tests/test-applications/cloudflare-mcp-agent/package.json index 0549f5cae5b7..2b17b465acc8 100644 --- a/dev-packages/e2e-tests/test-applications/cloudflare-mcp-agent/package.json +++ b/dev-packages/e2e-tests/test-applications/cloudflare-mcp-agent/package.json @@ -17,6 +17,7 @@ "@modelcontextprotocol/sdk": "1.32.1", "@modelcontextprotocol/server": "2.3.1", "@sentry/cloudflare": "file:../../packed/sentry-cloudflare-packed.tgz", + "@sentry/mcp": "file:../../packed/sentry-mcp-packed.tgz", "agents": "0.31.0", "zod": "^4.3.6" }, diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-mcp-agent/src/index.ts b/dev-packages/e2e-tests/test-applications/cloudflare-mcp-agent/src/index.ts index 6bdf6ed19c78..a55488651188 100644 --- a/dev-packages/e2e-tests/test-applications/cloudflare-mcp-agent/src/index.ts +++ b/dev-packages/e2e-tests/test-applications/cloudflare-mcp-agent/src/index.ts @@ -2,6 +2,7 @@ import * as Sentry from '@sentry/cloudflare'; import { McpAgent } from 'agents/mcp'; import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import * as z from 'zod'; +import { addFeedbackTool } from '@sentry/mcp'; class MyMCPAgentBase extends McpAgent> { #mcpServer = Sentry.wrapMcpServerWithSentry( @@ -16,6 +17,8 @@ class MyMCPAgentBase extends McpAgent> { } async init(): Promise { + addFeedbackTool(this.#mcpServer); + this.#mcpServer.registerTool( 'my-tool', { diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-mcp-agent/tests/feedback.test.ts b/dev-packages/e2e-tests/test-applications/cloudflare-mcp-agent/tests/feedback.test.ts new file mode 100644 index 000000000000..67ed3a20c4e2 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-mcp-agent/tests/feedback.test.ts @@ -0,0 +1,74 @@ +import { expect, test } from '@playwright/test'; +import { waitForEnvelopeItem } from '@sentry-internal/test-utils'; + +async function rpc(baseURL: string, sessionId: string | undefined, body: unknown): Promise { + return fetch(`${baseURL}/mcp`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json, text/event-stream', + ...(sessionId ? { 'Mcp-Session-Id': sessionId } : {}), + }, + body: JSON.stringify(body), + }); +} + +async function result(response: Response): Promise { + const text = await response.text(); + const data = text + .split('\n') + .filter(line => line.startsWith('data: ')) + .at(-1); + return JSON.parse(data ? data.slice(6) : text).result; +} + +test('McpAgent registers the feedback tool in init() and sends reports', async ({ baseURL }) => { + const init = await rpc(baseURL!, undefined, { + jsonrpc: '2.0', + id: 0, + method: 'initialize', + params: { + protocolVersion: '2024-11-05', + capabilities: {}, + clientInfo: { name: 'feedback-client', version: '1.0.0' }, + }, + }); + const sessionId = init.headers.get('Mcp-Session-Id')!; + await rpc(baseURL!, sessionId, { jsonrpc: '2.0', method: 'notifications/initialized' }); + + const tools = await result( + await rpc(baseURL!, sessionId, { jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }), + ); + expect(tools.tools.map((t: { name: string }) => t.name)).toContain('submit_feedback'); + + const feedbackPromise = waitForEnvelopeItem('cloudflare-mcp-agent', item => item[0].type === 'feedback'); + const sent = await result( + await rpc(baseURL!, sessionId, { + jsonrpc: '2.0', + id: 2, + method: 'tools/call', + params: { + name: 'submit_feedback', + arguments: { + task: 'report from an agent', + kind: 'idea', + impact: 'friction', + description: 'Feedback from a Cloudflare McpAgent.', + }, + }, + }), + ); + expect(sent.content[0].text).toMatch(/^Feedback sent \(ID [0-9a-f]{32}\)\.$/); + + const [, feedback] = await feedbackPromise; + expect(feedback).toMatchObject({ + contexts: { + feedback: { + source: 'mcp_agent', + name: 'MCP agent (feedback-client)', + message: 'Task: report from an agent\n\nFeedback from a Cloudflare McpAgent.', + }, + }, + tags: { 'feedback.kind': 'idea', 'feedback.impact': 'friction' }, + }); +}); diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-mcp/package.json b/dev-packages/e2e-tests/test-applications/cloudflare-mcp/package.json index 9c878cf5dcb0..5ee6c2622df0 100644 --- a/dev-packages/e2e-tests/test-applications/cloudflare-mcp/package.json +++ b/dev-packages/e2e-tests/test-applications/cloudflare-mcp/package.json @@ -16,6 +16,7 @@ "dependencies": { "@modelcontextprotocol/server": "^2.0.0", "@sentry/cloudflare": "file:../../packed/sentry-cloudflare-packed.tgz", + "@sentry/mcp": "file:../../packed/sentry-mcp-packed.tgz", "agents": "0.20.1", "zod": "^4.2.0" }, diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-mcp/src/index.ts b/dev-packages/e2e-tests/test-applications/cloudflare-mcp/src/index.ts index 1dac0ff759e5..f5285d733fbb 100644 --- a/dev-packages/e2e-tests/test-applications/cloudflare-mcp/src/index.ts +++ b/dev-packages/e2e-tests/test-applications/cloudflare-mcp/src/index.ts @@ -14,6 +14,7 @@ import * as Sentry from '@sentry/cloudflare'; import { McpServer } from '@modelcontextprotocol/server'; import { createMcpHandler } from 'agents/mcp/server'; import { z } from 'zod'; +import { addFeedbackTool } from '@sentry/mcp'; function createServer() { const server = Sentry.wrapMcpServerWithSentry( @@ -54,6 +55,8 @@ function createServer() { }, ); + addFeedbackTool(server); + return server; } diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-mcp/tests/feedback.test.ts b/dev-packages/e2e-tests/test-applications/cloudflare-mcp/tests/feedback.test.ts new file mode 100644 index 000000000000..7b4703249dbc --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-mcp/tests/feedback.test.ts @@ -0,0 +1,50 @@ +import { expect, test } from '@playwright/test'; +import { waitForEnvelopeItem } from '@sentry-internal/test-utils'; + +test('sends feedback from a server built per request', async ({ baseURL }) => { + const feedbackPromise = waitForEnvelopeItem('cloudflare-mcp', item => item[0].type === 'feedback'); + + const response = await fetch(`${baseURL}/mcp?protocol=modern&case=feedback`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json, text/event-stream', + 'MCP-Protocol-Version': '2026-07-28', + 'Mcp-Method': 'tools/call', + 'Mcp-Name': 'submit_feedback', + }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 'feedback-call', + method: 'tools/call', + params: { + _meta: { + 'io.modelcontextprotocol/protocolVersion': '2026-07-28', + 'io.modelcontextprotocol/clientInfo': { name: 'cloudflare-feedback-client', version: '1.0.0' }, + 'io.modelcontextprotocol/clientCapabilities': {}, + }, + name: 'submit_feedback', + arguments: { + task: 'report from an agent', + kind: 'idea', + impact: 'friction', + description: 'Per-request server.', + }, + }, + }), + }); + + expect(response.status).toBe(200); + await expect(response.text()).resolves.toContain('Feedback sent'); + + const [, feedback] = await feedbackPromise; + expect(feedback).toMatchObject({ + contexts: { + feedback: { + source: 'mcp_agent', + name: 'MCP agent (cloudflare-feedback-client)', + message: 'Task: report from an agent\n\nPer-request server.', + }, + }, + }); +}); diff --git a/packages/mcp/README.md b/packages/mcp/README.md index c0d94d9d9322..49a22548aecb 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -38,7 +38,8 @@ const server = Sentry.wrapMcpServerWithSentry(new McpServer({ name: 'acme', vers addFeedbackTool(server, { serverName: 'Acme' }); ``` -The tool is called `submit_feedback` unless you pass `name`. It is not registered when Sentry has no DSN. +The tool is called `submit_feedback` unless you pass `name`. Until Sentry has a client with a DSN, it returns an error to the +agent and other tools' errors get no hint. ### Registering the tool yourself diff --git a/packages/mcp/src/addFeedbackTool.ts b/packages/mcp/src/addFeedbackTool.ts index 8d5707fb18b8..c6f25e6cf557 100644 --- a/packages/mcp/src/addFeedbackTool.ts +++ b/packages/mcp/src/addFeedbackTool.ts @@ -66,7 +66,7 @@ export interface AddFeedbackToolOptions extends FeedbackToolDescriptionOptions { * Reports are sent to Sentry as User Feedback, tagged with `feedback.kind`, `feedback.impact` and `feedback.tool`. * * Errors from the server's other tools also tell the agent about the feedback tool, unless `errorHints` is `false`. - * The tool is not registered when Sentry has no DSN. + * It can be called before `Sentry.init()`: without a client, the tool returns an error and other tools' errors get no hint. * * @example * ```ts @@ -77,15 +77,14 @@ export interface AddFeedbackToolOptions extends FeedbackToolDescriptionOptions { export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptions = {}): void { const server = mcpServer as McpServerLike; - if (!isFeedbackAvailable()) { - DEBUG_BUILD && debug.log('[MCP] Not registering the feedback tool because Sentry has no DSN.'); - return; - } - const name = options.name ?? DEFAULT_FEEDBACK_TOOL_NAME; const description = options.description ?? getFeedbackToolDescription(options); const handler = (args: AgentFeedback): ToolResult => { + if (!isFeedbackAvailable()) { + return { isError: true, content: [{ type: 'text', text: "Feedback isn't available on this server." }] }; + } + const result = captureAgentFeedback(args, { clientName: server.server?.getClientVersion?.()?.name, scrub: options.scrub, diff --git a/packages/mcp/src/errorHints.ts b/packages/mcp/src/errorHints.ts index 9102c01fd063..182058725c22 100644 --- a/packages/mcp/src/errorHints.ts +++ b/packages/mcp/src/errorHints.ts @@ -1,6 +1,6 @@ import type { Event, EventHint } from '@sentry/core'; import { fill, getGlobalScope, isObjectLike } from '@sentry/core'; -import { feedbackHint } from './feedback'; +import { feedbackHint, isFeedbackAvailable } from './feedback'; /** * Decides whether a failed tool call points the agent at the feedback tool. @@ -57,7 +57,9 @@ export function addErrorHints( ): void { addRestoreMessageProcessor(); - const shouldHint = filter ?? ((_toolName: string, failure: unknown) => shouldHintFeedback(failure)); + const filterFailure = filter ?? ((_toolName: string, failure: unknown) => shouldHintFeedback(failure)); + // Checked per failure, since on Cloudflare the client only exists inside a request. + const shouldHint: ErrorHintFilter = (toolName, failure) => isFeedbackAvailable() && filterFailure(toolName, failure); const hint = feedbackHint({ toolName: feedbackToolName, recipient, available: true }); const wrap = (name: unknown, tool: unknown): void => { if (typeof name === 'string' && name !== feedbackToolName) { diff --git a/packages/mcp/src/feedback.ts b/packages/mcp/src/feedback.ts index ec49cf8d87c6..a0f592450e30 100644 --- a/packages/mcp/src/feedback.ts +++ b/packages/mcp/src/feedback.ts @@ -175,7 +175,7 @@ export interface FeedbackHintOptions { */ toolName?: string; /** - * Whether the agent can call the feedback tool. Defaults to `isFeedbackAvailable()`. + * Whether the agent can call the feedback tool. Defaults to whether Sentry has a client with a DSN. */ available?: boolean; /** diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index 97305c068141..1a2244b1b75e 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -2,13 +2,7 @@ export { addFeedbackTool } from './addFeedbackTool'; export type { AddFeedbackToolOptions } from './addFeedbackTool'; export { shouldHintFeedback } from './errorHints'; export type { ErrorHintFilter } from './errorHints'; -export { - captureAgentFeedback, - feedbackHint, - feedbackInputSchema, - getFeedbackToolDescription, - isFeedbackAvailable, -} from './feedback'; +export { captureAgentFeedback, feedbackHint, feedbackInputSchema, getFeedbackToolDescription } from './feedback'; export type { AgentFeedback, CaptureAgentFeedbackOptions, diff --git a/packages/mcp/test/addFeedbackTool.test.ts b/packages/mcp/test/addFeedbackTool.test.ts index 0853db797c94..5abe6b946117 100644 --- a/packages/mcp/test/addFeedbackTool.test.ts +++ b/packages/mcp/test/addFeedbackTool.test.ts @@ -72,12 +72,17 @@ describe('addFeedbackTool', () => { expect(captureFeedback).not.toHaveBeenCalled(); }); - it('does not register the tool when Sentry has no DSN', () => { + it('registers the tool before Sentry has a client and returns an error until it has one', () => { vi.mocked(getClient).mockReturnValue(undefined); const registerTool = vi.fn(); addFeedbackTool({ registerTool }); + const handler = registerTool.mock.lastCall![2]; - expect(registerTool).not.toHaveBeenCalled(); + expect(handler(report)).toEqual({ + isError: true, + content: [{ type: 'text', text: "Feedback isn't available on this server." }], + }); + expect(captureFeedback).not.toHaveBeenCalled(); }); }); diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index 4019e8b68cd3..a8bb04fdcd1c 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -151,6 +151,15 @@ describe.each(['executor', 'handler'] as const)('error hints (tool %s)', callbac expect(error.message).toBe('query is required'); }); + it('skips the hint while Sentry has no client', async () => { + const server = createServer(callbackKey); + addFeedbackTool(server); + server.registerTool('failed', {}, () => ({ isError: true, content: [{ type: 'text', text: 'nope' }] })); + vi.mocked(getClient).mockReturnValue(undefined); + + await expect(server.call('failed')).resolves.toEqual({ isError: true, content: [{ type: 'text', text: 'nope' }] }); + }); + it('does not wrap tools when errorHints is false', async () => { const server = createServer(callbackKey); addFeedbackTool(server, { errorHints: false }); From ee551a4b1aeccab7bae8e688c546f21f731652c6 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Mon, 30 Nov 2026 15:07:48 -0500 Subject: [PATCH 13/34] test(mcp): Cover a Sentry client that appears after the feedback tool is added --- packages/mcp/test/addFeedbackTool.test.ts | 9 ++++++++- packages/mcp/test/errorHints.test.ts | 15 +++++++++++++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/packages/mcp/test/addFeedbackTool.test.ts b/packages/mcp/test/addFeedbackTool.test.ts index 5abe6b946117..60211dca71b9 100644 --- a/packages/mcp/test/addFeedbackTool.test.ts +++ b/packages/mcp/test/addFeedbackTool.test.ts @@ -72,7 +72,9 @@ describe('addFeedbackTool', () => { expect(captureFeedback).not.toHaveBeenCalled(); }); - it('registers the tool before Sentry has a client and returns an error until it has one', () => { + // On Cloudflare the client only exists inside a request, so the tool can be added before it. + it('registers the tool before Sentry has a client and sends reports once it has one', () => { + const client = getClient(); vi.mocked(getClient).mockReturnValue(undefined); const registerTool = vi.fn(); @@ -84,5 +86,10 @@ describe('addFeedbackTool', () => { content: [{ type: 'text', text: "Feedback isn't available on this server." }], }); expect(captureFeedback).not.toHaveBeenCalled(); + + vi.mocked(getClient).mockReturnValue(client); + + expect(handler(report)).toEqual({ content: [{ type: 'text', text: 'Feedback sent (ID event-id).' }] }); + expect(captureFeedback).toHaveBeenCalledTimes(1); }); }); diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index a8bb04fdcd1c..6954fdcc07a6 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -151,13 +151,24 @@ describe.each(['executor', 'handler'] as const)('error hints (tool %s)', callbac expect(error.message).toBe('query is required'); }); - it('skips the hint while Sentry has no client', async () => { + it('skips the hint while Sentry has no client and adds it once it has one', async () => { + const client = getClient(); + vi.mocked(getClient).mockReturnValue(undefined); const server = createServer(callbackKey); addFeedbackTool(server); server.registerTool('failed', {}, () => ({ isError: true, content: [{ type: 'text', text: 'nope' }] })); - vi.mocked(getClient).mockReturnValue(undefined); await expect(server.call('failed')).resolves.toEqual({ isError: true, content: [{ type: 'text', text: 'nope' }] }); + + vi.mocked(getClient).mockReturnValue(client); + + await expect(server.call('failed')).resolves.toEqual({ + isError: true, + content: [ + { type: 'text', text: 'nope' }, + { type: 'text', text: HINT }, + ], + }); }); it('does not wrap tools when errorHints is false', async () => { From f7ec36f5a1b620b3f3772f093f10b782a4e50df8 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Mon, 30 Nov 2026 15:34:10 -0500 Subject: [PATCH 14/34] feat(mcp): Return hint and withHint from addFeedbackTool, skip errors that already have a hint --- packages/mcp/README.md | 26 ++++++++++++-- packages/mcp/src/addFeedbackTool.ts | 43 ++++++++++++++++++++--- packages/mcp/src/errorHints.ts | 18 +++++++++- packages/mcp/src/index.ts | 2 +- packages/mcp/test/addFeedbackTool.test.ts | 39 ++++++++++++++++++++ packages/mcp/test/errorHints.test.ts | 29 +++++++++++++++ 6 files changed, 148 insertions(+), 9 deletions(-) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 49a22548aecb..8b86ca08e31b 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -65,7 +65,9 @@ server.registerTool( 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 maintainers with `submit_feedback`." Thrown errors -get the hint in their message, and Sentry still records the original message. +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 +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, rate limits) and JSON-RPC client errors such as invalid params. Build on it to skip more, or turn the hints off: @@ -79,7 +81,27 @@ addFeedbackTool(server, { addFeedbackTool(server, { errorHints: false }); ``` -If you register the tool yourself, append `feedbackHint()` to your own error messages. +### Hints on other results + +Some results aren't errors but still suggest a problem, like a search that comes back empty. Add the hint to those +yourself with the `withHint` or `hint` that `addFeedbackTool` returns. Both use the tool's name and `serverName`, and +leave the result unchanged until Sentry has a client: + +```js +const { withHint } = addFeedbackTool(server, { serverName: 'Orders' }); + +server.registerTool('search_orders', { ... }, async ({ query }) => { + const orders = await searchOrders(query); + const result = { content: [{ type: 'text', text: JSON.stringify(orders) }], structuredContent: { orders } }; + + return orders.length ? result : withHint(result, 'If this stays empty after you broaden the query'); +}); +``` + +`withHint` adds the hint as its own text block and leaves `structuredContent` and the existing content alone. `hint` +returns just the sentence, for your own messages. + +If you register the tool yourself, use `feedbackHint()` instead. ## Support diff --git a/packages/mcp/src/addFeedbackTool.ts b/packages/mcp/src/addFeedbackTool.ts index c6f25e6cf557..975556257000 100644 --- a/packages/mcp/src/addFeedbackTool.ts +++ b/packages/mcp/src/addFeedbackTool.ts @@ -6,6 +6,7 @@ import type { AgentFeedback, FeedbackToolDescriptionOptions } from './feedback'; import { captureAgentFeedback, DEFAULT_FEEDBACK_TOOL_NAME, + feedbackHint, feedbackInputSchema, getFeedbackToolDescription, isFeedbackAvailable, @@ -61,24 +62,45 @@ export interface AddFeedbackToolOptions extends FeedbackToolDescriptionOptions { errorHints?: boolean | ErrorHintFilter; } +/** + * What `addFeedbackTool` returns, for pointing agents at the feedback tool from results that are not errors. + */ +export interface FeedbackTool { + /** + * Returns the sentence that points the agent at the feedback tool, using its name and `serverName`. + * Empty while Sentry has no client. `condition` defaults to "If this keeps failing after you adjust your request". + */ + hint(condition?: string): string; + /** + * Returns a copy of `result` with the hint as an extra text block. `structuredContent` and the existing + * content are left as they are, and the result is returned unchanged while Sentry has no client. + */ + withHint(result: T, condition?: string): T; +} + /** * Registers a tool on an MCP server that lets agents report friction with the server's tools. * Reports are sent to Sentry as User Feedback, tagged with `feedback.kind`, `feedback.impact` and `feedback.tool`. * * Errors from the server's other tools also tell the agent about the feedback tool, unless `errorHints` is `false`. + * Successful results are never modified; use the returned `hint` or `withHint` to add the hint to those yourself. * It can be called before `Sentry.init()`: without a client, the tool returns an error and other tools' errors get no hint. * * @example * ```ts * const server = Sentry.wrapMcpServerWithSentry(new McpServer({ name: 'acme', version: '1.0.0' })); - * addFeedbackTool(server, { serverName: 'Acme' }); + * const { withHint } = addFeedbackTool(server, { serverName: 'Acme' }); + * + * // In a tool whose search came back empty + * return withHint({ content }, 'If this stays empty after you broaden the query'); * ``` */ -export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptions = {}): void { +export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptions = {}): FeedbackTool { const server = mcpServer as McpServerLike; const name = options.name ?? DEFAULT_FEEDBACK_TOOL_NAME; const description = options.description ?? getFeedbackToolDescription(options); + const recipient = options.serverName ? `the ${options.serverName} maintainers` : undefined; const handler = (args: AgentFeedback): ToolResult => { if (!isFeedbackAvailable()) { @@ -97,20 +119,31 @@ export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptio return { content: [{ type: 'text', text: `Feedback sent (ID ${result.feedbackId}).` }] }; }; - if (!registerTool(server, name, description, handler)) { + const registered = registerTool(server, name, description, handler); + const hint = (condition?: string): string => + registered ? feedbackHint({ condition, toolName: name, recipient }) : ''; + const withHint = (result: T, condition?: string): T => { + const text = hint(condition); + + return text ? { ...result, content: [...(result.content ?? []), { type: 'text', text }] } : result; + }; + + if (!registered) { DEBUG_BUILD && debug.warn('[MCP] Could not register the feedback tool: the server has no `registerTool` or `tool` method.'); - return; + return { hint, withHint }; } if (options.errorHints !== false) { addErrorHints( mcpServer as Record, name, - options.serverName ? `the ${options.serverName} maintainers` : undefined, + recipient, typeof options.errorHints === 'function' ? options.errorHints : undefined, ); } + + return { hint, withHint }; } function registerTool( diff --git a/packages/mcp/src/errorHints.ts b/packages/mcp/src/errorHints.ts index 182058725c22..6f581eae238d 100644 --- a/packages/mcp/src/errorHints.ts +++ b/packages/mcp/src/errorHints.ts @@ -58,8 +58,11 @@ export function addErrorHints( addRestoreMessageProcessor(); const filterFailure = filter ?? ((_toolName: string, failure: unknown) => shouldHintFeedback(failure)); + // Every hint ends with this, so a failure that already has one (written by the tool) gets no second one. + const hintMarker = `with \`${feedbackToolName}\``; // Checked per failure, since on Cloudflare the client only exists inside a request. - const shouldHint: ErrorHintFilter = (toolName, failure) => isFeedbackAvailable() && filterFailure(toolName, failure); + const shouldHint: ErrorHintFilter = (toolName, failure) => + isFeedbackAvailable() && !mentions(failure, hintMarker) && filterFailure(toolName, failure); const hint = feedbackHint({ toolName: feedbackToolName, recipient, available: true }); const wrap = (name: unknown, tool: unknown): void => { if (typeof name === 'string' && name !== feedbackToolName) { @@ -135,6 +138,19 @@ async function callWithHint( } } +function mentions(failure: unknown, text: string): boolean { + if (failure instanceof Error) { + return failure.message.includes(text); + } + + return ( + isErrorResult(failure) && + failure.content.some( + block => isObjectLike(block) && typeof block['text'] === 'string' && block['text'].includes(text), + ) + ); +} + function isErrorResult(result: unknown): result is { isError: true; content: unknown[] } { return isObjectLike(result) && result['isError'] === true && Array.isArray(result['content']); } diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index 1a2244b1b75e..34bcbc3ea78f 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -1,5 +1,5 @@ export { addFeedbackTool } from './addFeedbackTool'; -export type { AddFeedbackToolOptions } from './addFeedbackTool'; +export type { AddFeedbackToolOptions, FeedbackTool } from './addFeedbackTool'; export { shouldHintFeedback } from './errorHints'; export type { ErrorHintFilter } from './errorHints'; export { captureAgentFeedback, feedbackHint, feedbackInputSchema, getFeedbackToolDescription } from './feedback'; diff --git a/packages/mcp/test/addFeedbackTool.test.ts b/packages/mcp/test/addFeedbackTool.test.ts index 60211dca71b9..310716fdd4fd 100644 --- a/packages/mcp/test/addFeedbackTool.test.ts +++ b/packages/mcp/test/addFeedbackTool.test.ts @@ -47,6 +47,45 @@ describe('addFeedbackTool', () => { expect(captureFeedback).toHaveBeenCalledWith(expect.objectContaining({ name: 'MCP agent (cursor)' })); }); + it('returns a hint bound to the tool name and server name', () => { + const { hint, withHint } = addFeedbackTool( + { registerTool: vi.fn() }, + { name: 'submit_feedback_to_orders', serverName: 'Orders' }, + ); + const expected = + 'If this stays empty after you broaden the query, report it to the Orders maintainers with `submit_feedback_to_orders`.'; + + expect(hint('If this stays empty after you broaden the query')).toBe(expected); + expect(hint()).toBe( + 'If this keeps failing after you adjust your request, report it to the Orders maintainers with `submit_feedback_to_orders`.', + ); + + const result = { + content: [{ type: 'text', text: '[]' }], + structuredContent: { orders: [] }, + }; + expect(withHint(result, 'If this stays empty after you broaden the query')).toEqual({ + content: [ + { type: 'text', text: '[]' }, + { type: 'text', text: expected }, + ], + structuredContent: { orders: [] }, + }); + }); + + it('returns empty hints while Sentry has no client or the tool could not be registered', () => { + const result = { content: [{ type: 'text', text: '[]' }] }; + + const unregistered = addFeedbackTool({}); + expect(unregistered.hint()).toBe(''); + expect(unregistered.withHint(result)).toBe(result); + + vi.mocked(getClient).mockReturnValue(undefined); + const { hint, withHint } = addFeedbackTool({ registerTool: vi.fn() }); + expect(hint()).toBe(''); + expect(withHint(result)).toBe(result); + }); + it('falls back to the legacy tool() method', () => { const tool = vi.fn(); diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index 6954fdcc07a6..f45c9f34b3d1 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -171,6 +171,35 @@ describe.each(['executor', 'handler'] as const)('error hints (tool %s)', callbac }); }); + it('does not add a second hint to failures that already have one', async () => { + const server = createServer(callbackKey); + const { withHint, hint } = addFeedbackTool(server); + const ownHint = withHint( + { isError: true, content: [{ type: 'text', text: 'Index is rebuilding.' }] }, + 'If this keeps failing after the rebuild', + ); + const error = new Error(`Upstream returned 500. ${hint('If retrying does not help')}`); + server.registerTool('hinted-result', {}, () => ownHint); + server.registerTool('hinted-throw', {}, () => { + throw error; + }); + + 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 maintainers with `submit_feedback`.", + ); + }); + + it('never modifies successful results, structured or not', async () => { + const server = createServer(callbackKey); + const structured = { content: [{ type: 'text', text: '{"orders":[]}' }], structuredContent: { orders: [] } }; + addFeedbackTool(server); + server.registerTool('structured', {}, () => structured); + + await expect(server.call('structured')).resolves.toBe(structured); + }); + it('does not wrap tools when errorHints is false', async () => { const server = createServer(callbackKey); addFeedbackTool(server, { errorHints: false }); From 990c4aa7686316589ecc25d1305ba6eda16f9eef Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 11:07:31 -0500 Subject: [PATCH 15/34] ref(mcp): Type the errorHints failure as a thrown Error or a tool error result The filter only ever receives a thrown Error or a result with isError: true, so type it that way and export ToolErrorResult. Callbacks can now narrow with instanceof or read content without casts. Examples use CustomError so they don't suggest schema validation errors, which the MCP SDK handles before the tool runs. --- packages/mcp/README.md | 2 +- packages/mcp/src/errorHints.ts | 26 +++++++++++++-------- packages/mcp/src/index.ts | 2 +- packages/mcp/test/errorHints.test.ts | 35 ++++++++++++++++++++++++---- 4 files changed, 48 insertions(+), 17 deletions(-) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 8b86ca08e31b..c2ed0381e085 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -76,7 +76,7 @@ rate limits) and JSON-RPC client errors such as invalid params. Build on it to s import { addFeedbackTool, shouldHintFeedback } from '@sentry/mcp'; addFeedbackTool(server, { - errorHints: (toolName, failure) => shouldHintFeedback(failure) && !(failure instanceof ValidationError), + errorHints: (toolName, failure) => shouldHintFeedback(failure) && !(failure instanceof CustomError), }); addFeedbackTool(server, { errorHints: false }); ``` diff --git a/packages/mcp/src/errorHints.ts b/packages/mcp/src/errorHints.ts index 6f581eae238d..983073005a86 100644 --- a/packages/mcp/src/errorHints.ts +++ b/packages/mcp/src/errorHints.ts @@ -2,11 +2,20 @@ import type { Event, EventHint } from '@sentry/core'; import { fill, getGlobalScope, isObjectLike } from '@sentry/core'; import { feedbackHint, isFeedbackAvailable } from './feedback'; +/** + * A tool result with `isError: true`. + */ +export interface ToolErrorResult { + isError: true; + content: unknown[]; + [key: string]: unknown; +} + /** * Decides whether a failed tool call points the agent at the feedback tool. * `failure` is the error the tool threw, or the error result it returned. */ -export type ErrorHintFilter = (toolName: string, failure: unknown) => boolean; +export type ErrorHintFilter = (toolName: string, failure: Error | ToolErrorResult) => boolean; type ToolCallback = (...args: unknown[]) => unknown; @@ -23,7 +32,7 @@ let processorAdded = false; * @example * ```ts * addFeedbackTool(server, { - * errorHints: (toolName, failure) => shouldHintFeedback(failure) && !(failure instanceof ValidationError), + * errorHints: (toolName, failure) => shouldHintFeedback(failure) && !(failure instanceof CustomError), * }); * ``` */ @@ -57,7 +66,7 @@ export function addErrorHints( ): void { addRestoreMessageProcessor(); - const filterFailure = filter ?? ((_toolName: string, failure: unknown) => shouldHintFeedback(failure)); + const filterFailure: ErrorHintFilter = filter ?? ((_toolName, failure) => shouldHintFeedback(failure)); // Every hint ends with this, so a failure that already has one (written by the tool) gets no second one. const hintMarker = `with \`${feedbackToolName}\``; // Checked per failure, since on Cloudflare the client only exists inside a request. @@ -138,20 +147,17 @@ async function callWithHint( } } -function mentions(failure: unknown, text: string): boolean { +function mentions(failure: Error | ToolErrorResult, text: string): boolean { if (failure instanceof Error) { return failure.message.includes(text); } - return ( - isErrorResult(failure) && - failure.content.some( - block => isObjectLike(block) && typeof block['text'] === 'string' && block['text'].includes(text), - ) + return failure.content.some( + block => isObjectLike(block) && typeof block['text'] === 'string' && block['text'].includes(text), ); } -function isErrorResult(result: unknown): result is { isError: true; content: unknown[] } { +function isErrorResult(result: unknown): result is ToolErrorResult { return isObjectLike(result) && result['isError'] === true && Array.isArray(result['content']); } diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index 34bcbc3ea78f..5af72ba87766 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -1,7 +1,7 @@ export { addFeedbackTool } from './addFeedbackTool'; export type { AddFeedbackToolOptions, FeedbackTool } from './addFeedbackTool'; export { shouldHintFeedback } from './errorHints'; -export type { ErrorHintFilter } from './errorHints'; +export type { ErrorHintFilter, ToolErrorResult } from './errorHints'; export { captureAgentFeedback, feedbackHint, feedbackInputSchema, getFeedbackToolDescription } from './feedback'; export type { AgentFeedback, diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index f45c9f34b3d1..aaeccc25fcbd 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -2,6 +2,7 @@ import type { Event, EventProcessor } from '@sentry/core'; import { getClient, getGlobalScope } from '@sentry/core'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { addFeedbackTool } from '../src/addFeedbackTool'; +import type { ToolErrorResult } from '../src/errorHints'; import { shouldHintFeedback } from '../src/errorHints'; vi.mock('@sentry/core', async importOriginal => { @@ -140,17 +141,41 @@ describe.each(['executor', 'handler'] as const)('error hints (tool %s)', callbac it('skips failures the errorHints filter rejects', async () => { const server = createServer(callbackKey); - class ValidationError extends Error {} - const error = new ValidationError('query is required'); - addFeedbackTool(server, { errorHints: (_name, failure) => !(failure instanceof ValidationError) }); - server.registerTool('validates', {}, () => { + class CustomError extends Error {} + const error = new CustomError('query is required'); + addFeedbackTool(server, { errorHints: (_name, failure) => !(failure instanceof CustomError) }); + server.registerTool('custom', {}, () => { throw error; }); - await expect(server.call('validates')).rejects.toBe(error); + await expect(server.call('custom')).rejects.toBe(error); expect(error.message).toBe('query is required'); }); + it('passes thrown errors and error results to the errorHints filter', async () => { + const server = createServer(callbackKey); + const failures: Array = []; + const thrown = new Error('Upstream returned 500'); + const returned = { isError: true, content: [{ type: 'text', text: 'nope' }] }; + addFeedbackTool(server, { + errorHints: (_name, failure) => { + failures.push(failure); + + // Narrows without casts: an Error, or a result with `content` + return failure instanceof Error || failure.content.length > 0; + }, + }); + server.registerTool('throws', {}, () => { + throw thrown; + }); + server.registerTool('returns', {}, () => returned); + + await expect(server.call('throws')).rejects.toBe(thrown); + await server.call('returns'); + + expect(failures).toEqual([thrown, returned]); + }); + it('skips the hint while Sentry has no client and adds it once it has one', async () => { const client = getClient(); vi.mocked(getClient).mockReturnValue(undefined); From 9e0a0765a15fa9d78123c494340b9e9ebb2200bb Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 11:20:03 -0500 Subject: [PATCH 16/34] feat(mcp): Add withFeedbackHint to add the hint without the addFeedbackTool return value It uses the tool from the last addFeedbackTool call, so tools defined away from the server setup don't need the returned withHint threaded to them. --- packages/mcp/README.md | 15 ++++---- packages/mcp/src/addFeedbackTool.ts | 44 ++++++++++++++++++----- packages/mcp/src/index.ts | 2 +- packages/mcp/test/addFeedbackTool.test.ts | 34 +++++++++++++++++- 4 files changed, 79 insertions(+), 16 deletions(-) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index c2ed0381e085..8307dccdcc7d 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -84,22 +84,25 @@ addFeedbackTool(server, { errorHints: false }); ### Hints on other results Some results aren't errors but still suggest a problem, like a search that comes back empty. Add the hint to those -yourself with the `withHint` or `hint` that `addFeedbackTool` returns. Both use the tool's name and `serverName`, and -leave the result unchanged until Sentry has a client: +yourself with `withFeedbackHint`. It uses the name and `serverName` from your `addFeedbackTool` call, and leaves the +result unchanged until Sentry has a client: ```js -const { withHint } = addFeedbackTool(server, { serverName: 'Orders' }); +import { addFeedbackTool, withFeedbackHint } from '@sentry/mcp'; + +addFeedbackTool(server, { serverName: 'Orders' }); server.registerTool('search_orders', { ... }, async ({ query }) => { const orders = await searchOrders(query); const result = { content: [{ type: 'text', text: JSON.stringify(orders) }], structuredContent: { orders } }; - return orders.length ? result : withHint(result, 'If this stays empty after you broaden the query'); + return orders.length ? result : withFeedbackHint(result, 'If this stays empty after you broaden the query'); }); ``` -`withHint` adds the hint as its own text block and leaves `structuredContent` and the existing content alone. `hint` -returns just the sentence, for your own messages. +`withFeedbackHint` adds the hint as its own text block and leaves `structuredContent` and the existing content alone. +`addFeedbackTool` also returns `withHint`, the same function bound to that call, and `hint`, which returns just the +sentence for your own messages. If you register the tool yourself, use `feedbackHint()` instead. diff --git a/packages/mcp/src/addFeedbackTool.ts b/packages/mcp/src/addFeedbackTool.ts index 975556257000..12b62804c18a 100644 --- a/packages/mcp/src/addFeedbackTool.ts +++ b/packages/mcp/src/addFeedbackTool.ts @@ -78,21 +78,46 @@ export interface FeedbackTool { withHint(result: T, condition?: string): T; } +/** + * The feedback tool from the last `addFeedbackTool` call. A process runs one server config, so the last call wins. + */ +let registeredTool: { name: string; recipient: string | undefined } | undefined; + +/** + * Returns a copy of `result` with a hint that points the agent at the tool `addFeedbackTool` registered, as an extra + * text block. `structuredContent` and the existing content are left as they are. The result is returned unchanged + * before `addFeedbackTool` registers the tool and while Sentry has no client. + * `condition` defaults to "If this keeps failing after you adjust your request". + * + * @example + * ```ts + * // In a tool whose search came back empty + * return withFeedbackHint({ content }, 'If this stays empty after you broaden the query'); + * ``` + */ +export function withFeedbackHint(result: T, condition?: string): T { + const text = registeredTool + ? feedbackHint({ condition, toolName: registeredTool.name, recipient: registeredTool.recipient }) + : ''; + + return appendHint(result, text); +} + /** * Registers a tool on an MCP server that lets agents report friction with the server's tools. * Reports are sent to Sentry as User Feedback, tagged with `feedback.kind`, `feedback.impact` and `feedback.tool`. * * Errors from the server's other tools also tell the agent about the feedback tool, unless `errorHints` is `false`. - * Successful results are never modified; use the returned `hint` or `withHint` to add the hint to those yourself. + * Successful results are never modified; use `withFeedbackHint`, or the returned `hint` or `withHint`, to add the hint to those yourself. * It can be called before `Sentry.init()`: without a client, the tool returns an error and other tools' errors get no hint. * * @example * ```ts * const server = Sentry.wrapMcpServerWithSentry(new McpServer({ name: 'acme', version: '1.0.0' })); - * const { withHint } = addFeedbackTool(server, { serverName: 'Acme' }); + * addFeedbackTool(server, { serverName: 'Acme' }); * * // In a tool whose search came back empty - * return withHint({ content }, 'If this stays empty after you broaden the query'); + * return withFeedbackHint({ content }, 'If this stays empty after you broaden the query'); * ``` */ export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptions = {}): FeedbackTool { @@ -122,11 +147,8 @@ export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptio const registered = registerTool(server, name, description, handler); const hint = (condition?: string): string => registered ? feedbackHint({ condition, toolName: name, recipient }) : ''; - const withHint = (result: T, condition?: string): T => { - const text = hint(condition); - - return text ? { ...result, content: [...(result.content ?? []), { type: 'text', text }] } : result; - }; + const withHint = (result: T, condition?: string): T => + appendHint(result, hint(condition)); if (!registered) { DEBUG_BUILD && @@ -134,6 +156,8 @@ export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptio return { hint, withHint }; } + registeredTool = { name, recipient }; + if (options.errorHints !== false) { addErrorHints( mcpServer as Record, @@ -146,6 +170,10 @@ export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptio return { hint, withHint }; } +function appendHint(result: T, text: string): T { + return text ? { ...result, content: [...(result.content ?? []), { type: 'text', text }] } : result; +} + function registerTool( server: McpServerLike, name: string, diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index 5af72ba87766..2c3eb0e64f36 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -1,4 +1,4 @@ -export { addFeedbackTool } from './addFeedbackTool'; +export { addFeedbackTool, withFeedbackHint } from './addFeedbackTool'; export type { AddFeedbackToolOptions, FeedbackTool } from './addFeedbackTool'; export { shouldHintFeedback } from './errorHints'; export type { ErrorHintFilter, ToolErrorResult } from './errorHints'; diff --git a/packages/mcp/test/addFeedbackTool.test.ts b/packages/mcp/test/addFeedbackTool.test.ts index 310716fdd4fd..59673591c5b1 100644 --- a/packages/mcp/test/addFeedbackTool.test.ts +++ b/packages/mcp/test/addFeedbackTool.test.ts @@ -1,6 +1,6 @@ import { captureFeedback, getClient } from '@sentry/core'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { addFeedbackTool } from '../src/addFeedbackTool'; +import { addFeedbackTool, withFeedbackHint } from '../src/addFeedbackTool'; import { feedbackInputSchema } from '../src/feedback'; vi.mock('@sentry/core', async importOriginal => { @@ -86,6 +86,38 @@ describe('addFeedbackTool', () => { expect(withHint(result)).toBe(result); }); + it('withFeedbackHint uses the tool from the last addFeedbackTool call', () => { + addFeedbackTool({ registerTool: vi.fn() }, { serverName: 'Acme' }); + addFeedbackTool({ registerTool: vi.fn() }, { name: 'submit_feedback_to_orders', serverName: 'Orders' }); + const result = { content: [{ type: 'text', text: '[]' }], structuredContent: { orders: [] } }; + + expect(withFeedbackHint(result, 'If this stays empty after you broaden the query')).toEqual({ + content: [ + { type: 'text', text: '[]' }, + { + type: 'text', + text: 'If this stays empty after you broaden the query, report it to the Orders maintainers with `submit_feedback_to_orders`.', + }, + ], + structuredContent: { orders: [] }, + }); + }); + + it('withFeedbackHint returns the result unchanged before a tool is registered or while Sentry has no client', async () => { + const result = { content: [{ type: 'text', text: '[]' }] }; + vi.resetModules(); + const fresh = await import('../src/addFeedbackTool'); + + expect(fresh.withFeedbackHint(result)).toBe(result); + + fresh.addFeedbackTool({}); + expect(fresh.withFeedbackHint(result)).toBe(result); + + fresh.addFeedbackTool({ registerTool: vi.fn() }); + vi.mocked(getClient).mockReturnValue(undefined); + expect(fresh.withFeedbackHint(result)).toBe(result); + }); + it('falls back to the legacy tool() method', () => { const tool = vi.fn(); From 1392a9b5ecd109e09fad0f6e01a4c9d468c2e20d Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 11:22:27 -0500 Subject: [PATCH 17/34] ref(mcp): Drop hint and withHint from the addFeedbackTool return value withFeedbackHint covers the same case without threading the return value, so addFeedbackTool returns nothing and there is one way to add the hint. --- packages/mcp/README.md | 2 -- packages/mcp/src/addFeedbackTool.ts | 38 +++------------------- packages/mcp/src/index.ts | 2 +- packages/mcp/test/addFeedbackTool.test.ts | 39 ----------------------- packages/mcp/test/errorHints.test.ts | 9 +++--- 5 files changed, 11 insertions(+), 79 deletions(-) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 8307dccdcc7d..a42d61fd5543 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -101,8 +101,6 @@ server.registerTool('search_orders', { ... }, async ({ query }) => { ``` `withFeedbackHint` adds the hint as its own text block and leaves `structuredContent` and the existing content alone. -`addFeedbackTool` also returns `withHint`, the same function bound to that call, and `hint`, which returns just the -sentence for your own messages. If you register the tool yourself, use `feedbackHint()` instead. diff --git a/packages/mcp/src/addFeedbackTool.ts b/packages/mcp/src/addFeedbackTool.ts index 12b62804c18a..ac3ebe19f8a6 100644 --- a/packages/mcp/src/addFeedbackTool.ts +++ b/packages/mcp/src/addFeedbackTool.ts @@ -62,22 +62,6 @@ export interface AddFeedbackToolOptions extends FeedbackToolDescriptionOptions { errorHints?: boolean | ErrorHintFilter; } -/** - * What `addFeedbackTool` returns, for pointing agents at the feedback tool from results that are not errors. - */ -export interface FeedbackTool { - /** - * Returns the sentence that points the agent at the feedback tool, using its name and `serverName`. - * Empty while Sentry has no client. `condition` defaults to "If this keeps failing after you adjust your request". - */ - hint(condition?: string): string; - /** - * Returns a copy of `result` with the hint as an extra text block. `structuredContent` and the existing - * content are left as they are, and the result is returned unchanged while Sentry has no client. - */ - withHint(result: T, condition?: string): T; -} - /** * The feedback tool from the last `addFeedbackTool` call. A process runs one server config, so the last call wins. */ @@ -100,7 +84,7 @@ export function withFeedbackHint(result: T, c ? feedbackHint({ condition, toolName: registeredTool.name, recipient: registeredTool.recipient }) : ''; - return appendHint(result, text); + return text ? { ...result, content: [...(result.content ?? []), { type: 'text', text }] } : result; } /** @@ -108,7 +92,7 @@ export function withFeedbackHint(result: T, c * Reports are sent to Sentry as User Feedback, tagged with `feedback.kind`, `feedback.impact` and `feedback.tool`. * * Errors from the server's other tools also tell the agent about the feedback tool, unless `errorHints` is `false`. - * Successful results are never modified; use `withFeedbackHint`, or the returned `hint` or `withHint`, to add the hint to those yourself. + * Successful results are never modified; use `withFeedbackHint` to add the hint to those yourself. * It can be called before `Sentry.init()`: without a client, the tool returns an error and other tools' errors get no hint. * * @example @@ -120,7 +104,7 @@ export function withFeedbackHint(result: T, c * return withFeedbackHint({ content }, 'If this stays empty after you broaden the query'); * ``` */ -export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptions = {}): FeedbackTool { +export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptions = {}): void { const server = mcpServer as McpServerLike; const name = options.name ?? DEFAULT_FEEDBACK_TOOL_NAME; @@ -144,16 +128,10 @@ export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptio return { content: [{ type: 'text', text: `Feedback sent (ID ${result.feedbackId}).` }] }; }; - const registered = registerTool(server, name, description, handler); - const hint = (condition?: string): string => - registered ? feedbackHint({ condition, toolName: name, recipient }) : ''; - const withHint = (result: T, condition?: string): T => - appendHint(result, hint(condition)); - - if (!registered) { + if (!registerTool(server, name, description, handler)) { DEBUG_BUILD && debug.warn('[MCP] Could not register the feedback tool: the server has no `registerTool` or `tool` method.'); - return { hint, withHint }; + return; } registeredTool = { name, recipient }; @@ -166,12 +144,6 @@ export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptio typeof options.errorHints === 'function' ? options.errorHints : undefined, ); } - - return { hint, withHint }; -} - -function appendHint(result: T, text: string): T { - return text ? { ...result, content: [...(result.content ?? []), { type: 'text', text }] } : result; } function registerTool( diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index 2c3eb0e64f36..afa5f4159eea 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -1,5 +1,5 @@ export { addFeedbackTool, withFeedbackHint } from './addFeedbackTool'; -export type { AddFeedbackToolOptions, FeedbackTool } from './addFeedbackTool'; +export type { AddFeedbackToolOptions } from './addFeedbackTool'; export { shouldHintFeedback } from './errorHints'; export type { ErrorHintFilter, ToolErrorResult } from './errorHints'; export { captureAgentFeedback, feedbackHint, feedbackInputSchema, getFeedbackToolDescription } from './feedback'; diff --git a/packages/mcp/test/addFeedbackTool.test.ts b/packages/mcp/test/addFeedbackTool.test.ts index 59673591c5b1..1b787e6fd695 100644 --- a/packages/mcp/test/addFeedbackTool.test.ts +++ b/packages/mcp/test/addFeedbackTool.test.ts @@ -47,45 +47,6 @@ describe('addFeedbackTool', () => { expect(captureFeedback).toHaveBeenCalledWith(expect.objectContaining({ name: 'MCP agent (cursor)' })); }); - it('returns a hint bound to the tool name and server name', () => { - const { hint, withHint } = addFeedbackTool( - { registerTool: vi.fn() }, - { name: 'submit_feedback_to_orders', serverName: 'Orders' }, - ); - const expected = - 'If this stays empty after you broaden the query, report it to the Orders maintainers with `submit_feedback_to_orders`.'; - - expect(hint('If this stays empty after you broaden the query')).toBe(expected); - expect(hint()).toBe( - 'If this keeps failing after you adjust your request, report it to the Orders maintainers with `submit_feedback_to_orders`.', - ); - - const result = { - content: [{ type: 'text', text: '[]' }], - structuredContent: { orders: [] }, - }; - expect(withHint(result, 'If this stays empty after you broaden the query')).toEqual({ - content: [ - { type: 'text', text: '[]' }, - { type: 'text', text: expected }, - ], - structuredContent: { orders: [] }, - }); - }); - - it('returns empty hints while Sentry has no client or the tool could not be registered', () => { - const result = { content: [{ type: 'text', text: '[]' }] }; - - const unregistered = addFeedbackTool({}); - expect(unregistered.hint()).toBe(''); - expect(unregistered.withHint(result)).toBe(result); - - vi.mocked(getClient).mockReturnValue(undefined); - const { hint, withHint } = addFeedbackTool({ registerTool: vi.fn() }); - expect(hint()).toBe(''); - expect(withHint(result)).toBe(result); - }); - it('withFeedbackHint uses the tool from the last addFeedbackTool call', () => { addFeedbackTool({ registerTool: vi.fn() }, { serverName: 'Acme' }); addFeedbackTool({ registerTool: vi.fn() }, { name: 'submit_feedback_to_orders', serverName: 'Orders' }); diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index aaeccc25fcbd..84f892b536cc 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -1,9 +1,10 @@ import type { Event, EventProcessor } from '@sentry/core'; import { getClient, getGlobalScope } from '@sentry/core'; import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { addFeedbackTool } from '../src/addFeedbackTool'; +import { addFeedbackTool, withFeedbackHint } from '../src/addFeedbackTool'; import type { ToolErrorResult } from '../src/errorHints'; import { shouldHintFeedback } from '../src/errorHints'; +import { feedbackHint } from '../src/feedback'; vi.mock('@sentry/core', async importOriginal => { const actual = await importOriginal>(); @@ -198,12 +199,12 @@ describe.each(['executor', 'handler'] as const)('error hints (tool %s)', callbac it('does not add a second hint to failures that already have one', async () => { const server = createServer(callbackKey); - const { withHint, hint } = addFeedbackTool(server); - const ownHint = withHint( + addFeedbackTool(server); + const ownHint = withFeedbackHint( { isError: true, content: [{ type: 'text', text: 'Index is rebuilding.' }] }, 'If this keeps failing after the rebuild', ); - const error = new Error(`Upstream returned 500. ${hint('If retrying does not help')}`); + const error = new Error(`Upstream returned 500. ${feedbackHint({ condition: 'If retrying does not help' })}`); server.registerTool('hinted-result', {}, () => ownHint); server.registerTool('hinted-throw', {}, () => { throw error; From c5d02d746c2120f4e35f02598a1f8bf66ae091a4 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 11:24:38 -0500 Subject: [PATCH 18/34] feat(mcp): Default feedbackHint to the tool from the last addFeedbackTool call feedbackHint now takes its tool name and recipient from addFeedbackTool like withFeedbackHint does, so a thrown error only needs a condition. The state moves to feedback.ts so both helpers share it. --- packages/mcp/README.md | 7 +++- packages/mcp/src/addFeedbackTool.ts | 29 ++-------------- packages/mcp/src/feedback.ts | 40 ++++++++++++++++++++--- packages/mcp/src/index.ts | 10 ++++-- packages/mcp/test/addFeedbackTool.test.ts | 17 ++++++++-- packages/mcp/test/errorHints.test.ts | 4 +-- 6 files changed, 68 insertions(+), 39 deletions(-) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index a42d61fd5543..882e991afd5e 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -101,8 +101,13 @@ server.registerTool('search_orders', { ... }, async ({ query }) => { ``` `withFeedbackHint` adds the hint as its own text block and leaves `structuredContent` and the existing content alone. +For just the sentence, such as in an error you throw, use `feedbackHint`, which takes the same defaults: -If you register the tool yourself, use `feedbackHint()` instead. +```js +throw new Error(`Index is rebuilding. ${feedbackHint({ condition: 'If this keeps failing after the rebuild' })}`); +``` + +If you register the tool yourself, pass `toolName` and `recipient` to `feedbackHint`. ## Support diff --git a/packages/mcp/src/addFeedbackTool.ts b/packages/mcp/src/addFeedbackTool.ts index ac3ebe19f8a6..a92aee6c97c7 100644 --- a/packages/mcp/src/addFeedbackTool.ts +++ b/packages/mcp/src/addFeedbackTool.ts @@ -6,10 +6,10 @@ import type { AgentFeedback, FeedbackToolDescriptionOptions } from './feedback'; import { captureAgentFeedback, DEFAULT_FEEDBACK_TOOL_NAME, - feedbackHint, feedbackInputSchema, getFeedbackToolDescription, isFeedbackAvailable, + setRegisteredFeedbackTool, } from './feedback'; type ToolResult = { @@ -62,31 +62,6 @@ export interface AddFeedbackToolOptions extends FeedbackToolDescriptionOptions { errorHints?: boolean | ErrorHintFilter; } -/** - * The feedback tool from the last `addFeedbackTool` call. A process runs one server config, so the last call wins. - */ -let registeredTool: { name: string; recipient: string | undefined } | undefined; - -/** - * Returns a copy of `result` with a hint that points the agent at the tool `addFeedbackTool` registered, as an extra - * text block. `structuredContent` and the existing content are left as they are. The result is returned unchanged - * before `addFeedbackTool` registers the tool and while Sentry has no client. - * `condition` defaults to "If this keeps failing after you adjust your request". - * - * @example - * ```ts - * // In a tool whose search came back empty - * return withFeedbackHint({ content }, 'If this stays empty after you broaden the query'); - * ``` - */ -export function withFeedbackHint(result: T, condition?: string): T { - const text = registeredTool - ? feedbackHint({ condition, toolName: registeredTool.name, recipient: registeredTool.recipient }) - : ''; - - return text ? { ...result, content: [...(result.content ?? []), { type: 'text', text }] } : result; -} - /** * Registers a tool on an MCP server that lets agents report friction with the server's tools. * Reports are sent to Sentry as User Feedback, tagged with `feedback.kind`, `feedback.impact` and `feedback.tool`. @@ -134,7 +109,7 @@ export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptio return; } - registeredTool = { name, recipient }; + setRegisteredFeedbackTool(name, recipient); if (options.errorHints !== false) { addErrorHints( diff --git a/packages/mcp/src/feedback.ts b/packages/mcp/src/feedback.ts index a0f592450e30..4ecafe251532 100644 --- a/packages/mcp/src/feedback.ts +++ b/packages/mcp/src/feedback.ts @@ -171,7 +171,7 @@ export interface FeedbackHintOptions { */ condition?: string; /** - * Name of the registered feedback tool. Defaults to `submit_feedback`. + * Name of the registered feedback tool. Defaults to the name from the last `addFeedbackTool` call, or `submit_feedback`. */ toolName?: string; /** @@ -179,11 +179,24 @@ export interface FeedbackHintOptions { */ available?: boolean; /** - * Who the agent reports to. Defaults to "this server's maintainers". + * Who the agent reports to. Defaults to "the {serverName} maintainers" from the last `addFeedbackTool` call, + * or "this server's maintainers". */ recipient?: string; } +/** + * The feedback tool from the last `addFeedbackTool` call. A process runs one server config, so the last call wins. + */ +let registeredTool: { name: string; recipient: string | undefined } | undefined; + +/** + * Records the tool `addFeedbackTool` registered, so `feedbackHint` and `withFeedbackHint` default to it. + */ +export function setRegisteredFeedbackTool(name: string, recipient: string | undefined): void { + registeredTool = { name, recipient }; +} + /** * Returns the sentence that points the agent at the feedback tool, for tool errors. * Empty when the tool is unavailable, so agents are never sent to a tool they cannot call. @@ -195,9 +208,28 @@ export function feedbackHint(options: FeedbackHintOptions = {}): string { } const condition = options.condition ?? 'If this keeps failing after you adjust your request'; - const recipient = options.recipient ?? "this server's maintainers"; + const recipient = options.recipient ?? registeredTool?.recipient ?? "this server's maintainers"; + const toolName = options.toolName ?? registeredTool?.name ?? DEFAULT_FEEDBACK_TOOL_NAME; + + return `${condition}, report it to ${recipient} with \`${toolName}\`.`; +} + +/** + * Returns a copy of `result` with a hint that points the agent at the tool `addFeedbackTool` registered, as an extra + * text block. `structuredContent` and the existing content are left as they are. The result is returned unchanged + * before `addFeedbackTool` registers the tool and while Sentry has no client. + * `condition` defaults to "If this keeps failing after you adjust your request". + * + * @example + * ```ts + * // In a tool whose search came back empty + * return withFeedbackHint({ content }, 'If this stays empty after you broaden the query'); + * ``` + */ +export function withFeedbackHint(result: T, condition?: string): T { + const text = registeredTool ? feedbackHint({ condition }) : ''; - return `${condition}, report it to ${recipient} with \`${options.toolName ?? DEFAULT_FEEDBACK_TOOL_NAME}\`.`; + return text ? { ...result, content: [...(result.content ?? []), { type: 'text', text }] } : result; } function isPlaceholder(text: string): boolean { diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index afa5f4159eea..f39b4d48e80c 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -1,8 +1,14 @@ -export { addFeedbackTool, withFeedbackHint } from './addFeedbackTool'; +export { addFeedbackTool } from './addFeedbackTool'; export type { AddFeedbackToolOptions } from './addFeedbackTool'; export { shouldHintFeedback } from './errorHints'; export type { ErrorHintFilter, ToolErrorResult } from './errorHints'; -export { captureAgentFeedback, feedbackHint, feedbackInputSchema, getFeedbackToolDescription } from './feedback'; +export { + captureAgentFeedback, + feedbackHint, + feedbackInputSchema, + getFeedbackToolDescription, + withFeedbackHint, +} from './feedback'; export type { AgentFeedback, CaptureAgentFeedbackOptions, diff --git a/packages/mcp/test/addFeedbackTool.test.ts b/packages/mcp/test/addFeedbackTool.test.ts index 1b787e6fd695..50082c7f4b6b 100644 --- a/packages/mcp/test/addFeedbackTool.test.ts +++ b/packages/mcp/test/addFeedbackTool.test.ts @@ -1,7 +1,7 @@ import { captureFeedback, getClient } from '@sentry/core'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { addFeedbackTool, withFeedbackHint } from '../src/addFeedbackTool'; -import { feedbackInputSchema } from '../src/feedback'; +import { addFeedbackTool } from '../src/addFeedbackTool'; +import { feedbackHint, feedbackInputSchema, withFeedbackHint } from '../src/feedback'; vi.mock('@sentry/core', async importOriginal => { const actual = await importOriginal>(); @@ -67,7 +67,7 @@ describe('addFeedbackTool', () => { it('withFeedbackHint returns the result unchanged before a tool is registered or while Sentry has no client', async () => { const result = { content: [{ type: 'text', text: '[]' }] }; vi.resetModules(); - const fresh = await import('../src/addFeedbackTool'); + const fresh = { ...(await import('../src/addFeedbackTool')), ...(await import('../src/feedback')) }; expect(fresh.withFeedbackHint(result)).toBe(result); @@ -79,6 +79,17 @@ describe('addFeedbackTool', () => { expect(fresh.withFeedbackHint(result)).toBe(result); }); + it('feedbackHint defaults to the tool from the last addFeedbackTool call', () => { + addFeedbackTool({ registerTool: vi.fn() }, { name: 'submit_feedback_to_orders', serverName: 'Orders' }); + + expect(feedbackHint({ condition: 'If retrying does not help' })).toBe( + 'If retrying does not help, report it to the Orders maintainers with `submit_feedback_to_orders`.', + ); + expect(feedbackHint({ toolName: 'report_issue', recipient: 'the Sentry MCP team' })).toBe( + 'If this keeps failing after you adjust your request, report it to the Sentry MCP team with `report_issue`.', + ); + }); + it('falls back to the legacy tool() method', () => { const tool = vi.fn(); diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index 84f892b536cc..591c8cb47f2b 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -1,10 +1,10 @@ import type { Event, EventProcessor } from '@sentry/core'; import { getClient, getGlobalScope } from '@sentry/core'; import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { addFeedbackTool, withFeedbackHint } from '../src/addFeedbackTool'; +import { addFeedbackTool } from '../src/addFeedbackTool'; import type { ToolErrorResult } from '../src/errorHints'; import { shouldHintFeedback } from '../src/errorHints'; -import { feedbackHint } from '../src/feedback'; +import { feedbackHint, withFeedbackHint } from '../src/feedback'; vi.mock('@sentry/core', async importOriginal => { const actual = await importOriginal>(); From b02c6f260d8d40cd710a806d5c464682923af220 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 11:26:03 -0500 Subject: [PATCH 19/34] ref(mcp): Take the feedbackHint condition as its first argument Matches withFeedbackHint(result, condition), and the common call only needs the condition. toolName, recipient and available move to the second argument. --- packages/mcp/README.md | 4 ++-- packages/mcp/src/errorHints.ts | 2 +- packages/mcp/src/feedback.ts | 17 ++++++++++------- packages/mcp/test/addFeedbackTool.test.ts | 4 ++-- packages/mcp/test/errorHints.test.ts | 2 +- packages/mcp/test/feedback.test.ts | 4 ++-- 6 files changed, 18 insertions(+), 15 deletions(-) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 882e991afd5e..69fbbec19dfa 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -104,10 +104,10 @@ server.registerTool('search_orders', { ... }, async ({ query }) => { For just the sentence, such as in an error you throw, use `feedbackHint`, which takes the same defaults: ```js -throw new Error(`Index is rebuilding. ${feedbackHint({ condition: 'If this keeps failing after the rebuild' })}`); +throw new Error(`Index is rebuilding. ${feedbackHint('If this keeps failing after the rebuild')}`); ``` -If you register the tool yourself, pass `toolName` and `recipient` to `feedbackHint`. +If you register the tool yourself, pass `toolName` and `recipient` as the second argument to `feedbackHint`. ## Support diff --git a/packages/mcp/src/errorHints.ts b/packages/mcp/src/errorHints.ts index 983073005a86..42342402a6c6 100644 --- a/packages/mcp/src/errorHints.ts +++ b/packages/mcp/src/errorHints.ts @@ -72,7 +72,7 @@ export function addErrorHints( // Checked per failure, since on Cloudflare the client only exists inside a request. const shouldHint: ErrorHintFilter = (toolName, failure) => isFeedbackAvailable() && !mentions(failure, hintMarker) && filterFailure(toolName, failure); - const hint = feedbackHint({ toolName: feedbackToolName, recipient, available: true }); + const hint = feedbackHint(undefined, { toolName: feedbackToolName, recipient, available: true }); const wrap = (name: unknown, tool: unknown): void => { if (typeof name === 'string' && name !== feedbackToolName) { wrapRegisteredTool(name, tool, hint, shouldHint); diff --git a/packages/mcp/src/feedback.ts b/packages/mcp/src/feedback.ts index 4ecafe251532..1d12c5f99219 100644 --- a/packages/mcp/src/feedback.ts +++ b/packages/mcp/src/feedback.ts @@ -166,10 +166,6 @@ export function captureAgentFeedback( * Options for `feedbackHint`. */ export interface FeedbackHintOptions { - /** - * When the agent should report it. Defaults to "If this keeps failing after you adjust your request". - */ - condition?: string; /** * Name of the registered feedback tool. Defaults to the name from the last `addFeedbackTool` call, or `submit_feedback`. */ @@ -200,14 +196,21 @@ export function setRegisteredFeedbackTool(name: string, recipient: string | unde /** * Returns the sentence that points the agent at the feedback tool, for tool errors. * Empty when the tool is unavailable, so agents are never sent to a tool they cannot call. + * + * @example + * ```ts + * throw new Error(`Index is rebuilding. ${feedbackHint('If this keeps failing after the rebuild')}`); + * ``` */ -export function feedbackHint(options: FeedbackHintOptions = {}): string { +export function feedbackHint( + condition = 'If this keeps failing after you adjust your request', + options: FeedbackHintOptions = {}, +): string { const available = options.available ?? isFeedbackAvailable(); if (!available) { return ''; } - const condition = options.condition ?? 'If this keeps failing after you adjust your request'; const recipient = options.recipient ?? registeredTool?.recipient ?? "this server's maintainers"; const toolName = options.toolName ?? registeredTool?.name ?? DEFAULT_FEEDBACK_TOOL_NAME; @@ -227,7 +230,7 @@ export function feedbackHint(options: FeedbackHintOptions = {}): string { * ``` */ export function withFeedbackHint(result: T, condition?: string): T { - const text = registeredTool ? feedbackHint({ condition }) : ''; + const text = registeredTool ? feedbackHint(condition) : ''; return text ? { ...result, content: [...(result.content ?? []), { type: 'text', text }] } : result; } diff --git a/packages/mcp/test/addFeedbackTool.test.ts b/packages/mcp/test/addFeedbackTool.test.ts index 50082c7f4b6b..0dffc14b82f4 100644 --- a/packages/mcp/test/addFeedbackTool.test.ts +++ b/packages/mcp/test/addFeedbackTool.test.ts @@ -82,10 +82,10 @@ describe('addFeedbackTool', () => { it('feedbackHint defaults to the tool from the last addFeedbackTool call', () => { addFeedbackTool({ registerTool: vi.fn() }, { name: 'submit_feedback_to_orders', serverName: 'Orders' }); - expect(feedbackHint({ condition: 'If retrying does not help' })).toBe( + expect(feedbackHint('If retrying does not help')).toBe( 'If retrying does not help, report it to the Orders maintainers with `submit_feedback_to_orders`.', ); - expect(feedbackHint({ toolName: 'report_issue', recipient: 'the Sentry MCP team' })).toBe( + expect(feedbackHint(undefined, { toolName: 'report_issue', recipient: 'the Sentry MCP team' })).toBe( 'If this keeps failing after you adjust your request, report it to the Sentry MCP team with `report_issue`.', ); }); diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index 591c8cb47f2b..287167bb12cb 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -204,7 +204,7 @@ describe.each(['executor', 'handler'] as const)('error hints (tool %s)', callbac { isError: true, content: [{ type: 'text', text: 'Index is rebuilding.' }] }, 'If this keeps failing after the rebuild', ); - const error = new Error(`Upstream returned 500. ${feedbackHint({ condition: 'If retrying does not help' })}`); + const error = new Error(`Upstream returned 500. ${feedbackHint('If retrying does not help')}`); server.registerTool('hinted-result', {}, () => ownHint); server.registerTool('hinted-throw', {}, () => { throw error; diff --git a/packages/mcp/test/feedback.test.ts b/packages/mcp/test/feedback.test.ts index 6fd0c12e009b..28c5b70a8fac 100644 --- a/packages/mcp/test/feedback.test.ts +++ b/packages/mcp/test/feedback.test.ts @@ -103,7 +103,7 @@ describe('feedbackHint', () => { expect(feedbackHint()).toBe( "If this keeps failing after you adjust your request, report it to this server's maintainers with `submit_feedback`.", ); - expect(feedbackHint({ condition: 'If no tool can do this', toolName: 'submit_feedback_to_acme_team' })).toBe( + expect(feedbackHint('If no tool can do this', { toolName: 'submit_feedback_to_acme_team' })).toBe( "If no tool can do this, report it to this server's maintainers with `submit_feedback_to_acme_team`.", ); }); @@ -111,7 +111,7 @@ describe('feedbackHint', () => { it('names a custom recipient', () => { mockClient(); - expect(feedbackHint({ recipient: 'the Sentry MCP team' })).toBe( + expect(feedbackHint(undefined, { recipient: 'the Sentry MCP team' })).toBe( 'If this keeps failing after you adjust your request, report it to the Sentry MCP team with `submit_feedback`.', ); }); From 986399239f1e90a7dd385e9613ddc73aeef9d71e Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 11:30:05 -0500 Subject: [PATCH 20/34] feat(mcp): Let feedbackHint take one options object feedbackHint takes a condition with optional options, or a single options object that can hold the condition, so options never need an undefined first argument. --- packages/mcp/README.md | 3 ++- packages/mcp/src/errorHints.ts | 2 +- packages/mcp/src/feedback.ts | 15 +++++++++++---- packages/mcp/test/addFeedbackTool.test.ts | 2 +- packages/mcp/test/feedback.test.ts | 5 ++++- 5 files changed, 19 insertions(+), 8 deletions(-) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 69fbbec19dfa..4566132c8249 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -107,7 +107,8 @@ For just the sentence, such as in an error you throw, use `feedbackHint`, which throw new Error(`Index is rebuilding. ${feedbackHint('If this keeps failing after the rebuild')}`); ``` -If you register the tool yourself, pass `toolName` and `recipient` as the second argument to `feedbackHint`. +If you register the tool yourself, pass `toolName` and `recipient` to `feedbackHint`, either after the condition or in +one object with it. ## Support diff --git a/packages/mcp/src/errorHints.ts b/packages/mcp/src/errorHints.ts index 42342402a6c6..983073005a86 100644 --- a/packages/mcp/src/errorHints.ts +++ b/packages/mcp/src/errorHints.ts @@ -72,7 +72,7 @@ export function addErrorHints( // Checked per failure, since on Cloudflare the client only exists inside a request. const shouldHint: ErrorHintFilter = (toolName, failure) => isFeedbackAvailable() && !mentions(failure, hintMarker) && filterFailure(toolName, failure); - const hint = feedbackHint(undefined, { toolName: feedbackToolName, recipient, available: true }); + const hint = feedbackHint({ toolName: feedbackToolName, recipient, available: true }); const wrap = (name: unknown, tool: unknown): void => { if (typeof name === 'string' && name !== feedbackToolName) { wrapRegisteredTool(name, tool, hint, shouldHint); diff --git a/packages/mcp/src/feedback.ts b/packages/mcp/src/feedback.ts index 1d12c5f99219..6435f45566e8 100644 --- a/packages/mcp/src/feedback.ts +++ b/packages/mcp/src/feedback.ts @@ -166,6 +166,10 @@ export function captureAgentFeedback( * Options for `feedbackHint`. */ export interface FeedbackHintOptions { + /** + * When the agent should report it. Defaults to "If this keeps failing after you adjust your request". + */ + condition?: string; /** * Name of the registered feedback tool. Defaults to the name from the last `addFeedbackTool` call, or `submit_feedback`. */ @@ -196,16 +200,19 @@ export function setRegisteredFeedbackTool(name: string, recipient: string | unde /** * Returns the sentence that points the agent at the feedback tool, for tool errors. * Empty when the tool is unavailable, so agents are never sent to a tool they cannot call. + * Takes the condition, the condition and options, or just the options. * * @example * ```ts * throw new Error(`Index is rebuilding. ${feedbackHint('If this keeps failing after the rebuild')}`); * ``` */ -export function feedbackHint( - condition = 'If this keeps failing after you adjust your request', - options: FeedbackHintOptions = {}, -): string { +export function feedbackHint(condition?: string, options?: Omit): string; +export function feedbackHint(options: FeedbackHintOptions): string; +export function feedbackHint(conditionOrOptions?: string | FeedbackHintOptions, rest?: FeedbackHintOptions): string { + const options = + typeof conditionOrOptions === 'object' ? conditionOrOptions : { ...rest, condition: conditionOrOptions }; + const condition = options.condition ?? 'If this keeps failing after you adjust your request'; const available = options.available ?? isFeedbackAvailable(); if (!available) { return ''; diff --git a/packages/mcp/test/addFeedbackTool.test.ts b/packages/mcp/test/addFeedbackTool.test.ts index 0dffc14b82f4..969ee9e16cef 100644 --- a/packages/mcp/test/addFeedbackTool.test.ts +++ b/packages/mcp/test/addFeedbackTool.test.ts @@ -85,7 +85,7 @@ describe('addFeedbackTool', () => { expect(feedbackHint('If retrying does not help')).toBe( 'If retrying does not help, report it to the Orders maintainers with `submit_feedback_to_orders`.', ); - expect(feedbackHint(undefined, { toolName: 'report_issue', recipient: 'the Sentry MCP team' })).toBe( + expect(feedbackHint({ toolName: 'report_issue', recipient: 'the Sentry MCP team' })).toBe( 'If this keeps failing after you adjust your request, report it to the Sentry MCP team with `report_issue`.', ); }); diff --git a/packages/mcp/test/feedback.test.ts b/packages/mcp/test/feedback.test.ts index 28c5b70a8fac..32d1a4789dc6 100644 --- a/packages/mcp/test/feedback.test.ts +++ b/packages/mcp/test/feedback.test.ts @@ -106,12 +106,15 @@ describe('feedbackHint', () => { expect(feedbackHint('If no tool can do this', { toolName: 'submit_feedback_to_acme_team' })).toBe( "If no tool can do this, report it to this server's maintainers with `submit_feedback_to_acme_team`.", ); + expect(feedbackHint({ condition: 'If no tool can do this', toolName: 'submit_feedback_to_acme_team' })).toBe( + "If no tool can do this, report it to this server's maintainers with `submit_feedback_to_acme_team`.", + ); }); it('names a custom recipient', () => { mockClient(); - expect(feedbackHint(undefined, { recipient: 'the Sentry MCP team' })).toBe( + expect(feedbackHint({ recipient: 'the Sentry MCP team' })).toBe( 'If this keeps failing after you adjust your request, report it to the Sentry MCP team with `submit_feedback`.', ); }); From f3639c540c2e92e7ba153680cd3470e0acd868e8 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 11:35:19 -0500 Subject: [PATCH 21/34] feat(mcp): Add createFeedbackTool for servers that register tools themselves createFeedbackTool returns the tool's name, config and handler, and makes them the defaults for feedbackHint and withFeedbackHint, so a server with its own catalog keeps the right hint without calling addFeedbackTool. addFeedbackTool is built on it. feedbackInputSchema and getFeedbackToolDescription are no longer exported, since tool.config covers them. --- packages/mcp/README.md | 27 ++-- packages/mcp/src/addFeedbackTool.ts | 95 +++----------- packages/mcp/src/createFeedbackTool.ts | 123 +++++++++++++++++++ packages/mcp/src/index.ts | 11 +- packages/mcp/test/createFeedbackTool.test.ts | 65 ++++++++++ 5 files changed, 217 insertions(+), 104 deletions(-) create mode 100644 packages/mcp/src/createFeedbackTool.ts create mode 100644 packages/mcp/test/createFeedbackTool.test.ts diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 4566132c8249..5e13fa070bc2 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -43,24 +43,20 @@ agent and other tools' errors get no hint. ### Registering the tool yourself -If your server registers tools through its own catalog, use the parts instead: +If your server registers tools through its own catalog, create the tool and register it like your other tools: ```js -import { captureAgentFeedback, feedbackInputSchema, getFeedbackToolDescription } from '@sentry/mcp'; - -server.registerTool( - 'submit_feedback', - { description: getFeedbackToolDescription({ serverName: 'Acme' }), inputSchema: feedbackInputSchema }, - args => { - const result = captureAgentFeedback(args, { clientName: 'cursor' }); - - return result.ok - ? { content: [{ type: 'text', text: 'Feedback sent.' }] } - : { isError: true, content: [{ type: 'text', text: result.error }] }; - }, -); +import { createFeedbackTool } from '@sentry/mcp'; + +const tool = createFeedbackTool({ serverName: 'Acme', server }); + +server.registerTool(tool.name, tool.config, tool.handler); ``` +It takes the same options as `addFeedbackTool`, plus `server`, which lets each report name the agent that sent it. +`feedbackHint` and `withFeedbackHint` use its name and `serverName`, but your other tools' errors don't get the hint +automatically: add `feedbackHint()` to them 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 @@ -107,9 +103,6 @@ For just the sentence, such as in an error you throw, use `feedbackHint`, which throw new Error(`Index is rebuilding. ${feedbackHint('If this keeps failing after the rebuild')}`); ``` -If you register the tool yourself, pass `toolName` and `recipient` to `feedbackHint`, either after the condition or in -one object with it. - ## Support - [Report a bug](https://github.com/getsentry/sentry-javascript/issues/new/choose) diff --git a/packages/mcp/src/addFeedbackTool.ts b/packages/mcp/src/addFeedbackTool.ts index a92aee6c97c7..b4f0edce1b08 100644 --- a/packages/mcp/src/addFeedbackTool.ts +++ b/packages/mcp/src/addFeedbackTool.ts @@ -1,59 +1,30 @@ import { debug } from '@sentry/core'; +import type { CreateFeedbackToolOptions, FeedbackToolDefinition } from './createFeedbackTool'; +import { buildFeedbackTool, getRecipient } from './createFeedbackTool'; import { DEBUG_BUILD } from './debug-build'; import type { ErrorHintFilter } from './errorHints'; import { addErrorHints } from './errorHints'; -import type { AgentFeedback, FeedbackToolDescriptionOptions } from './feedback'; -import { - captureAgentFeedback, - DEFAULT_FEEDBACK_TOOL_NAME, - feedbackInputSchema, - getFeedbackToolDescription, - isFeedbackAvailable, - setRegisteredFeedbackTool, -} from './feedback'; - -type ToolResult = { - content: Array<{ type: 'text'; text: string }>; - isError?: boolean; -}; +import { setRegisteredFeedbackTool } from './feedback'; // The public parameter is `object`, like `wrapMcpServerWithSentry`, so any MCP SDK version's server is accepted. interface McpServerLike { registerTool?: ( name: string, - config: Record, - handler: (args: AgentFeedback) => ToolResult, + config: FeedbackToolDefinition['config'], + handler: FeedbackToolDefinition['handler'], ) => unknown; tool?: ( name: string, description: string, - inputSchema: Record, - handler: (args: AgentFeedback) => ToolResult, + inputSchema: FeedbackToolDefinition['config']['inputSchema'], + handler: FeedbackToolDefinition['handler'], ) => unknown; - server?: { getClientVersion?: () => { name?: string } | undefined }; } /** * Options for `addFeedbackTool`. */ -export interface AddFeedbackToolOptions extends FeedbackToolDescriptionOptions { - /** - * Names the server in the tool description and in the error hints, which then say - * "report it to the {serverName} maintainers". Defaults to "this MCP server". - */ - serverName?: string; - /** - * Name of the tool. Defaults to `submit_feedback`. - */ - name?: string; - /** - * Replaces the default tool description. - */ - description?: string; - /** - * Extra scrubbing applied to each report's message. See `captureAgentFeedback`. - */ - scrub?: (message: string) => string; +export interface AddFeedbackToolOptions extends Omit { /** * Whether failed calls to the server's other tools point the agent at the feedback tool. * Defaults to `shouldHintFeedback`, which skips upstream HTTP 4xx and JSON-RPC client errors. @@ -80,70 +51,36 @@ export interface AddFeedbackToolOptions extends FeedbackToolDescriptionOptions { * ``` */ export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptions = {}): void { - const server = mcpServer as McpServerLike; - - const name = options.name ?? DEFAULT_FEEDBACK_TOOL_NAME; - const description = options.description ?? getFeedbackToolDescription(options); - const recipient = options.serverName ? `the ${options.serverName} maintainers` : undefined; - - const handler = (args: AgentFeedback): ToolResult => { - if (!isFeedbackAvailable()) { - return { isError: true, content: [{ type: 'text', text: "Feedback isn't available on this server." }] }; - } - - const result = captureAgentFeedback(args, { - clientName: server.server?.getClientVersion?.()?.name, - scrub: options.scrub, - }); + const tool = buildFeedbackTool({ ...options, server: mcpServer }); - if (!result.ok) { - return { isError: true, content: [{ type: 'text', text: result.error }] }; - } - - return { content: [{ type: 'text', text: `Feedback sent (ID ${result.feedbackId}).` }] }; - }; - - if (!registerTool(server, name, description, handler)) { + if (!registerTool(mcpServer, tool)) { DEBUG_BUILD && debug.warn('[MCP] Could not register the feedback tool: the server has no `registerTool` or `tool` method.'); return; } - setRegisteredFeedbackTool(name, recipient); + const recipient = getRecipient(options); + setRegisteredFeedbackTool(tool.name, recipient); if (options.errorHints !== false) { addErrorHints( mcpServer as Record, - name, + tool.name, recipient, typeof options.errorHints === 'function' ? options.errorHints : undefined, ); } } -function registerTool( - server: McpServerLike, - name: string, - description: string, - handler: (args: AgentFeedback) => ToolResult, -): boolean { +function registerTool(server: McpServerLike, tool: FeedbackToolDefinition): boolean { if (typeof server.registerTool === 'function') { - server.registerTool( - name, - { - title: 'Submit Feedback', - description, - inputSchema: feedbackInputSchema, - annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, - }, - handler, - ); + server.registerTool(tool.name, tool.config, tool.handler); return true; } if (typeof server.tool === 'function') { - server.tool(name, description, feedbackInputSchema, handler); + server.tool(tool.name, tool.config.description, tool.config.inputSchema, tool.handler); return true; } diff --git a/packages/mcp/src/createFeedbackTool.ts b/packages/mcp/src/createFeedbackTool.ts new file mode 100644 index 000000000000..200dd071deb1 --- /dev/null +++ b/packages/mcp/src/createFeedbackTool.ts @@ -0,0 +1,123 @@ +import type { AgentFeedback } from './feedback'; +import { + captureAgentFeedback, + DEFAULT_FEEDBACK_TOOL_NAME, + feedbackInputSchema, + getFeedbackToolDescription, + isFeedbackAvailable, + setRegisteredFeedbackTool, +} from './feedback'; + +/** + * Options for `createFeedbackTool`. + */ +export interface CreateFeedbackToolOptions { + /** + * Names the server in the tool description and in the hints, which then say + * "report it to the {serverName} maintainers". Defaults to "this MCP server". + */ + serverName?: string; + /** + * Name of the tool. Defaults to `submit_feedback`. + */ + name?: string; + /** + * Replaces the default tool description. + */ + description?: string; + /** + * Extra scrubbing applied to each report's message. See `captureAgentFeedback`. + */ + scrub?: (message: string) => string; + /** + * The MCP server the tool is registered on. Each report then names the agent that sent it. + */ + server?: object; +} + +/** + * What the feedback tool's handler returns. + */ +export interface FeedbackToolResult { + content: Array<{ type: 'text'; text: string }>; + isError?: boolean; + // MCP SDKs type tool results with an index signature, so a handler without one is not assignable. + [key: string]: unknown; +} + +/** + * A feedback tool to register on an MCP server: `server.registerTool(tool.name, tool.config, tool.handler)`. + */ +export interface FeedbackToolDefinition { + name: string; + config: { + title: string; + description: string; + inputSchema: typeof feedbackInputSchema; + annotations: { readOnlyHint: boolean; destructiveHint: boolean; openWorldHint: boolean }; + }; + handler: (input: AgentFeedback) => FeedbackToolResult; +} + +/** + * Creates a tool that lets agents report friction with an MCP server's tools, for servers that register tools + * themselves, such as through a catalog. Reports are sent to Sentry as User Feedback, tagged with `feedback.kind`, + * `feedback.impact` and `feedback.tool`. `feedbackHint` and `withFeedbackHint` then use its name and `serverName`. + * + * Unlike `addFeedbackTool`, it does not add hints to the errors of the server's other tools. + * + * @example + * ```ts + * const tool = createFeedbackTool({ serverName: 'Acme', server }); + * server.registerTool(tool.name, tool.config, tool.handler); + * ``` + */ +export function createFeedbackTool(options: CreateFeedbackToolOptions = {}): FeedbackToolDefinition { + const tool = buildFeedbackTool(options); + setRegisteredFeedbackTool(tool.name, getRecipient(options)); + + return tool; +} + +/** + * Builds the feedback tool without making it the default for `feedbackHint`, for `addFeedbackTool`, which does that + * only once the tool is registered. + */ +export function buildFeedbackTool(options: CreateFeedbackToolOptions): FeedbackToolDefinition { + const server: { server?: { getClientVersion?: () => { name?: string } | undefined } } | undefined = options.server; + + const handler = (input: AgentFeedback): FeedbackToolResult => { + if (!isFeedbackAvailable()) { + return { isError: true, content: [{ type: 'text', text: "Feedback isn't available on this server." }] }; + } + + const result = captureAgentFeedback(input, { + clientName: server?.server?.getClientVersion?.()?.name, + scrub: options.scrub, + }); + + if (!result.ok) { + return { isError: true, content: [{ type: 'text', text: result.error }] }; + } + + return { content: [{ type: 'text', text: `Feedback sent (ID ${result.feedbackId}).` }] }; + }; + + return { + name: options.name ?? DEFAULT_FEEDBACK_TOOL_NAME, + config: { + title: 'Submit Feedback', + description: options.description ?? getFeedbackToolDescription(options), + inputSchema: feedbackInputSchema, + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, + }, + handler, + }; +} + +/** + * Returns who the hints tell the agent to report to. + */ +export function getRecipient(options: CreateFeedbackToolOptions): string | undefined { + return options.serverName ? `the ${options.serverName} maintainers` : undefined; +} diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index f39b4d48e80c..e860ebbfc29b 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -1,18 +1,13 @@ export { addFeedbackTool } from './addFeedbackTool'; export type { AddFeedbackToolOptions } from './addFeedbackTool'; +export { createFeedbackTool } from './createFeedbackTool'; +export type { CreateFeedbackToolOptions, FeedbackToolDefinition, FeedbackToolResult } from './createFeedbackTool'; export { shouldHintFeedback } from './errorHints'; export type { ErrorHintFilter, ToolErrorResult } from './errorHints'; -export { - captureAgentFeedback, - feedbackHint, - feedbackInputSchema, - getFeedbackToolDescription, - withFeedbackHint, -} from './feedback'; +export { captureAgentFeedback, feedbackHint, withFeedbackHint } from './feedback'; export type { AgentFeedback, CaptureAgentFeedbackOptions, CaptureAgentFeedbackResult, FeedbackHintOptions, - FeedbackToolDescriptionOptions, } from './feedback'; diff --git a/packages/mcp/test/createFeedbackTool.test.ts b/packages/mcp/test/createFeedbackTool.test.ts new file mode 100644 index 000000000000..156c39dfaef1 --- /dev/null +++ b/packages/mcp/test/createFeedbackTool.test.ts @@ -0,0 +1,65 @@ +import { captureFeedback, getClient } from '@sentry/core'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { createFeedbackTool } from '../src/createFeedbackTool'; +import { feedbackHint, feedbackInputSchema, withFeedbackHint } from '../src/feedback'; + +vi.mock('@sentry/core', async importOriginal => { + const actual = await importOriginal>(); + return { ...actual, captureFeedback: vi.fn(() => 'event-id'), getClient: vi.fn() }; +}); + +const report = { + task: 'find slow endpoints', + kind: 'missing', + impact: 'blocked', + description: 'No p95 tool.', +} as const; + +describe('createFeedbackTool', () => { + beforeEach(() => { + vi.mocked(getClient).mockReturnValue({ + getDsn: () => ({}), + getDataCollectionOptions: () => ({ userInfo: true }), + } as unknown as ReturnType); + }); + + afterEach(() => { + vi.clearAllMocks(); + }); + + it('returns a tool definition that sends reports', () => { + const server = { server: { getClientVersion: () => ({ name: 'cursor' }) } }; + + const tool = createFeedbackTool({ serverName: 'Orders', server }); + + expect(tool.name).toBe('submit_feedback'); + expect(tool.config).toEqual({ + title: 'Submit Feedback', + description: expect.stringContaining('the Orders MCP server'), + inputSchema: feedbackInputSchema, + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, + }); + expect(tool.handler(report)).toEqual({ content: [{ type: 'text', text: 'Feedback sent (ID event-id).' }] }); + expect(captureFeedback).toHaveBeenCalledWith(expect.objectContaining({ name: 'MCP agent (cursor)' })); + }); + + it('makes its name and serverName the defaults for the hints', () => { + createFeedbackTool({ name: 'submit_feedback_to_orders', serverName: 'Orders' }); + const hint = 'If retrying does not help, report it to the Orders maintainers with `submit_feedback_to_orders`.'; + + expect(feedbackHint('If retrying does not help')).toBe(hint); + expect(withFeedbackHint({ content: [] }, 'If retrying does not help')).toEqual({ + content: [{ type: 'text', text: hint }], + }); + }); + + it('returns an error while Sentry has no client', () => { + vi.mocked(getClient).mockReturnValue(undefined); + + expect(createFeedbackTool().handler(report)).toEqual({ + isError: true, + content: [{ type: 'text', text: "Feedback isn't available on this server." }], + }); + expect(captureFeedback).not.toHaveBeenCalled(); + }); +}); From 8d0c5cc98686aba6ea41035dbab0a4b10e46d18c Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 11:38:24 -0500 Subject: [PATCH 22/34] ref(mcp): Take only the condition in feedbackHint addFeedbackTool and createFeedbackTool now record the tool name and server, so feedbackHint no longer needs toolName, recipient or available. The error hints keep naming their own server through an internal formatter. --- packages/mcp/src/errorHints.ts | 4 +- packages/mcp/src/feedback.ts | 51 +++++++---------------- packages/mcp/src/index.ts | 7 +--- packages/mcp/test/addFeedbackTool.test.ts | 3 -- packages/mcp/test/errorHints.test.ts | 18 ++++++++ packages/mcp/test/feedback.test.ts | 17 +++----- 6 files changed, 42 insertions(+), 58 deletions(-) diff --git a/packages/mcp/src/errorHints.ts b/packages/mcp/src/errorHints.ts index 983073005a86..250ed9a67830 100644 --- a/packages/mcp/src/errorHints.ts +++ b/packages/mcp/src/errorHints.ts @@ -1,6 +1,6 @@ import type { Event, EventHint } from '@sentry/core'; import { fill, getGlobalScope, isObjectLike } from '@sentry/core'; -import { feedbackHint, isFeedbackAvailable } from './feedback'; +import { formatFeedbackHint, isFeedbackAvailable } from './feedback'; /** * A tool result with `isError: true`. @@ -72,7 +72,7 @@ export function addErrorHints( // Checked per failure, since on Cloudflare the client only exists inside a request. const shouldHint: ErrorHintFilter = (toolName, failure) => isFeedbackAvailable() && !mentions(failure, hintMarker) && filterFailure(toolName, failure); - const hint = feedbackHint({ toolName: feedbackToolName, recipient, available: true }); + const hint = formatFeedbackHint(feedbackToolName, recipient); const wrap = (name: unknown, tool: unknown): void => { if (typeof name === 'string' && name !== feedbackToolName) { wrapRegisteredTool(name, tool, hint, shouldHint); diff --git a/packages/mcp/src/feedback.ts b/packages/mcp/src/feedback.ts index 6435f45566e8..5638ed097b1d 100644 --- a/packages/mcp/src/feedback.ts +++ b/packages/mcp/src/feedback.ts @@ -162,29 +162,6 @@ export function captureAgentFeedback( return { ok: true, feedbackId }; } -/** - * Options for `feedbackHint`. - */ -export interface FeedbackHintOptions { - /** - * When the agent should report it. Defaults to "If this keeps failing after you adjust your request". - */ - condition?: string; - /** - * Name of the registered feedback tool. Defaults to the name from the last `addFeedbackTool` call, or `submit_feedback`. - */ - toolName?: string; - /** - * Whether the agent can call the feedback tool. Defaults to whether Sentry has a client with a DSN. - */ - available?: boolean; - /** - * Who the agent reports to. Defaults to "the {serverName} maintainers" from the last `addFeedbackTool` call, - * or "this server's maintainers". - */ - recipient?: string; -} - /** * The feedback tool from the last `addFeedbackTool` call. A process runs one server config, so the last call wins. */ @@ -198,29 +175,31 @@ export function setRegisteredFeedbackTool(name: string, recipient: string | unde } /** - * Returns the sentence that points the agent at the feedback tool, for tool errors. - * Empty when the tool is unavailable, so agents are never sent to a tool they cannot call. - * Takes the condition, the condition and options, or just the options. + * Returns the sentence that points the agent at the tool `addFeedbackTool` or `createFeedbackTool` made, for tool errors. + * Empty while Sentry has no client, so agents are never sent to a tool they cannot call. + * `condition` defaults to "If this keeps failing after you adjust your request". * * @example * ```ts * throw new Error(`Index is rebuilding. ${feedbackHint('If this keeps failing after the rebuild')}`); * ``` */ -export function feedbackHint(condition?: string, options?: Omit): string; -export function feedbackHint(options: FeedbackHintOptions): string; -export function feedbackHint(conditionOrOptions?: string | FeedbackHintOptions, rest?: FeedbackHintOptions): string { - const options = - typeof conditionOrOptions === 'object' ? conditionOrOptions : { ...rest, condition: conditionOrOptions }; - const condition = options.condition ?? 'If this keeps failing after you adjust your request'; - const available = options.available ?? isFeedbackAvailable(); - if (!available) { +export function feedbackHint(condition?: string): string { + if (!isFeedbackAvailable()) { return ''; } - const recipient = options.recipient ?? registeredTool?.recipient ?? "this server's maintainers"; - const toolName = options.toolName ?? registeredTool?.name ?? DEFAULT_FEEDBACK_TOOL_NAME; + return formatFeedbackHint(registeredTool?.name ?? DEFAULT_FEEDBACK_TOOL_NAME, registeredTool?.recipient, condition); +} +/** + * Builds the hint for a given tool, without checking that feedback is available. + */ +export function formatFeedbackHint( + toolName: string, + recipient = "this server's maintainers", + condition = 'If this keeps failing after you adjust your request', +): string { return `${condition}, report it to ${recipient} with \`${toolName}\`.`; } diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index e860ebbfc29b..3e2912303521 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -5,9 +5,4 @@ export type { CreateFeedbackToolOptions, FeedbackToolDefinition, FeedbackToolRes export { shouldHintFeedback } from './errorHints'; export type { ErrorHintFilter, ToolErrorResult } from './errorHints'; export { captureAgentFeedback, feedbackHint, withFeedbackHint } from './feedback'; -export type { - AgentFeedback, - CaptureAgentFeedbackOptions, - CaptureAgentFeedbackResult, - FeedbackHintOptions, -} from './feedback'; +export type { AgentFeedback, CaptureAgentFeedbackOptions, CaptureAgentFeedbackResult } from './feedback'; diff --git a/packages/mcp/test/addFeedbackTool.test.ts b/packages/mcp/test/addFeedbackTool.test.ts index 969ee9e16cef..ecd6873480f7 100644 --- a/packages/mcp/test/addFeedbackTool.test.ts +++ b/packages/mcp/test/addFeedbackTool.test.ts @@ -85,9 +85,6 @@ describe('addFeedbackTool', () => { expect(feedbackHint('If retrying does not help')).toBe( 'If retrying does not help, report it to the Orders maintainers with `submit_feedback_to_orders`.', ); - expect(feedbackHint({ toolName: 'report_issue', recipient: 'the Sentry MCP team' })).toBe( - 'If this keeps failing after you adjust your request, report it to the Sentry MCP team with `report_issue`.', - ); }); it('falls back to the legacy tool() method', () => { diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index 287167bb12cb..bd32a6054666 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -177,6 +177,24 @@ describe.each(['executor', 'handler'] as const)('error hints (tool %s)', callbac expect(failures).toEqual([thrown, returned]); }); + it('names its own server and tool, not the ones from the last addFeedbackTool call', async () => { + const orders = createServer(callbackKey); + addFeedbackTool(orders, { name: 'submit_feedback_to_orders', serverName: 'Orders' }); + orders.registerTool('failed', {}, () => ({ isError: true, content: [{ type: 'text', text: 'nope' }] })); + addFeedbackTool(createServer(callbackKey), { serverName: 'Billing' }); + + await expect(orders.call('failed')).resolves.toEqual({ + isError: true, + content: [ + { type: 'text', text: 'nope' }, + { + type: 'text', + text: 'If this keeps failing after you adjust your request, report it to the Orders maintainers with `submit_feedback_to_orders`.', + }, + ], + }); + }); + it('skips the hint while Sentry has no client and adds it once it has one', async () => { const client = getClient(); vi.mocked(getClient).mockReturnValue(undefined); diff --git a/packages/mcp/test/feedback.test.ts b/packages/mcp/test/feedback.test.ts index 32d1a4789dc6..ba7afc3ca1c1 100644 --- a/packages/mcp/test/feedback.test.ts +++ b/packages/mcp/test/feedback.test.ts @@ -1,6 +1,6 @@ import { captureFeedback, getClient, getIsolationScope } from '@sentry/core'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { captureAgentFeedback, feedbackHint, getFeedbackToolDescription } from '../src/feedback'; +import { captureAgentFeedback, feedbackHint, formatFeedbackHint, getFeedbackToolDescription } from '../src/feedback'; vi.mock('@sentry/core', async importOriginal => { const actual = await importOriginal>(); @@ -103,19 +103,14 @@ describe('feedbackHint', () => { expect(feedbackHint()).toBe( "If this keeps failing after you adjust your request, report it to this server's maintainers with `submit_feedback`.", ); - expect(feedbackHint('If no tool can do this', { toolName: 'submit_feedback_to_acme_team' })).toBe( - "If no tool can do this, report it to this server's maintainers with `submit_feedback_to_acme_team`.", - ); - expect(feedbackHint({ condition: 'If no tool can do this', toolName: 'submit_feedback_to_acme_team' })).toBe( - "If no tool can do this, report it to this server's maintainers with `submit_feedback_to_acme_team`.", + expect(feedbackHint('If no tool can do this')).toBe( + "If no tool can do this, report it to this server's maintainers with `submit_feedback`.", ); }); - it('names a custom recipient', () => { - mockClient(); - - expect(feedbackHint({ recipient: 'the Sentry MCP team' })).toBe( - 'If this keeps failing after you adjust your request, report it to the Sentry MCP team with `submit_feedback`.', + it('formats a hint for a given tool and recipient', () => { + expect(formatFeedbackHint('report_issue', 'the Sentry MCP team')).toBe( + 'If this keeps failing after you adjust your request, report it to the Sentry MCP team with `report_issue`.', ); }); From 2da27d82de5fa471231de253c398c381943fdb7f Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 11:41:36 -0500 Subject: [PATCH 23/34] fix(mcp): Return no feedbackHint until a feedback tool is made feedbackHint fell back to submit_feedback before any tool existed, which could point agents at a tool the server doesn't have. It now matches withFeedbackHint. --- packages/mcp/src/feedback.ts | 14 +++++++------- packages/mcp/test/feedback.test.ts | 15 ++++++++++++++- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/packages/mcp/src/feedback.ts b/packages/mcp/src/feedback.ts index 5638ed097b1d..6cd90058dd66 100644 --- a/packages/mcp/src/feedback.ts +++ b/packages/mcp/src/feedback.ts @@ -176,7 +176,8 @@ export function setRegisteredFeedbackTool(name: string, recipient: string | unde /** * Returns the sentence that points the agent at the tool `addFeedbackTool` or `createFeedbackTool` made, for tool errors. - * Empty while Sentry has no client, so agents are never sent to a tool they cannot call. + * Empty until one of them made the tool, and while Sentry has no client, so agents are never sent to a tool they + * cannot call. * `condition` defaults to "If this keeps failing after you adjust your request". * * @example @@ -185,11 +186,11 @@ export function setRegisteredFeedbackTool(name: string, recipient: string | unde * ``` */ export function feedbackHint(condition?: string): string { - if (!isFeedbackAvailable()) { + if (!registeredTool || !isFeedbackAvailable()) { return ''; } - return formatFeedbackHint(registeredTool?.name ?? DEFAULT_FEEDBACK_TOOL_NAME, registeredTool?.recipient, condition); + return formatFeedbackHint(registeredTool.name, registeredTool.recipient, condition); } /** @@ -204,9 +205,8 @@ export function formatFeedbackHint( } /** - * Returns a copy of `result` with a hint that points the agent at the tool `addFeedbackTool` registered, as an extra - * text block. `structuredContent` and the existing content are left as they are. The result is returned unchanged - * before `addFeedbackTool` registers the tool and while Sentry has no client. + * Returns a copy of `result` with `feedbackHint` as an extra text block. `structuredContent` and the existing content + * are left as they are. The result is returned unchanged when `feedbackHint` is empty. * `condition` defaults to "If this keeps failing after you adjust your request". * * @example @@ -216,7 +216,7 @@ export function formatFeedbackHint( * ``` */ export function withFeedbackHint(result: T, condition?: string): T { - const text = registeredTool ? feedbackHint(condition) : ''; + const text = feedbackHint(condition); return text ? { ...result, content: [...(result.content ?? []), { type: 'text', text }] } : result; } diff --git a/packages/mcp/test/feedback.test.ts b/packages/mcp/test/feedback.test.ts index ba7afc3ca1c1..904978e02dc4 100644 --- a/packages/mcp/test/feedback.test.ts +++ b/packages/mcp/test/feedback.test.ts @@ -1,6 +1,12 @@ import { captureFeedback, getClient, getIsolationScope } from '@sentry/core'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { captureAgentFeedback, feedbackHint, formatFeedbackHint, getFeedbackToolDescription } from '../src/feedback'; +import { + captureAgentFeedback, + feedbackHint, + formatFeedbackHint, + getFeedbackToolDescription, + setRegisteredFeedbackTool, +} from '../src/feedback'; vi.mock('@sentry/core', async importOriginal => { const actual = await importOriginal>(); @@ -97,8 +103,15 @@ describe('feedbackHint', () => { vi.clearAllMocks(); }); + it('returns an empty string until a feedback tool is made', () => { + mockClient(); + + expect(feedbackHint()).toBe(''); + }); + it('points the agent at the feedback tool', () => { mockClient(); + setRegisteredFeedbackTool('submit_feedback', undefined); expect(feedbackHint()).toBe( "If this keeps failing after you adjust your request, report it to this server's maintainers with `submit_feedback`.", From 56f44ba96eb99eb74f6f1f01ca012a08598b8a3b Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 11:46:39 -0500 Subject: [PATCH 24/34] feat(mcp): Add error hints in createFeedbackTool when given the server createFeedbackTool already takes the server to name the agent, so it now also adds the error hints, with the same errorHints option as addFeedbackTool. addFeedbackTool checks that it can register the tool, then builds on it. --- packages/mcp/README.md | 6 +-- packages/mcp/src/addFeedbackTool.ts | 43 +++------------- packages/mcp/src/createFeedbackTool.ts | 53 ++++++++++++-------- packages/mcp/test/createFeedbackTool.test.ts | 30 +++++++++++ 4 files changed, 71 insertions(+), 61 deletions(-) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 5e13fa070bc2..8e8770241094 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -53,9 +53,9 @@ const tool = createFeedbackTool({ serverName: 'Acme', server }); server.registerTool(tool.name, tool.config, tool.handler); ``` -It takes the same options as `addFeedbackTool`, plus `server`, which lets each report name the agent that sent it. -`feedbackHint` and `withFeedbackHint` use its name and `serverName`, but your other tools' errors don't get the hint -automatically: add `feedbackHint()` to them yourself. For a handler of your own, use `captureAgentFeedback`. +It takes the same options as `addFeedbackTool`, plus an optional `server`. With `server`, each report names the agent +that sent it and your other tools' errors get the hint, as with `addFeedbackTool`. Without it, add `feedbackHint()` to +your errors yourself. For a handler of your own, use `captureAgentFeedback`. ### Pointing agents at the tool diff --git a/packages/mcp/src/addFeedbackTool.ts b/packages/mcp/src/addFeedbackTool.ts index b4f0edce1b08..c65ea92ef8bf 100644 --- a/packages/mcp/src/addFeedbackTool.ts +++ b/packages/mcp/src/addFeedbackTool.ts @@ -1,10 +1,7 @@ import { debug } from '@sentry/core'; import type { CreateFeedbackToolOptions, FeedbackToolDefinition } from './createFeedbackTool'; -import { buildFeedbackTool, getRecipient } from './createFeedbackTool'; +import { createFeedbackTool } from './createFeedbackTool'; import { DEBUG_BUILD } from './debug-build'; -import type { ErrorHintFilter } from './errorHints'; -import { addErrorHints } from './errorHints'; -import { setRegisteredFeedbackTool } from './feedback'; // The public parameter is `object`, like `wrapMcpServerWithSentry`, so any MCP SDK version's server is accepted. interface McpServerLike { @@ -24,14 +21,7 @@ interface McpServerLike { /** * Options for `addFeedbackTool`. */ -export interface AddFeedbackToolOptions extends Omit { - /** - * Whether failed calls to the server's other tools point the agent at the feedback tool. - * Defaults to `shouldHintFeedback`, which skips upstream HTTP 4xx and JSON-RPC client errors. - * Pass a function to choose per failure, or `false` to turn the hints off. - */ - errorHints?: boolean | ErrorHintFilter; -} +export type AddFeedbackToolOptions = Omit; /** * Registers a tool on an MCP server that lets agents report friction with the server's tools. @@ -51,39 +41,20 @@ export interface AddFeedbackToolOptions extends Omit, - tool.name, - recipient, - typeof options.errorHints === 'function' ? options.errorHints : undefined, - ); - } -} + const tool = createFeedbackTool({ ...options, server: mcpServer }); -function registerTool(server: McpServerLike, tool: FeedbackToolDefinition): boolean { if (typeof server.registerTool === 'function') { server.registerTool(tool.name, tool.config, tool.handler); - return true; - } - - if (typeof server.tool === 'function') { - server.tool(tool.name, tool.config.description, tool.config.inputSchema, tool.handler); - - return true; + return; } - return false; + server.tool?.(tool.name, tool.config.description, tool.config.inputSchema, tool.handler); } diff --git a/packages/mcp/src/createFeedbackTool.ts b/packages/mcp/src/createFeedbackTool.ts index 200dd071deb1..2d2ac04d7a0a 100644 --- a/packages/mcp/src/createFeedbackTool.ts +++ b/packages/mcp/src/createFeedbackTool.ts @@ -1,3 +1,5 @@ +import type { ErrorHintFilter } from './errorHints'; +import { addErrorHints } from './errorHints'; import type { AgentFeedback } from './feedback'; import { captureAgentFeedback, @@ -30,9 +32,20 @@ export interface CreateFeedbackToolOptions { */ scrub?: (message: string) => string; /** - * The MCP server the tool is registered on. Each report then names the agent that sent it. + * The MCP server the tool is registered on. Each report then names the agent that sent it, and the server's + * other tools get error hints. */ server?: object; + /** + * Whether failed calls to the server's other tools point the agent at the feedback tool. Needs `server`. + * Defaults to `shouldHintFeedback`, which skips upstream HTTP 4xx and JSON-RPC client errors. + * Pass a function to choose per failure, or `false` to turn the hints off. + */ + errorHints?: boolean | ErrorHintFilter; +} + +interface McpServerWithClient { + server?: { getClientVersion?: () => { name?: string } | undefined }; } /** @@ -64,7 +77,8 @@ export interface FeedbackToolDefinition { * themselves, such as through a catalog. Reports are sent to Sentry as User Feedback, tagged with `feedback.kind`, * `feedback.impact` and `feedback.tool`. `feedbackHint` and `withFeedbackHint` then use its name and `serverName`. * - * Unlike `addFeedbackTool`, it does not add hints to the errors of the server's other tools. + * With `server`, errors from the server's other tools also tell the agent about the feedback tool, like + * `addFeedbackTool`, unless `errorHints` is `false`. * * @example * ```ts @@ -73,18 +87,9 @@ export interface FeedbackToolDefinition { * ``` */ export function createFeedbackTool(options: CreateFeedbackToolOptions = {}): FeedbackToolDefinition { - const tool = buildFeedbackTool(options); - setRegisteredFeedbackTool(tool.name, getRecipient(options)); - - return tool; -} - -/** - * Builds the feedback tool without making it the default for `feedbackHint`, for `addFeedbackTool`, which does that - * only once the tool is registered. - */ -export function buildFeedbackTool(options: CreateFeedbackToolOptions): FeedbackToolDefinition { - const server: { server?: { getClientVersion?: () => { name?: string } | undefined } } | undefined = options.server; + const server: McpServerWithClient | undefined = options.server; + const name = options.name ?? DEFAULT_FEEDBACK_TOOL_NAME; + const recipient = options.serverName ? `the ${options.serverName} maintainers` : undefined; const handler = (input: AgentFeedback): FeedbackToolResult => { if (!isFeedbackAvailable()) { @@ -103,8 +108,19 @@ export function buildFeedbackTool(options: CreateFeedbackToolOptions): FeedbackT return { content: [{ type: 'text', text: `Feedback sent (ID ${result.feedbackId}).` }] }; }; + setRegisteredFeedbackTool(name, recipient); + + if (options.server && options.errorHints !== false) { + addErrorHints( + options.server as Record, + name, + recipient, + typeof options.errorHints === 'function' ? options.errorHints : undefined, + ); + } + return { - name: options.name ?? DEFAULT_FEEDBACK_TOOL_NAME, + name, config: { title: 'Submit Feedback', description: options.description ?? getFeedbackToolDescription(options), @@ -114,10 +130,3 @@ export function buildFeedbackTool(options: CreateFeedbackToolOptions): FeedbackT handler, }; } - -/** - * Returns who the hints tell the agent to report to. - */ -export function getRecipient(options: CreateFeedbackToolOptions): string | undefined { - return options.serverName ? `the ${options.serverName} maintainers` : undefined; -} diff --git a/packages/mcp/test/createFeedbackTool.test.ts b/packages/mcp/test/createFeedbackTool.test.ts index 156c39dfaef1..7e3f5f557559 100644 --- a/packages/mcp/test/createFeedbackTool.test.ts +++ b/packages/mcp/test/createFeedbackTool.test.ts @@ -53,6 +53,36 @@ describe('createFeedbackTool', () => { }); }); + it.each([ + [undefined, true], + [false, false], + ])( + "adds error hints to the server's other tools when given the server (errorHints: %s)", + async (errorHints, hinted) => { + const tools: Record unknown }> = {}; + const server = { + _registeredTools: tools, + registerTool: (name: string, _config: unknown, handler: () => unknown) => (tools[name] = { handler }), + }; + const failed = { isError: true, content: [{ type: 'text', text: 'Upstream returned 500.' }] }; + + const tool = createFeedbackTool({ serverName: 'Orders', server, errorHints }); + server.registerTool(tool.name, tool.config, tool.handler); + server.registerTool('search', {}, () => failed); + + const content = hinted + ? [ + ...failed.content, + { + type: 'text', + text: 'If this keeps failing after you adjust your request, report it to the Orders maintainers with `submit_feedback`.', + }, + ] + : failed.content; + expect(await tools['search']!.handler()).toEqual({ ...failed, content }); + }, + ); + it('returns an error while Sentry has no client', () => { vi.mocked(getClient).mockReturnValue(undefined); From 8df64f806f8babefca791b1662a3b80d166e5afb Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 11:53:59 -0500 Subject: [PATCH 25/34] feat(mcp): Return the feedback ID as structured content The feedback tool now declares an outputSchema and returns structuredContent: { feedbackId } next to the text, so servers that require an outputSchema on every tool can register tool.handler as is. --- .../node-express-mcp-v1/tests/mcp.test.ts | 1 + .../node-express-mcp-v2/tests/mcp.test.ts | 1 + packages/mcp/src/createFeedbackTool.ts | 9 ++++++++- packages/mcp/src/feedback.ts | 7 +++++++ packages/mcp/test/addFeedbackTool.test.ts | 10 ++++++++-- packages/mcp/test/createFeedbackTool.test.ts | 8 ++++++-- 6 files changed, 31 insertions(+), 5 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 b8bb319e3a38..9c58f2f1a72b 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 @@ -137,6 +137,7 @@ test('auto-instruments a legacy MCP SDK v1 server (no manual wrap)', async ({ ba expect(result.content).toEqual([ { type: 'text', text: expect.stringMatching(/^Feedback sent \(ID [0-9a-f]{32}\)\.$/) }, ]); + expect(result.structuredContent).toEqual({ feedbackId: expect.stringMatching(/^[0-9a-f]{32}$/) }); const [, feedback] = await feedbackPromise; expect(feedback).toMatchObject({ 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 e62e4f2bb335..eb0b5395390e 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 @@ -173,6 +173,7 @@ test('auto-instruments a stable MCP SDK v2 server (no manual wrap)', async ({ ba expect(result.content).toEqual([ { type: 'text', text: expect.stringMatching(/^Feedback sent \(ID [0-9a-f]{32}\)\.$/) }, ]); + expect(result.structuredContent).toEqual({ feedbackId: expect.stringMatching(/^[0-9a-f]{32}$/) }); const [, feedback] = await feedbackPromise; expect(feedback).toMatchObject({ diff --git a/packages/mcp/src/createFeedbackTool.ts b/packages/mcp/src/createFeedbackTool.ts index 2d2ac04d7a0a..f53635735c65 100644 --- a/packages/mcp/src/createFeedbackTool.ts +++ b/packages/mcp/src/createFeedbackTool.ts @@ -5,6 +5,7 @@ import { captureAgentFeedback, DEFAULT_FEEDBACK_TOOL_NAME, feedbackInputSchema, + feedbackOutputSchema, getFeedbackToolDescription, isFeedbackAvailable, setRegisteredFeedbackTool, @@ -53,6 +54,7 @@ interface McpServerWithClient { */ export interface FeedbackToolResult { content: Array<{ type: 'text'; text: string }>; + structuredContent?: { feedbackId: string }; isError?: boolean; // MCP SDKs type tool results with an index signature, so a handler without one is not assignable. [key: string]: unknown; @@ -67,6 +69,7 @@ export interface FeedbackToolDefinition { title: string; description: string; inputSchema: typeof feedbackInputSchema; + outputSchema: typeof feedbackOutputSchema; annotations: { readOnlyHint: boolean; destructiveHint: boolean; openWorldHint: boolean }; }; handler: (input: AgentFeedback) => FeedbackToolResult; @@ -105,7 +108,10 @@ export function createFeedbackTool(options: CreateFeedbackToolOptions = {}): Fee return { isError: true, content: [{ type: 'text', text: result.error }] }; } - return { content: [{ type: 'text', text: `Feedback sent (ID ${result.feedbackId}).` }] }; + return { + content: [{ type: 'text', text: `Feedback sent (ID ${result.feedbackId}).` }], + structuredContent: { feedbackId: result.feedbackId }, + }; }; setRegisteredFeedbackTool(name, recipient); @@ -125,6 +131,7 @@ export function createFeedbackTool(options: CreateFeedbackToolOptions = {}): Fee title: 'Submit Feedback', description: options.description ?? getFeedbackToolDescription(options), inputSchema: feedbackInputSchema, + outputSchema: feedbackOutputSchema, annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, }, handler, diff --git a/packages/mcp/src/feedback.ts b/packages/mcp/src/feedback.ts index 6cd90058dd66..10e5272e851d 100644 --- a/packages/mcp/src/feedback.ts +++ b/packages/mcp/src/feedback.ts @@ -65,6 +65,13 @@ export const feedbackInputSchema = { toolName: z.string().trim().max(100).optional().describe('The tool the feedback is about, if any.'), }; +/** + * Output schema of the feedback tool, as a zod raw shape. + */ +export const feedbackOutputSchema = { + feedbackId: z.string().describe('ID of the feedback sent to Sentry.'), +}; + /** * Options for `getFeedbackToolDescription`. */ diff --git a/packages/mcp/test/addFeedbackTool.test.ts b/packages/mcp/test/addFeedbackTool.test.ts index ecd6873480f7..a2f0be59438d 100644 --- a/packages/mcp/test/addFeedbackTool.test.ts +++ b/packages/mcp/test/addFeedbackTool.test.ts @@ -43,7 +43,10 @@ describe('addFeedbackTool', () => { ); const handler = registerTool.mock.lastCall![2]; - expect(handler(report)).toEqual({ content: [{ type: 'text', text: 'Feedback sent (ID event-id).' }] }); + expect(handler(report)).toEqual({ + content: [{ type: 'text', text: 'Feedback sent (ID event-id).' }], + structuredContent: { feedbackId: 'event-id' }, + }); expect(captureFeedback).toHaveBeenCalledWith(expect.objectContaining({ name: 'MCP agent (cursor)' })); }); @@ -129,7 +132,10 @@ describe('addFeedbackTool', () => { vi.mocked(getClient).mockReturnValue(client); - expect(handler(report)).toEqual({ content: [{ type: 'text', text: 'Feedback sent (ID event-id).' }] }); + expect(handler(report)).toEqual({ + content: [{ type: 'text', text: 'Feedback sent (ID event-id).' }], + structuredContent: { feedbackId: 'event-id' }, + }); expect(captureFeedback).toHaveBeenCalledTimes(1); }); }); diff --git a/packages/mcp/test/createFeedbackTool.test.ts b/packages/mcp/test/createFeedbackTool.test.ts index 7e3f5f557559..abf3d3909650 100644 --- a/packages/mcp/test/createFeedbackTool.test.ts +++ b/packages/mcp/test/createFeedbackTool.test.ts @@ -1,7 +1,7 @@ import { captureFeedback, getClient } from '@sentry/core'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { createFeedbackTool } from '../src/createFeedbackTool'; -import { feedbackHint, feedbackInputSchema, withFeedbackHint } from '../src/feedback'; +import { feedbackHint, feedbackInputSchema, feedbackOutputSchema, withFeedbackHint } from '../src/feedback'; vi.mock('@sentry/core', async importOriginal => { const actual = await importOriginal>(); @@ -37,9 +37,13 @@ describe('createFeedbackTool', () => { title: 'Submit Feedback', description: expect.stringContaining('the Orders MCP server'), inputSchema: feedbackInputSchema, + outputSchema: feedbackOutputSchema, annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, }); - expect(tool.handler(report)).toEqual({ content: [{ type: 'text', text: 'Feedback sent (ID event-id).' }] }); + expect(tool.handler(report)).toEqual({ + content: [{ type: 'text', text: 'Feedback sent (ID event-id).' }], + structuredContent: { feedbackId: 'event-id' }, + }); expect(captureFeedback).toHaveBeenCalledWith(expect.objectContaining({ name: 'MCP agent (cursor)' })); }); From a4194a3bd5acfecc7b28bc1c55f2811c8bc28738 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 12:24:44 -0500 Subject: [PATCH 26/34] feat(mcp): Name the agent from the MCP SDK v2 handler context or the active span The feedback handler now reads the client name from the per-request envelope MCP SDK v2 passes, then the server's handshake, then the mcp.client.name attribute on the active span, so catalogs without the server can still name the agent. Adds @sentry/conventions for the attribute name, which every Sentry SDK already installs. --- packages/mcp/package.json | 3 ++ packages/mcp/src/createFeedbackTool.ts | 33 ++++++++++++++++++-- packages/mcp/test/createFeedbackTool.test.ts | 20 ++++++++++-- pnpm-lock.yaml | 4 +++ 4 files changed, 55 insertions(+), 5 deletions(-) diff --git a/packages/mcp/package.json b/packages/mcp/package.json index f744124840e4..97e55e623a58 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -26,6 +26,9 @@ "publishConfig": { "access": "public" }, + "dependencies": { + "@sentry/conventions": "^0.37.0" + }, "peerDependencies": { "@sentry/core": "^11.0.0", "zod": "^3.25.0 || ^4.0.0" diff --git a/packages/mcp/src/createFeedbackTool.ts b/packages/mcp/src/createFeedbackTool.ts index f53635735c65..603ed03b7a90 100644 --- a/packages/mcp/src/createFeedbackTool.ts +++ b/packages/mcp/src/createFeedbackTool.ts @@ -1,3 +1,5 @@ +import { MCP_CLIENT_NAME } from '@sentry/conventions/attributes'; +import { getActiveSpan, isObjectLike, spanToJSON } from '@sentry/core'; import type { ErrorHintFilter } from './errorHints'; import { addErrorHints } from './errorHints'; import type { AgentFeedback } from './feedback'; @@ -72,9 +74,14 @@ export interface FeedbackToolDefinition { outputSchema: typeof feedbackOutputSchema; annotations: { readOnlyHint: boolean; destructiveHint: boolean; openWorldHint: boolean }; }; - handler: (input: AgentFeedback) => FeedbackToolResult; + /** + * `context` is the handler context MCP SDK v2 passes, used to read the agent's name. + */ + handler: (input: AgentFeedback, context?: unknown) => FeedbackToolResult; } +const CLIENT_INFO_META_KEY = 'io.modelcontextprotocol/clientInfo'; + /** * Creates a tool that lets agents report friction with an MCP server's tools, for servers that register tools * themselves, such as through a catalog. Reports are sent to Sentry as User Feedback, tagged with `feedback.kind`, @@ -94,13 +101,13 @@ export function createFeedbackTool(options: CreateFeedbackToolOptions = {}): Fee const name = options.name ?? DEFAULT_FEEDBACK_TOOL_NAME; const recipient = options.serverName ? `the ${options.serverName} maintainers` : undefined; - const handler = (input: AgentFeedback): FeedbackToolResult => { + const handler = (input: AgentFeedback, context?: unknown): FeedbackToolResult => { if (!isFeedbackAvailable()) { return { isError: true, content: [{ type: 'text', text: "Feedback isn't available on this server." }] }; } const result = captureAgentFeedback(input, { - clientName: server?.server?.getClientVersion?.()?.name, + clientName: getClientName(server, context), scrub: options.scrub, }); @@ -137,3 +144,23 @@ export function createFeedbackTool(options: CreateFeedbackToolOptions = {}): Fee handler, }; } + +// MCP SDK v2 deprecates `getClientVersion()` in favor of the per-request envelope, which 2026-07-28 requests carry. +// The span from `wrapMcpServerWithSentry` covers catalogs that call the handler with their own context, when sampled. +function getClientName(server: McpServerWithClient | undefined, context: unknown): string | undefined { + const envelope = isObjectLike(context) && isObjectLike(context['mcpReq']) ? context['mcpReq']['envelope'] : undefined; + const clientInfo = isObjectLike(envelope) ? envelope[CLIENT_INFO_META_KEY] : undefined; + if (isObjectLike(clientInfo) && typeof clientInfo['name'] === 'string') { + return clientInfo['name']; + } + + const serverClientName = server?.server?.getClientVersion?.()?.name; + if (serverClientName) { + return serverClientName; + } + + const span = getActiveSpan(); + const spanClientName = span ? spanToJSON(span).attributes[MCP_CLIENT_NAME] : undefined; + + return typeof spanClientName === 'string' ? spanClientName : undefined; +} diff --git a/packages/mcp/test/createFeedbackTool.test.ts b/packages/mcp/test/createFeedbackTool.test.ts index abf3d3909650..9cc1ce2b96a2 100644 --- a/packages/mcp/test/createFeedbackTool.test.ts +++ b/packages/mcp/test/createFeedbackTool.test.ts @@ -1,11 +1,11 @@ -import { captureFeedback, getClient } from '@sentry/core'; +import { captureFeedback, getActiveSpan, getClient, SentrySpan } from '@sentry/core'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { createFeedbackTool } from '../src/createFeedbackTool'; import { feedbackHint, feedbackInputSchema, feedbackOutputSchema, withFeedbackHint } from '../src/feedback'; vi.mock('@sentry/core', async importOriginal => { const actual = await importOriginal>(); - return { ...actual, captureFeedback: vi.fn(() => 'event-id'), getClient: vi.fn() }; + return { ...actual, captureFeedback: vi.fn(() => 'event-id'), getActiveSpan: vi.fn(), getClient: vi.fn() }; }); const report = { @@ -47,6 +47,22 @@ describe('createFeedbackTool', () => { expect(captureFeedback).toHaveBeenCalledWith(expect.objectContaining({ name: 'MCP agent (cursor)' })); }); + it('names the agent from the v2 handler context, then the server, then the active span', () => { + const server = { server: { getClientVersion: () => ({ name: 'cursor' }) } }; + const context = { mcpReq: { envelope: { 'io.modelcontextprotocol/clientInfo': { name: 'claude-code' } } } }; + vi.mocked(getActiveSpan).mockReturnValue(new SentrySpan({ attributes: { 'mcp.client.name': 'windsurf' } })); + + createFeedbackTool({ server }).handler(report, context); + createFeedbackTool({ server }).handler(report, {}); + createFeedbackTool().handler(report, {}); + vi.mocked(getActiveSpan).mockReturnValue(undefined); + createFeedbackTool().handler(report); + + ['MCP agent (claude-code)', 'MCP agent (cursor)', 'MCP agent (windsurf)', 'MCP agent'].forEach((name, index) => { + expect(captureFeedback).toHaveBeenNthCalledWith(index + 1, expect.objectContaining({ name })); + }); + }); + it('makes its name and serverName the defaults for the hints', () => { createFeedbackTool({ name: 'submit_feedback_to_orders', serverName: 'Orders' }); const hint = 'If retrying does not help, report it to the Orders maintainers with `submit_feedback_to_orders`.'; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a053c03e68ec..85a31a95427d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1594,6 +1594,10 @@ importers: version: link:../../dev-packages/rollup-utils packages/mcp: + dependencies: + '@sentry/conventions': + specifier: ^0.37.0 + version: 0.37.0 devDependencies: '@sentry-internal/rollup-utils': specifier: 11.21.0 From c00f78d9fa5abcd69f95fcedd15e8743b17d1c01 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 12:39:49 -0500 Subject: [PATCH 27/34] ref(mcp): Name the team instead of the maintainers in the feedback hint The hint now says "report it to the Orders team", matching sentry-mcp's wording. Also fixes comments that still said only addFeedbackTool sets the tool, and drops a duplicated default. --- .../node-express-mcp-v1/tests/mcp.test.ts | 2 +- .../node-express-mcp-v2/tests/mcp.test.ts | 2 +- packages/mcp/README.md | 2 +- packages/mcp/src/createFeedbackTool.ts | 4 ++-- packages/mcp/src/feedback.ts | 12 ++++++------ packages/mcp/test/addFeedbackTool.test.ts | 4 ++-- packages/mcp/test/createFeedbackTool.test.ts | 4 ++-- packages/mcp/test/errorHints.test.ts | 8 ++++---- packages/mcp/test/feedback.test.ts | 4 ++-- 9 files changed, 21 insertions(+), 21 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 9c58f2f1a72b..195d08c6e7f9 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 @@ -172,7 +172,7 @@ test('auto-instruments a legacy MCP SDK v1 server (no manual wrap)', async ({ ba { 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 maintainers with `submit_feedback`.', + '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`.', ), }, ]); 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 eb0b5395390e..f17525d7a74d 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 @@ -208,7 +208,7 @@ test('auto-instruments a stable MCP SDK v2 server (no manual wrap)', async ({ ba { 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 maintainers with `submit_feedback`.', + '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`.', ), }, ]); diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 8e8770241094..226f026fcbcd 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -60,7 +60,7 @@ 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 maintainers with `submit_feedback`." Thrown errors +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 the feedback tool don't get a second hint. diff --git a/packages/mcp/src/createFeedbackTool.ts b/packages/mcp/src/createFeedbackTool.ts index 603ed03b7a90..0da48b634733 100644 --- a/packages/mcp/src/createFeedbackTool.ts +++ b/packages/mcp/src/createFeedbackTool.ts @@ -19,7 +19,7 @@ import { export interface CreateFeedbackToolOptions { /** * Names the server in the tool description and in the hints, which then say - * "report it to the {serverName} maintainers". Defaults to "this MCP server". + * "report it to the {serverName} team". Defaults to "this MCP server". */ serverName?: string; /** @@ -99,7 +99,7 @@ const CLIENT_INFO_META_KEY = 'io.modelcontextprotocol/clientInfo'; export function createFeedbackTool(options: CreateFeedbackToolOptions = {}): FeedbackToolDefinition { const server: McpServerWithClient | undefined = options.server; const name = options.name ?? DEFAULT_FEEDBACK_TOOL_NAME; - const recipient = options.serverName ? `the ${options.serverName} maintainers` : undefined; + const recipient = options.serverName ? `the ${options.serverName} team` : undefined; const handler = (input: AgentFeedback, context?: unknown): FeedbackToolResult => { if (!isFeedbackAvailable()) { diff --git a/packages/mcp/src/feedback.ts b/packages/mcp/src/feedback.ts index 10e5272e851d..92748699f6fb 100644 --- a/packages/mcp/src/feedback.ts +++ b/packages/mcp/src/feedback.ts @@ -2,7 +2,7 @@ import { captureFeedback, getClient, getCombinedScopeData, getCurrentScope, getI import * as z from 'zod/v4'; /** - * The tool name `addFeedbackTool` registers when no other name is given. + * The feedback tool's name when no other is given. */ export const DEFAULT_FEEDBACK_TOOL_NAME = 'submit_feedback'; @@ -42,7 +42,7 @@ export interface AgentFeedback { } /** - * Input schema of the feedback tool, as a zod raw shape. Pass it as `inputSchema` to `registerTool`. + * Input schema of the feedback tool, as a zod raw shape. */ export const feedbackInputSchema = { task: z.string().trim().min(1).max(200).describe('A short phrase naming what the user asked you to do.'), @@ -170,12 +170,13 @@ export function captureAgentFeedback( } /** - * The feedback tool from the last `addFeedbackTool` call. A process runs one server config, so the last call wins. + * The feedback tool from the last `addFeedbackTool` or `createFeedbackTool` call. A process runs one server config, so + * the last call wins. */ let registeredTool: { name: string; recipient: string | undefined } | undefined; /** - * Records the tool `addFeedbackTool` registered, so `feedbackHint` and `withFeedbackHint` default to it. + * Records the tool `addFeedbackTool` or `createFeedbackTool` made, so `feedbackHint` and `withFeedbackHint` use it. */ export function setRegisteredFeedbackTool(name: string, recipient: string | undefined): void { registeredTool = { name, recipient }; @@ -205,7 +206,7 @@ export function feedbackHint(condition?: string): string { */ export function formatFeedbackHint( toolName: string, - recipient = "this server's maintainers", + recipient = "this server's team", condition = 'If this keeps failing after you adjust your request', ): string { return `${condition}, report it to ${recipient} with \`${toolName}\`.`; @@ -214,7 +215,6 @@ export function formatFeedbackHint( /** * Returns a copy of `result` with `feedbackHint` as an extra text block. `structuredContent` and the existing content * are left as they are. The result is returned unchanged when `feedbackHint` is empty. - * `condition` defaults to "If this keeps failing after you adjust your request". * * @example * ```ts diff --git a/packages/mcp/test/addFeedbackTool.test.ts b/packages/mcp/test/addFeedbackTool.test.ts index a2f0be59438d..c2940de1a633 100644 --- a/packages/mcp/test/addFeedbackTool.test.ts +++ b/packages/mcp/test/addFeedbackTool.test.ts @@ -60,7 +60,7 @@ describe('addFeedbackTool', () => { { type: 'text', text: '[]' }, { type: 'text', - text: 'If this stays empty after you broaden the query, report it to the Orders maintainers with `submit_feedback_to_orders`.', + text: 'If this stays empty after you broaden the query, report it to the Orders team with `submit_feedback_to_orders`.', }, ], structuredContent: { orders: [] }, @@ -86,7 +86,7 @@ describe('addFeedbackTool', () => { addFeedbackTool({ registerTool: vi.fn() }, { name: 'submit_feedback_to_orders', serverName: 'Orders' }); expect(feedbackHint('If retrying does not help')).toBe( - 'If retrying does not help, report it to the Orders maintainers with `submit_feedback_to_orders`.', + 'If retrying does not help, report it to the Orders team with `submit_feedback_to_orders`.', ); }); diff --git a/packages/mcp/test/createFeedbackTool.test.ts b/packages/mcp/test/createFeedbackTool.test.ts index 9cc1ce2b96a2..2be74e067447 100644 --- a/packages/mcp/test/createFeedbackTool.test.ts +++ b/packages/mcp/test/createFeedbackTool.test.ts @@ -65,7 +65,7 @@ describe('createFeedbackTool', () => { it('makes its name and serverName the defaults for the hints', () => { createFeedbackTool({ name: 'submit_feedback_to_orders', serverName: 'Orders' }); - const hint = 'If retrying does not help, report it to the Orders maintainers with `submit_feedback_to_orders`.'; + const hint = 'If retrying does not help, report it to the Orders team with `submit_feedback_to_orders`.'; expect(feedbackHint('If retrying does not help')).toBe(hint); expect(withFeedbackHint({ content: [] }, 'If retrying does not help')).toEqual({ @@ -95,7 +95,7 @@ describe('createFeedbackTool', () => { ...failed.content, { type: 'text', - text: 'If this keeps failing after you adjust your request, report it to the Orders maintainers with `submit_feedback`.', + text: 'If this keeps failing after you adjust your request, report it to the Orders team with `submit_feedback`.', }, ] : failed.content; diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index bd32a6054666..0b12a0df7d0f 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -12,7 +12,7 @@ vi.mock('@sentry/core', async importOriginal => { }); const HINT = - "If this keeps failing after you adjust your request, report it to this server's maintainers with `submit_feedback`."; + "If this keeps failing after you adjust your request, report it to this server's team with `submit_feedback`."; type Callback = (...args: unknown[]) => unknown; @@ -80,7 +80,7 @@ describe.each(['executor', 'handler'] as const)('error hints (tool %s)', callbac { type: 'text', text: 'nope' }, { type: 'text', - text: 'If this keeps failing after you adjust your request, report it to the Acme maintainers with `submit_feedback_to_acme_team`.', + text: 'If this keeps failing after you adjust your request, report it to the Acme team with `submit_feedback_to_acme_team`.', }, ], }); @@ -189,7 +189,7 @@ describe.each(['executor', 'handler'] as const)('error hints (tool %s)', callbac { type: 'text', text: 'nope' }, { type: 'text', - text: 'If this keeps failing after you adjust your request, report it to the Orders maintainers with `submit_feedback_to_orders`.', + text: 'If this keeps failing after you adjust your request, report it to the Orders team with `submit_feedback_to_orders`.', }, ], }); @@ -231,7 +231,7 @@ describe.each(['executor', 'handler'] as const)('error hints (tool %s)', callbac 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 maintainers with `submit_feedback`.", + "Upstream returned 500. If retrying does not help, report it to this server's team with `submit_feedback`.", ); }); diff --git a/packages/mcp/test/feedback.test.ts b/packages/mcp/test/feedback.test.ts index 904978e02dc4..2c2e02d6bcb5 100644 --- a/packages/mcp/test/feedback.test.ts +++ b/packages/mcp/test/feedback.test.ts @@ -114,10 +114,10 @@ describe('feedbackHint', () => { setRegisteredFeedbackTool('submit_feedback', undefined); expect(feedbackHint()).toBe( - "If this keeps failing after you adjust your request, report it to this server's maintainers with `submit_feedback`.", + "If this keeps failing after you adjust your request, report it to this server's team with `submit_feedback`.", ); expect(feedbackHint('If no tool can do this')).toBe( - "If no tool can do this, report it to this server's maintainers with `submit_feedback`.", + "If no tool can do this, report it to this server's team with `submit_feedback`.", ); }); From 318798a8395609d6359792c02f5391686d044674 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 13:04:44 -0500 Subject: [PATCH 28/34] docs(mcp): State the @modelcontextprotocol/sdk 1.23.0 floor Before 1.23.0, the v1 SDK wraps tool schemas with zod v3, so it can't read the feedback tool's zod v4 schema and every call fails. --- packages/mcp/README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 226f026fcbcd..50395f953480 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -14,8 +14,9 @@ [![npm dm](https://img.shields.io/npm/dm/@sentry/mcp.svg)](https://www.npmjs.com/package/@sentry/mcp) [![npm dt](https://img.shields.io/npm/dt/@sentry/mcp.svg)](https://www.npmjs.com/package/@sentry/mcp) -Helpers for MCP servers instrumented with a Sentry SDK. Works with `@modelcontextprotocol/sdk` v1 and -`@modelcontextprotocol/server` v2. +Helpers for MCP servers instrumented with a Sentry SDK. Works with `@modelcontextprotocol/sdk` 1.23.0 or newer and +`@modelcontextprotocol/server` v2. Older v1 versions can't read the feedback tool's zod v4 schema, so agents can't call +it. > NOTICE: This package is in beta state and may be subject to breaking changes. From 10b3fc71aa3695ce7abbbcea6717697902a2ef25 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 13:14:25 -0500 Subject: [PATCH 29/34] fix(mcp): Add error hints on @modelcontextprotocol/sdk 1.23.x Before 1.24.0, the v1 SDK keeps a registered tool's function under callback instead of handler, so the wrapper skipped those tools and no hints were added. --- packages/mcp/src/errorHints.ts | 7 ++++--- packages/mcp/test/errorHints.test.ts | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/packages/mcp/src/errorHints.ts b/packages/mcp/src/errorHints.ts index 250ed9a67830..a495845ba4fc 100644 --- a/packages/mcp/src/errorHints.ts +++ b/packages/mcp/src/errorHints.ts @@ -104,14 +104,15 @@ export function addErrorHints( } } -// MCP SDK v2 calls a registered tool's `executor`, v1 calls its `handler`. +// 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, hint: string, shouldHint: ErrorHintFilter): void { if (!isObjectLike(tool) || wrappedTools.has(tool)) { return; } - const key = - typeof tool['executor'] === 'function' ? 'executor' : typeof tool['handler'] === 'function' ? 'handler' : undefined; + const key = TOOL_CALLBACK_KEYS.find(candidate => typeof tool[candidate] === 'function'); if (!key) { return; } diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index 0b12a0df7d0f..dbd8e772faf9 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -16,8 +16,9 @@ const HINT = type Callback = (...args: unknown[]) => unknown; -// Mirrors where each MCP SDK keeps a registered tool's callback: `executor` in v2, `handler` in v1. -function createServer(callbackKey: 'executor' | 'handler') { +// 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> = {}; const server = { _registeredTools, @@ -42,7 +43,7 @@ function runEventProcessors(event: Event, originalException: unknown): Event { ); } -describe.each(['executor', 'handler'] as const)('error hints (tool %s)', callbackKey => { +describe.each(['executor', 'handler', 'callback'] as const)('error hints (tool %s)', callbackKey => { beforeEach(() => { vi.mocked(getClient).mockReturnValue({ getDsn: () => ({}), From a738f64527e24379b70ac340e49f3c8d74bc1660 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 13:25:47 -0500 Subject: [PATCH 30/34] fix(mcp): Keep error hints after a tool's callback is updated update({ callback }) puts a new function under the key we wrapped (v2 rebuilds executor), which dropped the hint. Wrap update so the new function is wrapped too, and follow renames for the errorHints filter. --- packages/mcp/src/errorHints.ts | 37 ++++++++++++++++++++++++---- packages/mcp/test/errorHints.test.ts | 33 +++++++++++++++++++++++-- 2 files changed, 63 insertions(+), 7 deletions(-) diff --git a/packages/mcp/src/errorHints.ts b/packages/mcp/src/errorHints.ts index a495845ba4fc..2f0e584d3b8a 100644 --- a/packages/mcp/src/errorHints.ts +++ b/packages/mcp/src/errorHints.ts @@ -24,6 +24,7 @@ const JSON_RPC_CLIENT_ERROR_CODES = new Set([-32700, -32600, -32601, -32602, -32 const originalMessages = new WeakMap(); const wrappedTools = new WeakSet(); +const hintCallbacks = new WeakSet(); let processorAdded = false; /** @@ -112,16 +113,42 @@ function wrapRegisteredTool(name: string, tool: unknown, hint: string, shouldHin return; } - const key = TOOL_CALLBACK_KEYS.find(candidate => typeof tool[candidate] === 'function'); - if (!key) { + if (!TOOL_CALLBACK_KEYS.some(candidate => typeof tool[candidate] === 'function')) { return; } wrappedTools.add(tool); - const original = tool[key] as ToolCallback; - tool[key] = function (this: unknown, ...args: unknown[]): Promise { - return callWithHint(() => original.apply(this, args), name, hint, shouldHint); + let toolName = name; + const wrapCallback = (): void => { + const key = TOOL_CALLBACK_KEYS.find(candidate => typeof tool[candidate] === 'function'); + const original = key ? (tool[key] as ToolCallback) : undefined; + if (!key || !original || hintCallbacks.has(original)) { + return; + } + + const wrapped = function (this: unknown, ...args: unknown[]): Promise { + return callWithHint(() => original.apply(this, args), toolName, hint, shouldHint); + }; + hintCallbacks.add(wrapped); + tool[key] = wrapped; }; + + wrapCallback(); + + // `update({ callback })` replaces the function we wrapped (v2 rebuilds `executor`), so wrap the new one. + if (typeof tool['update'] === 'function') { + fill(tool, 'update', (originalUpdate: ToolCallback) => { + return function (this: unknown, updates: unknown, ...rest: unknown[]): unknown { + const result = originalUpdate.call(this, updates, ...rest); + if (isObjectLike(updates) && typeof updates['name'] === 'string') { + toolName = updates['name']; + } + wrapCallback(); + + return result; + }; + }); + } } async function callWithHint( diff --git a/packages/mcp/test/errorHints.test.ts b/packages/mcp/test/errorHints.test.ts index dbd8e772faf9..f71d06a45fbe 100644 --- a/packages/mcp/test/errorHints.test.ts +++ b/packages/mcp/test/errorHints.test.ts @@ -23,8 +23,18 @@ function createServer(callbackKey: 'executor' | 'handler' | 'callback') { const server = { _registeredTools, registerTool(name: string, _config: unknown, callback: Callback) { - _registeredTools[name] = { [callbackKey]: callback }; - return _registeredTools[name]; + const tool: Record = { + [callbackKey]: callback, + // Like the SDKs, `update({ callback })` puts the new function under the same key + update: (updates: unknown) => { + const { callback: next } = updates as { callback?: Callback }; + if (next) { + tool[callbackKey] = next; + } + }, + }; + _registeredTools[name] = tool; + return tool; }, call(name: string, ...args: unknown[]) { return Promise.resolve(_registeredTools[name]![callbackKey]!(...args)); @@ -216,6 +226,25 @@ describe.each(['executor', 'handler', 'callback'] as const)('error hints (tool % }); }); + it('keeps the hint after the tool callback is updated', async () => { + const server = createServer(callbackKey); + addFeedbackTool(server); + const tool = server.registerTool('failed', {}, () => ({ + isError: true, + content: [{ type: 'text', text: 'first' }], + })); + tool.update!({ callback: () => ({ isError: true, content: [{ type: 'text', text: 'second' }] }) }); + tool.update!({ enabled: false }); + + await expect(server.call('failed')).resolves.toEqual({ + isError: true, + content: [ + { type: 'text', text: 'second' }, + { type: 'text', text: HINT }, + ], + }); + }); + it('does not add a second hint to failures that already have one', async () => { const server = createServer(callbackKey); addFeedbackTool(server); From b4637a1d5c0e0434c813b895f9c454144ef42be5 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 13:40:40 -0500 Subject: [PATCH 31/34] fix(mcp): Return an error from captureAgentFeedback without a Sentry client, scrub current API keys Without a client, captureFeedback drops the event but still returns an ID, so custom handlers told the agent its report was sent. The check now lives in captureAgentFeedback instead of only the built-in handler. The key pattern only matched legacy 48-character OpenAI keys. It now also catches sk-proj-, sk-svcacct- and sk-ant- keys, since feedback events skip beforeSend. --- packages/mcp/src/createFeedbackTool.ts | 5 ---- packages/mcp/src/feedback.ts | 10 ++++++-- packages/mcp/test/feedback.test.ts | 32 ++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 7 deletions(-) diff --git a/packages/mcp/src/createFeedbackTool.ts b/packages/mcp/src/createFeedbackTool.ts index 0da48b634733..b8e549d749de 100644 --- a/packages/mcp/src/createFeedbackTool.ts +++ b/packages/mcp/src/createFeedbackTool.ts @@ -9,7 +9,6 @@ import { feedbackInputSchema, feedbackOutputSchema, getFeedbackToolDescription, - isFeedbackAvailable, setRegisteredFeedbackTool, } from './feedback'; @@ -102,10 +101,6 @@ export function createFeedbackTool(options: CreateFeedbackToolOptions = {}): Fee const recipient = options.serverName ? `the ${options.serverName} team` : undefined; const handler = (input: AgentFeedback, context?: unknown): FeedbackToolResult => { - if (!isFeedbackAvailable()) { - return { isError: true, content: [{ type: 'text', text: "Feedback isn't available on this server." }] }; - } - const result = captureAgentFeedback(input, { clientName: getClientName(server, context), scrub: options.scrub, diff --git a/packages/mcp/src/feedback.ts b/packages/mcp/src/feedback.ts index 92748699f6fb..bd3e94d30021 100644 --- a/packages/mcp/src/feedback.ts +++ b/packages/mcp/src/feedback.ts @@ -24,7 +24,8 @@ const PLACEHOLDER_DESCRIPTIONS = new Set([ ]); const SCRUB_PATTERNS: Array<[RegExp, string]> = [ - [/\bsk-[a-zA-Z0-9]{48}\b/g, '[REDACTED_OPENAI_KEY]'], + // OpenAI (`sk-…`, `sk-proj-…`, `sk-svcacct-…`) and Anthropic (`sk-ant-…`) keys + [/\bsk-[A-Za-z0-9_-]{20,}/g, '[REDACTED_API_KEY]'], [/\bBearer\s+[a-zA-Z0-9\-._~+/]+={0,}/g, 'Bearer [REDACTED_TOKEN]'], [/\bsntrys_[a-zA-Z0-9_]+\b/g, '[REDACTED_SENTRY_TOKEN]'], [/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, '[REDACTED_EMAIL]'], @@ -130,12 +131,17 @@ export function isFeedbackAvailable(): boolean { /** * Sends a report the agent made through the feedback tool to Sentry as User Feedback. * - * Returns an error for the agent instead when the description is filler, such as `test` or `N/A`. + * Returns an error for the agent instead while Sentry has no client, since the report would be dropped, and when the + * description is filler, such as `test` or `N/A`. */ export function captureAgentFeedback( feedback: AgentFeedback, options: CaptureAgentFeedbackOptions = {}, ): CaptureAgentFeedbackResult { + if (!isFeedbackAvailable()) { + return { ok: false, error: "Feedback isn't available on this server." }; + } + if (isPlaceholder(feedback.description)) { return { ok: false, diff --git a/packages/mcp/test/feedback.test.ts b/packages/mcp/test/feedback.test.ts index 2c2e02d6bcb5..9e3563ad99be 100644 --- a/packages/mcp/test/feedback.test.ts +++ b/packages/mcp/test/feedback.test.ts @@ -52,6 +52,38 @@ describe('captureAgentFeedback', () => { }); }); + it.each([ + 'sk-proj-Ab3_dE5-fG7hI9jK1lM3nO5pQ7rS9tU1vW3xY5z', + 'sk-svcacct-Ab3dE5fG7hI9jK1lM3nO5pQ7rS9tU1', + 'sk-ant-api03-Ab3dE5fG7hI9jK1lM3nO5pQ7rS9tU1vW3_xY5z-AA', + `sk-${'a1B2'.repeat(12)}`, + ])('removes the API key %s', key => { + captureAgentFeedback({ + task: 'call api', + kind: 'broken', + impact: 'blocked', + description: `Used ${key} and got 401`, + }); + + expect(captureFeedback).toHaveBeenCalledWith( + expect.objectContaining({ message: 'Task: call api\n\nUsed [REDACTED_API_KEY] and got 401' }), + ); + }); + + it('returns an error and sends nothing while Sentry has no client', () => { + vi.mocked(getClient).mockReturnValue(undefined); + + const result = captureAgentFeedback({ + task: 'find orders', + kind: 'broken', + impact: 'blocked', + description: 'Failed.', + }); + + expect(result).toEqual({ ok: false, error: "Feedback isn't available on this server." }); + expect(captureFeedback).not.toHaveBeenCalled(); + }); + it('applies the custom scrubber after the built-in one', () => { captureAgentFeedback( { task: 'read logs', kind: 'broken', impact: 'friction', description: 'Bucket s3://acme-prod failed' }, From f7a755e60ae0d422d3c95b2c3e2de38825cbdf05 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 13:40:40 -0500 Subject: [PATCH 32/34] ref(mcp): Drop the tool() fallback in addFeedbackTool Only v1 servers older than the 1.23.0 floor lack registerTool. Error hints still wrap tool(), since newer servers can register other tools with it. --- packages/mcp/src/addFeedbackTool.ts | 20 +++----------------- packages/mcp/test/addFeedbackTool.test.ts | 11 +++-------- 2 files changed, 6 insertions(+), 25 deletions(-) diff --git a/packages/mcp/src/addFeedbackTool.ts b/packages/mcp/src/addFeedbackTool.ts index c65ea92ef8bf..f9c422a42b33 100644 --- a/packages/mcp/src/addFeedbackTool.ts +++ b/packages/mcp/src/addFeedbackTool.ts @@ -10,12 +10,6 @@ interface McpServerLike { config: FeedbackToolDefinition['config'], handler: FeedbackToolDefinition['handler'], ) => unknown; - tool?: ( - name: string, - description: string, - inputSchema: FeedbackToolDefinition['config']['inputSchema'], - handler: FeedbackToolDefinition['handler'], - ) => unknown; } /** @@ -42,19 +36,11 @@ export type AddFeedbackToolOptions = Omit; */ export function addFeedbackTool(mcpServer: object, options: AddFeedbackToolOptions = {}): void { const server: McpServerLike = mcpServer; - if (typeof server.registerTool !== 'function' && typeof server.tool !== 'function') { - DEBUG_BUILD && - debug.warn('[MCP] Could not register the feedback tool: the server has no `registerTool` or `tool` method.'); + if (typeof server.registerTool !== 'function') { + DEBUG_BUILD && debug.warn('[MCP] Could not register the feedback tool: the server has no `registerTool` method.'); return; } const tool = createFeedbackTool({ ...options, server: mcpServer }); - - if (typeof server.registerTool === 'function') { - server.registerTool(tool.name, tool.config, tool.handler); - - return; - } - - server.tool?.(tool.name, tool.config.description, tool.config.inputSchema, tool.handler); + server.registerTool(tool.name, tool.config, tool.handler); } diff --git a/packages/mcp/test/addFeedbackTool.test.ts b/packages/mcp/test/addFeedbackTool.test.ts index c2940de1a633..cc9719039da0 100644 --- a/packages/mcp/test/addFeedbackTool.test.ts +++ b/packages/mcp/test/addFeedbackTool.test.ts @@ -90,17 +90,12 @@ describe('addFeedbackTool', () => { ); }); - it('falls back to the legacy tool() method', () => { + it('does not register the tool on servers without registerTool', () => { const tool = vi.fn(); - addFeedbackTool({ tool }, { name: 'submit_feedback_to_acme_team', description: 'Custom.' }); + addFeedbackTool({ tool }); - expect(tool).toHaveBeenCalledWith( - 'submit_feedback_to_acme_team', - 'Custom.', - feedbackInputSchema, - expect.any(Function), - ); + expect(tool).not.toHaveBeenCalled(); }); it('returns a tool error for filler reports', () => { From 5b87913f68ad1debab31c832f24cc1e04c44c766 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 13:40:40 -0500 Subject: [PATCH 33/34] fix(scripts): Move range peer dependencies to the new major in bump-version Range peers like @sentry/mcp's on @sentry/core stay put within a major, but a major release would have shipped them still pinned to the old one. Move them to ^.0.0 (^.0.0-0 for prereleases), and fail before writing anything for a range form the script can't move. --- scripts/bump-version.js | 36 +++++++++++++++++++++++++++++++-- scripts/bump-version.test.ts | 39 ++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/scripts/bump-version.js b/scripts/bump-version.js index dd56b5ee11bf..01dc7e738b95 100644 --- a/scripts/bump-version.js +++ b/scripts/bump-version.js @@ -20,8 +20,9 @@ function updateWorkspaceDeps(pkgPath, workspaceNames, newVersion, { bumpVersion continue; } - // Range peers (like `@sentry/mcp`'s on `@sentry/core`) work with any SDK in range, so only exact peers follow the release. + // Range peers (like `@sentry/mcp`'s on `@sentry/core`) work with any SDK in range, so they only follow a new major. if (depType === 'peerDependencies' && !/^\d/.test(ver)) { + pkg[depType][dep] = getRangeForMajor(ver, newVersion, `${dep} in ${pkgPath}`); continue; } @@ -33,6 +34,25 @@ function updateWorkspaceDeps(pkgPath, workspaceNames, newVersion, { bumpVersion return pkg; } +/** + * Returns the range peer for `newVersion`: unchanged within a major, `^.0.0` at a new major, and + * `^.0.0-0` at a new major's prerelease so alphas and betas still satisfy it. + * Throws for other range forms, so a major release can't ship a peer range that excludes it. + */ +function getRangeForMajor(range, newVersion, label) { + const match = /^\^(\d+)\.\d+\.\d+(-0)?$/.exec(range); + if (!match) { + throw new Error(`Can't move the peer range ${label} (${range}) to ${newVersion}. Use the form ^.0.0.`); + } + + const newMajor = newVersion.split('.')[0]; + if (match[1] === newMajor) { + return range; + } + + return newVersion.includes('-') ? `^${newMajor}.0.0-0` : `^${newMajor}.0.0`; +} + function updateTarballVersions(filePath, newVersion) { const content = fs.readFileSync(filePath, 'utf-8'); fs.writeFileSync(filePath, content.replace(/(?<=sentry-[\w-]+-)\d+\.\d+\.\d+(-[\w.]+)?(?=\.tgz)/g, newVersion)); @@ -46,7 +66,8 @@ function updateTarballVersions(filePath, newVersion) { * Specifically: * - Updates `version` in every workspace package.json to newVersion * - Updates all internal workspace dependency references (dependencies, devDependencies, peerDependencies) - * to the new exact version (no ^ or ~ prefix), matching lerna's --exact flag + * to the new exact version (no ^ or ~ prefix), matching lerna's --exact flag. Range peerDependencies + * (`^.0.0`) are kept within a major and moved to the new major on a major release * - --force-publish: all packages are updated regardless of whether they changed * - No git tags, commits, or pushes are made */ @@ -64,11 +85,22 @@ function bumpVersions(rootDir, newVersion) { // before writing any changes (no partial updates). const workspaceNames = new Set(); const workspacePkgPaths = []; + const workspacePkgs = []; for (const workspace of workspaces) { const pkgPath = path.join(rootDir, workspace, 'package.json'); const pkg = readJson(pkgPath); workspaceNames.add(pkg.name); workspacePkgPaths.push(pkgPath); + workspacePkgs.push([pkgPath, pkg]); + } + + // Check range peers upfront too, so one that can't move to the new major fails before anything is written. + for (const [pkgPath, pkg] of workspacePkgs) { + for (const [dep, ver] of Object.entries(pkg.peerDependencies ?? {})) { + if (workspaceNames.has(dep) && !ver.startsWith('workspace:') && !/^\d/.test(ver)) { + getRangeForMajor(ver, newVersion, `${dep} in ${pkgPath}`); + } + } } // Apply version bumps diff --git a/scripts/bump-version.test.ts b/scripts/bump-version.test.ts index 0fcbc32e72f6..d17abb1258d1 100644 --- a/scripts/bump-version.test.ts +++ b/scripts/bump-version.test.ts @@ -140,6 +140,45 @@ describe('bump-version', () => { expect(mcp.peerDependencies['@sentry/core']).toBe('^10.0.0'); }); + it.each([ + ['11.0.0', '^11.0.0'], + ['11.0.0-alpha.0', '^11.0.0-0'], + ])('moves range peerDependencies to the new major (%s)', (newVersion, expected) => { + const rootDir = tracked( + setupFixture({ + packages: { + 'packages/core': { name: '@sentry/core', version: '10.1.0' }, + 'packages/mcp': { + name: '@sentry/mcp', + version: '10.1.0', + peerDependencies: { '@sentry/core': '^10.0.0' }, + }, + }, + }), + ); + + bumpVersions(rootDir, newVersion); + expect(readPackageJson(path.join(rootDir, 'packages/mcp')).peerDependencies['@sentry/core']).toBe(expected); + }); + + it('throws for a range peerDependency it cannot move to a new major', () => { + const rootDir = tracked( + setupFixture({ + packages: { + 'packages/core': { name: '@sentry/core', version: '10.1.0' }, + 'packages/mcp': { + name: '@sentry/mcp', + version: '10.1.0', + peerDependencies: { '@sentry/core': '>=10.0.0' }, + }, + }, + }), + ); + + expect(() => bumpVersions(rootDir, '11.0.0')).toThrow("Can't move the peer range @sentry/core"); + expect(readPackageJson(path.join(rootDir, 'packages/core')).version).toBe('10.1.0'); + }); + it('does not modify external (non-workspace) dependencies', () => { const rootDir = tracked( setupFixture({ From 7ad8373adc7e023fb6480b03e152fc850c0a2425 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 1 Dec 2026 13:41:24 -0500 Subject: [PATCH 34/34] test(mcp): Type the fake server's handler so createFeedbackTool's handler fits The fake typed the handler as taking no arguments, which the real handler, with its required input, isn't assignable to. --- packages/mcp/test/createFeedbackTool.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/mcp/test/createFeedbackTool.test.ts b/packages/mcp/test/createFeedbackTool.test.ts index 2be74e067447..f56c946c27a4 100644 --- a/packages/mcp/test/createFeedbackTool.test.ts +++ b/packages/mcp/test/createFeedbackTool.test.ts @@ -79,10 +79,11 @@ describe('createFeedbackTool', () => { ])( "adds error hints to the server's other tools when given the server (errorHints: %s)", async (errorHints, hinted) => { - const tools: Record unknown }> = {}; + type Handler = (...args: never[]) => unknown; + const tools: Record = {}; const server = { _registeredTools: tools, - registerTool: (name: string, _config: unknown, handler: () => unknown) => (tools[name] = { handler }), + registerTool: (name: string, _config: unknown, handler: Handler) => (tools[name] = { handler }), }; const failed = { isError: true, content: [{ type: 'text', text: 'Upstream returned 500.' }] };