diff --git a/packages/mcp-core/src/skillDefinitions.json b/packages/mcp-core/src/skillDefinitions.json index 4c48b44e0..a0e2af735 100644 --- a/packages/mcp-core/src/skillDefinitions.json +++ b/packages/mcp-core/src/skillDefinitions.json @@ -5,7 +5,7 @@ "description": "Read-only access to core Sentry data: issues, events, traces, replays, releases, cron monitors, uptime monitors, metric monitors, profiles, documentation, and project metadata", "defaultEnabled": true, "order": 1, - "toolCount": 49, + "toolCount": 50, "tools": [ { "name": "find_alert_rules", @@ -197,6 +197,11 @@ "description": "Search Sentry agent conversations (formerly AI conversations): one summary row per LLM agent conversation with title, cost, tokens, call counts, and previews. For one conversation's transcript, use get_agent_conversation_details.", "requiredScopes": ["event:read", "project:read"] }, + { + "name": "search_attributes", + "description": "Find span, log, or metric attribute keys in Sentry by meaning or partial name, with their types, descriptions, examples, and deprecation status. Alternatively, list the spans, logs, or metric attributes available. Use it to get information about attributes or find the exact key before searching traces, logs, or metrics. For attribute values, use search_traces, search_logs, or search_metrics; for issue tag values, use get_issue_tag_values.", + "requiredScopes": ["event:read"] + }, { "name": "search_docs", "description": "Search Sentry documentation for SDK setup, framework integrations, instrumentation, and configuration such as sampling, data scrubbing, and source maps. Returns matching page paths and snippets only. Use the Sentry tool `get_doc` to read a full page.", diff --git a/packages/mcp-core/src/toolDefinitions.json b/packages/mcp-core/src/toolDefinitions.json index 5d124006b..c0b8bdca6 100644 --- a/packages/mcp-core/src/toolDefinitions.json +++ b/packages/mcp-core/src/toolDefinitions.json @@ -13356,6 +13356,230 @@ "replacedBy": ["search_agent_conversations"] } }, + { + "name": "search_attributes", + "title": "Search Attributes", + "description": "Find span, log, or metric attribute keys in Sentry by meaning or partial name, with their types, descriptions, examples, and deprecation status. Alternatively, list the spans, logs, or metric attributes available. Use it to get information about attributes or find the exact key before searching traces, logs, or metrics. For attribute values, use search_traces, search_logs, or search_metrics; for issue tag values, use get_issue_tag_values.", + "inputSchema": { + "type": "object", + "properties": { + "organizationSlug": { + "type": "string", + "description": "The organization slug, from `find_organizations`. In `org/project` notation, the part before the slash." + }, + "projectSlug": { + "default": null, + "anyOf": [ + { + "type": "string", + "description": "The project slug. In `org/project` notation, the part after the slash." + }, + { + "type": "null" + } + ] + }, + "query": { + "description": "What attribute to find, in plain English or as part of a key. Omit to list the dataset's attributes.", + "type": "string" + }, + "period": { + "type": "string", + "pattern": "^\\d+[mhdw]$", + "description": "Relative time window, e.g. `30m`, `24h`, `7d`, `90d`." + }, + "regionUrl": { + "default": null, + "anyOf": [ + { + "type": "string", + "description": "The organization's region URL from `find_organizations`, e.g. `https://us.sentry.io`. Omit for self-hosted Sentry." + }, + { + "type": "null" + } + ] + }, + "limit": { + "description": "Maximum attributes to return. Defaults to 10 with a query and 50 when listing.", + "type": "number", + "minimum": 1, + "maximum": 100 + }, + "dataset": { + "type": "string", + "enum": ["spans", "logs", "metrics"], + "description": "Dataset to search: spans for requests, latency, DB, or AI calls; logs for log lines; metrics for counters, gauges, and distributions." + }, + "fresh": { + "description": "Bypass cached reads.", + "type": "boolean" + } + }, + "required": ["organizationSlug", "dataset"] + }, + "outputSchema": { + "type": "object", + "properties": { + "dataset": { + "type": "string", + "enum": ["spans", "logs", "metrics"] + }, + "period": { + "type": "string" + }, + "query": { + "type": ["string", "null"] + }, + "resultType": { + "type": "string", + "enum": ["list", "matches"], + "description": "list: the dataset's attributes. matches: the attributes that answer query." + }, + "best": { + "anyOf": [ + { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The exact key to use with search_traces, search_logs, or search_metrics." + }, + "type": { + "type": "string", + "enum": ["string", "number", "boolean", "array"] + }, + "addedBySentry": { + "type": "boolean" + }, + "description": { + "type": ["string", "null"] + }, + "examples": { + "type": "array", + "items": { + "type": ["string", "number", "boolean"] + } + }, + "aliases": { + "type": "array", + "items": { + "type": "string" + } + }, + "deprecated": { + "type": "boolean" + }, + "replacementKey": { + "description": "The key that replaces this one, when it's deprecated.", + "type": ["string", "null"] + } + }, + "required": [ + "key", + "type", + "addedBySentry", + "description", + "examples", + "aliases", + "deprecated", + "replacementKey" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "With matches, the one key that clearly answers query, if any." + }, + "attributes": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The exact key to use with search_traces, search_logs, or search_metrics." + }, + "type": { + "type": "string", + "enum": ["string", "number", "boolean", "array"] + }, + "addedBySentry": { + "type": "boolean" + }, + "description": { + "type": ["string", "null"] + }, + "examples": { + "type": "array", + "items": { + "type": ["string", "number", "boolean"] + } + }, + "aliases": { + "type": "array", + "items": { + "type": "string" + } + }, + "deprecated": { + "type": "boolean" + }, + "replacementKey": { + "description": "The key that replaces this one, when it's deprecated.", + "type": ["string", "null"] + } + }, + "required": [ + "key", + "type", + "addedBySentry", + "description", + "examples", + "aliases", + "deprecated", + "replacementKey" + ], + "additionalProperties": false + }, + "description": "With list, the attributes shown. With matches, the other candidates, most relevant first." + }, + "totalAttributes": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991, + "description": "How many attributes this result was picked from, before limit." + }, + "presentationHint": { + "description": "How best to present this data.", + "type": ["string", "null"] + }, + "notes": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "dataset", + "period", + "query", + "resultType", + "best", + "attributes", + "totalAttributes", + "presentationHint", + "notes" + ], + "additionalProperties": false + }, + "requiredScopes": ["event:read"], + "skills": ["inspect"], + "surface": "direct" + }, { "name": "search_docs", "title": "Search Sentry Docs", diff --git a/packages/mcp-core/src/tools/catalog/search-attributes.test.ts b/packages/mcp-core/src/tools/catalog/search-attributes.test.ts index ff7f5fad7..d241bd6ed 100644 --- a/packages/mcp-core/src/tools/catalog/search-attributes.test.ts +++ b/packages/mcp-core/src/tools/catalog/search-attributes.test.ts @@ -175,10 +175,12 @@ describe("search_attributes", () => { }); describe("requests", () => { - it("requires a spans, logs, or metrics dataset", async () => { - await expect(search({})).rejects.toThrowErrorMatchingInlineSnapshot( - `[UserInputError: Choose a dataset: \`spans\` (requests, latency, database and AI calls), \`logs\` (log lines), or \`metrics\` (counters, gauges, distributions).]`, - ); + it("requires a spans, logs, or metrics dataset", () => { + expect(() => + z + .object(searchAttributes.inputSchema) + .parse({ organizationSlug: "sentry-mcp-evals" }), + ).toThrow(); expect(() => z .object(searchAttributes.inputSchema) @@ -614,6 +616,72 @@ describe("search_attributes", () => { }, ); + it("keeps the note when every hint search fails", async () => { + vi.spyOn(logging, "logIssue").mockReturnValue(undefined); + // 501 isn't retried, which keeps the test fast. + serveAttributes((substring) => + substring === null + ? FULL_PAGE + : HttpResponse.json({ detail: "Server error" }, { status: 501 }), + ); + mockGenerateText + .mockResolvedValueOnce(mockAgentResponse({ hints: ["payment"] })) + .mockResolvedValueOnce( + mockAgentResponse({ best: null, candidates: [] }), + ); + + const output = await search({ + query: "payment provider", + dataset: "spans", + }); + + // Only the cut-off list was searched, so a miss may not be real. + expect(output.notes).toContain(KEY_CAP_NOTE); + }); + + it("keeps the note when only some hint searches fail", async () => { + vi.spyOn(logging, "logIssue").mockReturnValue(undefined); + // 501 isn't retried, which keeps the test fast. + serveAttributes((substring) => { + if (substring === null) return FULL_PAGE; + if (substring === "processor") { + return HttpResponse.json({ detail: "Server error" }, { status: 501 }); + } + return [userAttribute("payment.processor")]; + }); + mockGenerateText + .mockResolvedValueOnce( + mockAgentResponse({ hints: ["payment", "processor"] }), + ) + .mockResolvedValueOnce( + mockAgentResponse({ best: "payment.processor", candidates: [] }), + ); + + const output = await search({ + query: "payment provider", + dataset: "spans", + }); + + expect(output.best?.key).toBe("payment.processor"); + // Keys only the failed hint would have found may be missing. + expect(output.notes).toContain(KEY_CAP_NOTE); + }); + + it("keeps the note when a hint search reaches the limit too", async () => { + serveAttributes((substring) => + substring === null ? FULL_PAGE : manyAttributes(1000), + ); + mockGenerateText + .mockResolvedValueOnce(mockAgentResponse({ hints: ["app"] })) + .mockResolvedValueOnce( + mockAgentResponse({ best: null, candidates: [] }), + ); + + const output = await search({ query: "app setting", dataset: "spans" }); + + expect(output.notes).toContain(KEY_CAP_NOTE); + }); + it("leaves the note out when the hint searches find nothing", async () => { // The hint search looked through every key, so a miss is a real miss. const substrings = serveAttributes((substring) => @@ -697,6 +765,57 @@ describe("search_attributes", () => { ); }); + it("passes the call's cancel signal to both agents", async () => { + const controller = new AbortController(); + serveAttributes((substring) => + substring === null ? FULL_PAGE : [userAttribute("payment.processor")], + ); + mockGenerateText + .mockResolvedValueOnce(mockAgentResponse({ hints: ["payment"] })) + .mockResolvedValueOnce( + mockAgentResponse({ best: "payment.processor", candidates: [] }), + ); + + await searchAttributes.handler( + z.object(searchAttributes.inputSchema).parse({ + organizationSlug: "sentry-mcp-evals", + query: "payment provider", + dataset: "spans", + }), + { ...getServerContext(), signal: controller.signal }, + ); + + expect( + mockGenerateText.mock.calls.map(([options]) => options.abortSignal), + ).toEqual([controller.signal, controller.signal]); + }); + + it("stops without reporting hint searches when the call is cancelled", async () => { + const logIssue = vi.spyOn(logging, "logIssue").mockReturnValue(undefined); + const controller = new AbortController(); + serveAttributes((substring) => { + if (substring === null) return FULL_PAGE; + // The client cancels while the hint search is in flight. + controller.abort(); + return HttpResponse.json({ detail: "Server error" }, { status: 501 }); + }); + mockGenerateText.mockResolvedValueOnce( + mockAgentResponse({ hints: ["payment"] }), + ); + + await expect( + searchAttributes.handler( + z.object(searchAttributes.inputSchema).parse({ + organizationSlug: "sentry-mcp-evals", + query: "payment provider", + dataset: "spans", + }), + { ...getServerContext(), signal: controller.signal }, + ), + ).rejects.toThrow(); + expect(logIssue).not.toHaveBeenCalled(); + }); + it("counts the cap per type, not across types", async () => { // 1200 keys in all, but neither type is near its 1000-key cap. const substrings = serveAttributes(() => [ diff --git a/packages/mcp-core/src/tools/catalog/search-attributes.ts b/packages/mcp-core/src/tools/catalog/search-attributes.ts index 12f35ef3a..513ae817f 100644 --- a/packages/mcp-core/src/tools/catalog/search-attributes.ts +++ b/packages/mcp-core/src/tools/catalog/search-attributes.ts @@ -11,12 +11,18 @@ import type { ServerContext } from "../../types"; import { SEARCH_ATTRIBUTES_DATASETS } from "../support/search-attributes/config"; import { searchAttributesOutputSchema } from "../support/search-attributes/format"; import { runSearchAttributes } from "../support/search-attributes/search"; -import { searchToolBase } from "../support/search-events/search"; +import { + logSearchEventsError, + SEARCH_EVENTS_ANNOTATIONS, +} from "../support/search-events/search"; export default defineTool({ - ...searchToolBase("search_attributes"), - experimental: true, - includeInSkillDefinitions: false, + skills: ["inspect"], + requiredScopes: ["event:read"], + annotations: SEARCH_EVENTS_ANNOTATIONS, + onError: (error, params, context) => { + logSearchEventsError("search_attributes", error, params, context); + }, name: "search_attributes", title: "Search Attributes", description: @@ -43,9 +49,8 @@ export default defineTool({ ), dataset: z .enum(SEARCH_ATTRIBUTES_DATASETS) - .optional() .describe( - "Dataset whose attribute keys to list: spans for requests, latency, DB, or AI calls; logs for log lines; metrics for counters, gauges, and distributions.", + "Dataset to search: spans for requests, latency, DB, or AI calls; logs for log lines; metrics for counters, gauges, and distributions.", ), }, outputSchema: searchAttributesOutputSchema, diff --git a/packages/mcp-core/src/tools/support/search-attributes/agent.ts b/packages/mcp-core/src/tools/support/search-attributes/agent.ts index dc650fe00..df6dd1943 100644 --- a/packages/mcp-core/src/tools/support/search-attributes/agent.ts +++ b/packages/mcp-core/src/tools/support/search-attributes/agent.ts @@ -26,15 +26,18 @@ type KeyHintsAgentOutput = z.output; export async function generateKeyHintsAgent({ query, dataset, + abortSignal, }: { query: string; dataset: SearchAttributesDataset; + abortSignal?: AbortSignal | undefined; }): Promise { const { result } = await callEmbeddedAgent({ system: keyHintsSystemPrompt, prompt: `Dataset: ${dataset}\nQuestion: ${query}`, tools: {}, schema: keyHintsAgentOutputSchema, + abortSignal, }); return cleanKeyHints(result.hints); } @@ -86,6 +89,7 @@ export interface ShortlistAttributesAgentOptions { dataset: SearchAttributesDataset; attributes: TraceItemAttribute[]; limit: number; + abortSignal?: AbortSignal | undefined; } /** @@ -100,6 +104,7 @@ export async function shortlistAttributesAgent( prompt: buildShortlistPrompt(options), tools: {}, schema: shortlistAttributesAgentOutputSchema, + abortSignal: options.abortSignal, }); return toAttributeMatches(result, options.attributes, options.limit); } diff --git a/packages/mcp-core/src/tools/support/search-attributes/search.ts b/packages/mcp-core/src/tools/support/search-attributes/search.ts index 0f11a33d5..9f7d8c9e6 100644 --- a/packages/mcp-core/src/tools/support/search-attributes/search.ts +++ b/packages/mcp-core/src/tools/support/search-attributes/search.ts @@ -27,7 +27,7 @@ export interface SearchAttributesParams { period?: string | undefined; regionUrl: string | null; limit?: number | undefined; - dataset?: SearchAttributesDataset | undefined; + dataset: SearchAttributesDataset; } const DEFAULT_PERIOD = "14d"; @@ -54,12 +54,6 @@ export async function runSearchAttributes( setTargetTagsAndAttributes(params); - if (!params.dataset) { - throw new UserInputError( - "Choose a dataset: `spans` (requests, latency, database and AI calls), `logs` (log lines), or `metrics` (counters, gauges, distributions).", - ); - } - // The attributes API filters by numeric project ID, not slug. let projectId: string | undefined; if (params.projectSlug) { @@ -90,9 +84,9 @@ export async function runSearchAttributes( // Set once the hint searches replace rows with a smaller set related to the // query, so the list fallback can say what it's showing. let narrowedByHints = false; - // Set once any hint is searched. Hint searches look through every key, so - // a match past the cut would have turned up. - let searchedHints = false; + // Set once hint searches ran without failing or reaching the limit. They + // look through every key, so a match past the cut would have turned up. + let allSearchHintCallsSuccessful = false; const rowsReachesLimit = mayBeCutOff(rows); @@ -122,14 +116,19 @@ export async function runSearchAttributes( const keyHints = await withAgentFallback({ operation: "search_attributes.key_hints", fallback: () => [], - run: () => generateKeyHintsAgent({ query, dataset }), + run: () => + generateKeyHintsAgent({ + query, + dataset, + abortSignal: apiService.signal, + }), }); - searchedHints = keyHints.length > 0; // A hint search only adds keys, so a failed one is skipped rather than - // failing the call. 4xx and config errors aren't ours to report. + // failing the call. 4xx, config errors and aborted calls aren't ours to report. const searchHint = (hint: string) => fetchRows(hint).catch((error: unknown) => { if ( + !apiService.signal?.aborted && !(error instanceof ApiClientError) && !(error instanceof ConfigurationError) ) { @@ -140,18 +139,25 @@ export async function runSearchAttributes( }, }); } - return []; + // Null, not [], so a failed search isn't mistaken for no match. + return null; }); // If there are results from the hints, use that + recommended keys // otherwise it defaults to the original exhaustive list const hintRows = await Promise.all(keyHints.map(searchHint)); - if (hintRows.some((r) => r.length > 0)) { + const searchedRows = hintRows.filter((r) => r !== null); + allSearchHintCallsSuccessful = + hintRows.length > 0 && + searchedRows.length === hintRows.length && + // it's not fully successful if there were some that were potentially cut off + !searchedRows.some((r) => mayBeCutOff(r)); + if (searchedRows.some((r) => r.length > 0)) { const recommendedKeys = getRecommendedKeysByDataset(dataset); const recommendedRows = rows.filter((attribute) => recommendedKeys.has(attribute.key), ); - rows = mergeByKey([recommendedRows, ...hintRows]); + rows = mergeByKey([recommendedRows, ...searchedRows]); narrowedByHints = true; } } @@ -168,6 +174,7 @@ export async function runSearchAttributes( dataset, attributes: rows, limit: params.limit ?? FIND_LIMIT, + abortSignal: apiService.signal, }), }); @@ -185,7 +192,7 @@ export async function runSearchAttributes( query, matches, totalAttributes: rows.length, - mayBeIncomplete: !searchedHints && rowsReachesLimit, + mayBeIncomplete: !allSearchHintCallsSuccessful && rowsReachesLimit, }); } diff --git a/plugins/sentry-mcp-experimental/agents/sentry-mcp.md b/plugins/sentry-mcp-experimental/agents/sentry-mcp.md index 7f1cdde41..0e65412f7 100644 --- a/plugins/sentry-mcp-experimental/agents/sentry-mcp.md +++ b/plugins/sentry-mcp-experimental/agents/sentry-mcp.md @@ -101,7 +101,7 @@ You are a Sentry expert. Investigate errors, analyze performance, and manage pro ## Key Tool Distinctions -- `search_issues` returns grouped issue lists. The dataset search tools return counts, aggregations, or individual rows: `search_errors` (exceptions/crashes), `search_traces` (spans, requests, latency, and spans whose trace also has a matching log or metric), `search_logs`, `search_metrics`, `search_profiles`, and `search_replays`. +- `search_issues` returns grouped issue lists. The dataset search tools return counts, aggregations, or individual rows: `search_errors` (exceptions/crashes), `search_traces` (spans, requests, latency, and spans whose trace also has a matching log or metric), `search_logs`, `search_metrics`, `search_profiles`, and `search_replays`. `search_attributes` finds or lists attribute keys and their metadata for the spans, logs, or metrics datasets. - `get_sentry_resource` fetches a known issue, event, trace, span, replay, or generic Sentry resource from a URL or resource ID. It also routes supported profile URLs to profile details. Use `get_issue_breadcrumbs` for an issue's breadcrumb trail. `analyze_issue_with_seer` provides AI root cause analysis with code fixes. - Use `get_snapshot` for a preprod snapshot diff summary from `organizationSlug` + `snapshotId`. For snapshot URLs, use `get_sentry_resource` instead. - Use `get_snapshot_image` for metadata and preview/full image content for one snapshot image. Use the exact `image_file_name` from `get_snapshot` as `imageIdentifier`. diff --git a/plugins/sentry-mcp/agents/sentry-mcp.md b/plugins/sentry-mcp/agents/sentry-mcp.md index f709c5ba4..c704a9f0c 100644 --- a/plugins/sentry-mcp/agents/sentry-mcp.md +++ b/plugins/sentry-mcp/agents/sentry-mcp.md @@ -68,6 +68,7 @@ allowedTools: - render_issue_chart - render_sentry_chart - search_agent_conversations + - search_attributes - search_docs - search_errors - search_issue_events @@ -102,7 +103,7 @@ You are a Sentry expert. Investigate errors, analyze performance, and manage pro ## Key Tool Distinctions -- `search_issues` returns grouped issue lists. The dataset search tools return counts, aggregations, or individual rows: `search_errors` (exceptions/crashes), `search_traces` (spans, requests, latency, and spans whose trace also has a matching log or metric), `search_logs`, `search_metrics`, `search_profiles`, and `search_replays`. +- `search_issues` returns grouped issue lists. The dataset search tools return counts, aggregations, or individual rows: `search_errors` (exceptions/crashes), `search_traces` (spans, requests, latency, and spans whose trace also has a matching log or metric), `search_logs`, `search_metrics`, `search_profiles`, and `search_replays`. `search_attributes` finds or lists attribute keys and their metadata for the spans, logs, or metrics datasets. - `get_sentry_resource` fetches a known issue, event, trace, span, replay, or generic Sentry resource from a URL or resource ID. It also routes supported profile URLs to profile details. Use `get_issue_breadcrumbs` for an issue's breadcrumb trail. `analyze_issue_with_seer` provides AI root cause analysis with code fixes. - Use `get_snapshot` for a preprod snapshot diff summary from `organizationSlug` + `snapshotId`. For snapshot URLs, use `get_sentry_resource` instead. - Use `get_snapshot_image` for metadata and preview/full image content for one snapshot image. Use the exact `image_file_name` from `get_snapshot` as `imageIdentifier`.