diff --git a/packages/mcp-core/src/api-client/client.test.ts b/packages/mcp-core/src/api-client/client.test.ts index 3ffc8f115..5238b44aa 100644 --- a/packages/mcp-core/src/api-client/client.test.ts +++ b/packages/mcp-core/src/api-client/client.test.ts @@ -226,6 +226,26 @@ describe("API bearer token validation", () => { ); expect(requests).toBe(0); }); + + it("sends no ID filter only for an explicit all selection", async () => { + let url: URL | undefined; + mswServer.use( + http.delete( + "https://sentry.io/api/0/organizations/test-org/inbox/", + ({ request }) => { + url = new URL(request.url); + return new HttpResponse(null, { status: 204 }); + }, + ), + ); + + await new SentryApiService({ accessToken: "test-token" }).removeInboxItems({ + organizationSlug: "test-org", + selection: "all", + }); + + expect(url?.search).toBe(""); + }); }); describe("single-tenant web URLs", () => { @@ -2341,6 +2361,37 @@ describe("listIssues request", () => { }); }); +describe("inbox mutations", () => { + afterEach(() => mswServer.resetHandlers()); + + // Sentry applies an unfiltered inbox PUT or DELETE to every item. + it("refuses an empty or non-numeric selection without sending a request", async () => { + let requests = 0; + mswServer.use( + http.all("https://sentry.io/api/0/organizations/test-org/inbox/", () => { + requests += 1; + return HttpResponse.json({ updatedCount: 0 }); + }), + ); + const api = new SentryApiService({ accessToken: "test-token" }); + + await expect( + api.removeInboxItems({ organizationSlug: "test-org", selection: [] }), + ).rejects.toThrow("Select at least one inbox item ID."); + await expect( + api.updateInboxItems({ + organizationSlug: "test-org", + selection: [], + body: { isRead: true }, + }), + ).rejects.toThrow("Select at least one inbox item ID."); + await expect( + api.removeInboxItems({ organizationSlug: "test-org", selection: [""] }), + ).rejects.toThrow("Inbox item ID must be numeric"); + expect(requests).toBe(0); + }); +}); + describe("host configuration", () => { it("should handle hostname without protocol", () => { const apiService = new SentryApiService({ host: "sentry.io" }); diff --git a/packages/mcp-core/src/api-client/client.ts b/packages/mcp-core/src/api-client/client.ts index e305661ae..f6c816f01 100644 --- a/packages/mcp-core/src/api-client/client.ts +++ b/packages/mcp-core/src/api-client/client.ts @@ -87,7 +87,7 @@ import { } from "@sentry/api/client/endpoints"; import { z } from "zod"; import { DEFAULT_SEARCH_ISSUES_PERIOD } from "../constants"; -import { ConfigurationError } from "../errors"; +import { ConfigurationError, UserInputError } from "../errors"; import { isFreshRead } from "../internal/fresh-reads"; import { logIssue, logWarn } from "../telem/logging"; import type { SentryProtocol } from "../types"; @@ -145,6 +145,9 @@ import { ExternalIssueListSchema, ExternalIssueSchema, FlamegraphSchema, + InboxItemEventListSchema, + InboxItemListSchema, + InboxUpdateResponseSchema, IssueActivityListResponseSchema, IssueAlertRuleListSchema, IssueAlertRuleSchema, @@ -223,6 +226,8 @@ import type { ExternalIssue, ExternalIssueList, Flamegraph, + InboxItem, + InboxItemEvent, Issue, IssueActivityList, IssueAlertRule, @@ -333,6 +338,73 @@ type RequestOptions = { allowStatuses?: number[]; }; +/** + * Inbox list filters, as `InboxFilterSerializer` in + * `src/sentry/inbox/filters.py` accepts them. Omitted filters match all items. + */ +export type InboxFilters = { + subjectTypes?: readonly string[]; + /** Requires exactly one subject type. */ + subjectId?: string; + eventTypes?: readonly string[]; + recipients?: readonly ("user" | "team")[]; + isRead?: boolean; +}; + +function inboxFilterSearchParams(filters: InboxFilters): URLSearchParams { + const search = new URLSearchParams(); + for (const subjectType of filters.subjectTypes ?? []) { + search.append("subject_type", subjectType); + } + if (filters.subjectId !== undefined) { + search.set("subject_id", filters.subjectId); + } + for (const eventType of filters.eventTypes ?? []) { + search.append("event_type", eventType); + } + for (const recipient of filters.recipients ?? []) { + search.append("recipient", recipient); + } + if (filters.isRead !== undefined) { + search.set("is_read", String(filters.isRead)); + } + return search; +} + +/** + * Which items an inbox mutation changes: these item IDs, or `"all"` for every + * active item. + */ +export type InboxSelection = readonly string[] | "all"; + +/** + * The inbox mutation path for a selection. Sentry applies a PUT or DELETE + * without an `id` filter to every item, so only an explicit `"all"` sends one; + * an empty ID list is refused before any request is sent. + */ +function inboxMutationPath( + organizationSlug: string, + selection: InboxSelection, +): string { + const path = apiPath`/organizations/${organizationSlug}/inbox/`; + if (selection === "all") { + return path; + } + if (selection.length === 0) { + throw new UserInputError("Select at least one inbox item ID."); + } + const search = new URLSearchParams(); + for (const itemId of selection) { + if (!/^\d+$/.test(itemId)) { + throw new UserInputError( + `Inbox item ID must be numeric, got ${JSON.stringify(itemId)}.`, + ); + } + search.append("id", itemId); + } + return `${path}?${search}`; +} + /** * Caps for automatic retries. Which statuses and methods are retried is the * shared rule in `@sentry/api/client`. @@ -4721,6 +4793,118 @@ export class SentryApiService { return DroppedEventsResponseSchema.parse(body); } + /** + * Lists the authenticated user's active Inbox items, newest + * activity first. Requires a user token and the organization's + * `organizations:universal-inbox` feature; otherwise Sentry returns 404. + */ + async listInboxItems( + { + organizationSlug, + filters = {}, + cursor, + limit, + }: { + organizationSlug: string; + filters?: InboxFilters; + cursor?: string | null; + limit?: number; + }, + opts?: RequestOptions, + ): Promise<{ items: InboxItem[]; nextCursor: string | null }> { + const search = inboxFilterSearchParams(filters); + if (limit !== undefined) search.set("per_page", String(limit)); + if (cursor) search.set("cursor", cursor); + const response = await this.request( + `${apiPath`/organizations/${organizationSlug}/inbox/`}?${search}`, + undefined, + opts, + ); + return { + items: InboxItemListSchema.parse(await readJsonResponse(response)), + nextCursor: nextPageCursor(response), + }; + } + + /** + * Lists one active inbox item's events, newest first. Reading does not + * change the item's read state. + */ + async listInboxItemEvents( + { + organizationSlug, + itemId, + cursor, + limit, + }: { + organizationSlug: string; + itemId: string; + cursor?: string | null; + limit?: number; + }, + opts?: RequestOptions, + ): Promise<{ events: InboxItemEvent[]; nextCursor: string | null }> { + const search = new URLSearchParams(); + if (limit !== undefined) search.set("per_page", String(limit)); + if (cursor) search.set("cursor", cursor); + const path = apiPath`/organizations/${organizationSlug}/inbox/${itemId}/events/`; + const query = search.toString(); + const response = await this.request( + query ? `${path}?${query}` : path, + undefined, + opts, + ); + return { + events: InboxItemEventListSchema.parse(await readJsonResponse(response)), + nextCursor: nextPageCursor(response), + }; + } + + /** + * Sets read state for the selected active inbox items. Returns how many + * items matched, including items already in the requested state. + */ + async updateInboxItems( + { + organizationSlug, + selection, + body, + }: { + organizationSlug: string; + selection: InboxSelection; + body: { isRead: boolean }; + }, + opts?: RequestOptions, + ): Promise<{ updatedCount: number }> { + const response = await this.requestJSON( + inboxMutationPath(organizationSlug, selection), + { method: "PUT", body: JSON.stringify(body) }, + opts, + ); + return InboxUpdateResponseSchema.parse(response); + } + + /** + * Removes the selected active inbox items at once. Sentry deletes them one + * hour later. + */ + async removeInboxItems( + { + organizationSlug, + selection, + }: { + organizationSlug: string; + selection: InboxSelection; + }, + opts?: RequestOptions, + ): Promise { + await this.request( + inboxMutationPath(organizationSlug, selection), + { method: "DELETE" }, + opts, + ); + } + // POST https://us.sentry.io/api/0/issues/5485083130/autofix/ async startAutofix( { diff --git a/packages/mcp-core/src/api-client/schema.ts b/packages/mcp-core/src/api-client/schema.ts index ebb4c32d7..ea007cb0d 100644 --- a/packages/mcp-core/src/api-client/schema.ts +++ b/packages/mcp-core/src/api-client/schema.ts @@ -2666,3 +2666,66 @@ export const DroppedEventsResponseSchema = z acceptedEvents: z.array(DroppedEventsBucketSchema), }) .passthrough(); + +/** + * Who caused a Inbox event: a user, or Sentry itself (`system`, + * with a null ID). See `src/sentry/inbox/response_types.py`. + */ +export const InboxActorSchema = z + .object({ + type: z.string(), + id: z.string().nullable(), + name: z.string(), + }) + .passthrough(); + +/** One event in a Inbox item's history. */ +export const InboxItemEventSchema = z + .object({ + id: z.string(), + type: z.string(), + actor: InboxActorSchema, + // Event-specific keys, camelCase, with IDs as strings. + data: z.record(z.string(), z.unknown()), + summary: z.string(), + isUnread: z.boolean(), + dateAdded: z.string(), + }) + .passthrough(); + +export const InboxItemEventListSchema = z.array(InboxItemEventSchema); + +/** + * One item in the authenticated user's personal Inbox, grouping the + * events for one subject (an issue or a Seer investigation notebook). + */ +export const InboxItemSchema = z + .object({ + id: z.string(), + subjectType: z.string(), + subjectId: z.string(), + // Null when the subject is no longer available. + title: z.string().nullable(), + // The latest event's URL, falling back to the subject's inbox URL. + // Optional until every Sentry deploy returns it (getsentry/sentry#131406). + url: z.string().optional(), + // The latest event's summary. + subtitle: z.string(), + eventTypes: z.array(z.string()), + eventCount: z.number(), + unreadEventCount: z.number(), + latestEvent: InboxItemEventSchema, + isUnread: z.boolean(), + lastActivityAt: z.string(), + lastReadAt: z.string().nullable(), + }) + .passthrough(); + +export const InboxItemListSchema = z.array(InboxItemSchema); + +/** Items matching a bulk inbox update, including items already in that state. */ +export const InboxUpdateResponseSchema = z + .object({ + updatedCount: z.number(), + }) + .passthrough(); diff --git a/packages/mcp-core/src/api-client/types.ts b/packages/mcp-core/src/api-client/types.ts index 7a901f8b1..ac1c13707 100644 --- a/packages/mcp-core/src/api-client/types.ts +++ b/packages/mcp-core/src/api-client/types.ts @@ -81,6 +81,8 @@ import type { FlamegraphProfileSchema, FlamegraphSchema, GenericEventSchema, + InboxItemEventSchema, + InboxItemSchema, IssueActivityListResponseSchema, IssueActivitySchema, IssueAlertRuleListSchema, @@ -159,6 +161,8 @@ export type AlertActionOption = z.infer; export type AlertConditionOption = z.infer; export type AlertRuleProjectScope = z.infer; export type Detector = z.infer; +export type InboxItem = z.infer; +export type InboxItemEvent = z.infer; export type MetricMonitorUpdate = { name?: string; description?: string | null; diff --git a/packages/mcp-core/src/tools/catalog/get-inbox.test.ts b/packages/mcp-core/src/tools/catalog/get-inbox.test.ts new file mode 100644 index 000000000..a485bbbf5 --- /dev/null +++ b/packages/mcp-core/src/tools/catalog/get-inbox.test.ts @@ -0,0 +1,444 @@ +import { mswServer } from "@sentry/mcp-server-mocks"; +import { HttpResponse, http } from "msw"; +import { describe, expect, it } from "vitest"; +import { + ApiNotFoundError, + ApiPermissionError, + ApiValidationError, +} from "../../api-client"; +import { UserInputError } from "../../errors"; +import { + assertStructuredOnlyResult, + getStructuredContent, +} from "../../test-utils/structured-content"; +import getInbox, { getInboxOutputSchema } from "./get-inbox"; + +const INBOX_URL = + "https://sentry.io/api/0/organizations/sentry-mcp-evals/inbox/"; + +const context = { + constraints: { organizationSlug: null, projectSlug: null }, + accessToken: "access-token", + userId: "1", +}; + +const baseParams = { + organizationSlug: "sentry-mcp-evals", + regionUrl: null, + itemId: null, + isRead: null, + subjectType: null, + subjectId: null, + eventTypes: null, + recipient: null, + cursor: null, + limit: 25, +}; + +// Shapes follow InboxItemSerializer and InboxItemEventSerializer in +// src/sentry/inbox/serializers.py. +const mentionEvent = { + id: "9001", + type: "issue.user_mentioned", + actor: { + type: "user", + id: "42", + name: "Jane Doe", + avatar: { avatarType: "letter_avatar", avatarUuid: null, avatarUrl: null }, + }, + data: { commentId: "555" }, + summary: "Mentioned you in a comment", + isUnread: true, + dateAdded: "2026-11-15T10:00:00.000000Z", +}; + +const assignmentEvent = { + id: "9000", + type: "issue.user_assigned", + actor: { type: "user", id: "42", name: "Jane Doe", avatar: null }, + data: { assignmentSource: null }, + summary: "Assigned to you", + isUnread: false, + dateAdded: "2026-11-14T09:00:00.000000Z", +}; + +const completedEvent = { + id: "9100", + type: "notebook.completed", + actor: { type: "system", id: null, name: "Sentry", avatar: null }, + data: {}, + summary: "Investigation completed", + isUnread: false, + dateAdded: "2026-11-13T08:00:00.000000Z", +}; + +const issueItem = { + id: "101", + subjectType: "issue", + subjectId: "6507376925", + title: "TypeError: Cannot read properties of undefined", + url: "https://sentry-mcp-evals.sentry.io/inbox/issue/6507376925/", + subtitle: "Mentioned you in a comment", + eventTypes: ["issue.user_assigned", "issue.user_mentioned"], + eventCount: 2, + unreadEventCount: 1, + latestEvent: mentionEvent, + isUnread: true, + lastActivityAt: "2026-11-15T10:00:00.000000Z", + lastReadAt: "2026-11-14T12:00:00.000000Z", +}; + +const notebookItem = { + id: "102", + subjectType: "notebook", + subjectId: "77", + title: null, + url: "https://sentry-mcp-evals.sentry.io/inbox/notebook/77/", + subtitle: "Investigation completed", + eventTypes: ["notebook.completed"], + eventCount: 1, + unreadEventCount: 0, + latestEvent: completedEvent, + isUnread: false, + lastActivityAt: "2026-11-13T08:00:00.000000Z", + lastReadAt: "2026-11-13T09:00:00.000000Z", +}; + +function parse(result: unknown) { + assertStructuredOnlyResult(result); + const content = getStructuredContent(result); + return getInboxOutputSchema.parse(content); +} + +describe("get_inbox", () => { + it("lists inbox items with summaries, read state, and URLs", async () => { + mswServer.use( + http.get(INBOX_URL, () => + HttpResponse.json([issueItem, notebookItem], { + headers: { + Link: `<${INBOX_URL}?cursor=1731664800000000_102:0:0>; rel="next"; results="true"; cursor="1731664800000000_102:0:0"`, + }, + }), + ), + ); + + const result = await getInbox.handler(baseParams, context); + + expect(parse(result)).toMatchInlineSnapshot(` + { + "items": [ + { + "eventCount": 2, + "eventTypes": [ + "issue.user_assigned", + "issue.user_mentioned", + ], + "id": "101", + "isUnread": true, + "lastActivityAt": "2026-11-15T10:00:00.000000Z", + "lastReadAt": "2026-11-14T12:00:00.000000Z", + "latestEvent": { + "actor": { + "id": "42", + "name": "Jane Doe", + "type": "user", + }, + "data": { + "commentId": "555", + }, + "dateAdded": "2026-11-15T10:00:00.000000Z", + "id": "9001", + "isUnread": true, + "summary": "Mentioned you in a comment", + "type": "issue.user_mentioned", + }, + "subjectId": "6507376925", + "subjectType": "issue", + "subtitle": "Mentioned you in a comment", + "title": "TypeError: Cannot read properties of undefined", + "unreadEventCount": 1, + "url": "https://sentry-mcp-evals.sentry.io/inbox/issue/6507376925/", + }, + { + "eventCount": 1, + "eventTypes": [ + "notebook.completed", + ], + "id": "102", + "isUnread": false, + "lastActivityAt": "2026-11-13T08:00:00.000000Z", + "lastReadAt": "2026-11-13T09:00:00.000000Z", + "latestEvent": { + "actor": { + "id": null, + "name": "Sentry", + "type": "system", + }, + "data": {}, + "dateAdded": "2026-11-13T08:00:00.000000Z", + "id": "9100", + "isUnread": false, + "summary": "Investigation completed", + "type": "notebook.completed", + }, + "subjectId": "77", + "subjectType": "notebook", + "subtitle": "Investigation completed", + "title": null, + "unreadEventCount": 0, + "url": "https://sentry-mcp-evals.sentry.io/inbox/notebook/77/", + }, + ], + "nextCursor": "1731664800000000_102:0:0", + } + `); + }); + + it("returns a null URL when Sentry does not return one", async () => { + // Sentry deploys before getsentry/sentry#131406 have no item URL. + const { url: _url, ...itemWithoutUrl } = issueItem; + mswServer.use( + http.get(INBOX_URL, () => HttpResponse.json([itemWithoutUrl])), + ); + + const result = await getInbox.handler(baseParams, context); + expect(parse(result).items?.[0]?.url).toBeNull(); + }); + + it("forwards filters, the cursor, and the page size", async () => { + let captured: URLSearchParams | undefined; + mswServer.use( + http.get(INBOX_URL, ({ request }) => { + captured = new URL(request.url).searchParams; + return HttpResponse.json([]); + }), + ); + + const result = await getInbox.handler( + { + ...baseParams, + isRead: false, + subjectType: "issue", + subjectId: "6507376925", + eventTypes: ["issue.user_mentioned", "issue.team_mentioned"], + recipient: "team", + cursor: "1731664800000000_102:0:0", + limit: 50, + }, + context, + ); + + expect(captured && [...captured.entries()]).toEqual([ + ["subject_type", "issue"], + ["subject_id", "6507376925"], + ["event_type", "issue.user_mentioned"], + ["event_type", "issue.team_mentioned"], + ["recipient", "team"], + ["is_read", "false"], + ["per_page", "50"], + ["cursor", "1731664800000000_102:0:0"], + ]); + expect(parse(result)).toEqual({ items: [], nextCursor: null }); + }); + + it("sends no filters when none are given", async () => { + let captured: URLSearchParams | undefined; + mswServer.use( + http.get(INBOX_URL, ({ request }) => { + captured = new URL(request.url).searchParams; + return HttpResponse.json([]); + }), + ); + + const result = await getInbox.handler(baseParams, context); + + expect(captured && [...captured.entries()]).toEqual([["per_page", "25"]]); + expect(parse(result)).toEqual({ items: [], nextCursor: null }); + }); + + it("returns no next cursor on the last page", async () => { + mswServer.use( + http.get(INBOX_URL, () => + HttpResponse.json([issueItem], { + headers: { + Link: `<${INBOX_URL}?cursor=1731664800000000_101:0:0>; rel="next"; results="false"; cursor="1731664800000000_101:0:0"`, + }, + }), + ), + ); + + const result = await getInbox.handler(baseParams, context); + expect(parse(result).nextCursor).toBeNull(); + }); + + it("returns one item's events without changing its read state", async () => { + const requests: string[] = []; + mswServer.use( + http.all( + /\/api\/0\/organizations\/sentry-mcp-evals\/inbox\//, + ({ request }) => { + requests.push(`${request.method} ${new URL(request.url).pathname}`); + const url = new URL(request.url); + expect(url.searchParams.get("cursor")).toBe( + "1731579600000000_9000:0:0", + ); + expect(url.searchParams.get("per_page")).toBe("10"); + return HttpResponse.json([mentionEvent, assignmentEvent], { + headers: { + Link: `<${url.origin}${url.pathname}?cursor=1731578400000000_8999:0:0>; rel="next"; results="true"; cursor="1731578400000000_8999:0:0"`, + }, + }); + }, + ), + ); + + const result = await getInbox.handler( + { + ...baseParams, + itemId: "101", + cursor: "1731579600000000_9000:0:0", + limit: 10, + }, + context, + ); + + expect(requests).toEqual([ + "GET /api/0/organizations/sentry-mcp-evals/inbox/101/events/", + ]); + expect(parse(result)).toMatchInlineSnapshot(` + { + "events": [ + { + "actor": { + "id": "42", + "name": "Jane Doe", + "type": "user", + }, + "data": { + "commentId": "555", + }, + "dateAdded": "2026-11-15T10:00:00.000000Z", + "id": "9001", + "isUnread": true, + "summary": "Mentioned you in a comment", + "type": "issue.user_mentioned", + }, + { + "actor": { + "id": "42", + "name": "Jane Doe", + "type": "user", + }, + "data": { + "assignmentSource": null, + }, + "dateAdded": "2026-11-14T09:00:00.000000Z", + "id": "9000", + "isUnread": false, + "summary": "Assigned to you", + "type": "issue.user_assigned", + }, + ], + "itemId": "101", + "nextCursor": "1731578400000000_8999:0:0", + } + `); + }); + + it("rejects list filters combined with an item ID before calling Sentry", async () => { + await expect( + getInbox.handler( + { ...baseParams, itemId: "101", isRead: false, recipient: "user" }, + context, + ), + ).rejects.toThrow( + new UserInputError( + "Filters apply only to the item list, not to one item's events. Remove isRead and recipient, or remove itemId to list items.", + ), + ); + }); + + it("requires a subject type with a subject ID", async () => { + await expect( + getInbox.handler({ ...baseParams, subjectId: "123" }, context), + ).rejects.toThrow(UserInputError); + }); + + it("rejects a non-numeric item ID in the schema", () => { + expect(getInbox.inputSchema.itemId.safeParse("PROJ-1").success).toBe(false); + expect(getInbox.inputSchema.itemId.safeParse("101").success).toBe(true); + }); + + it("explains a 404 as Inbox not being enabled", async () => { + mswServer.use( + http.get(INBOX_URL, () => + HttpResponse.json( + { detail: "The requested resource does not exist" }, + { status: 404 }, + ), + ), + ); + + const error = await getInbox + .handler(baseParams, context) + .catch((caught: unknown) => caught); + expect(error).toBeInstanceOf(ApiNotFoundError); + expect((error as Error).message).toBe( + "Inbox is not enabled for organization 'sentry-mcp-evals', or you cannot access it.", + ); + }); + + it("explains a 404 for an item that is not in your inbox", async () => { + mswServer.use( + http.get(`${INBOX_URL}999/events/`, () => + HttpResponse.json({ detail: "Not found." }, { status: 404 }), + ), + ); + + await expect( + getInbox.handler({ ...baseParams, itemId: "999" }, context), + ).rejects.toThrow(/Inbox item 999 is not an active item in your Inbox/); + }); + + it("forwards types Sentry has not registered and surfaces its rejection", async () => { + let captured: URLSearchParams | undefined; + mswServer.use( + http.get(INBOX_URL, ({ request }) => { + captured = new URL(request.url).searchParams; + // InboxFilterSerializer's response for an unregistered type. + return HttpResponse.json( + { detail: { non_field_errors: ["Unknown event type."] } }, + { status: 400 }, + ); + }), + ); + + await expect( + getInbox.handler( + { ...baseParams, eventTypes: ["issue.not_a_type"] }, + context, + ), + ).rejects.toBeInstanceOf(ApiValidationError); + expect(captured?.getAll("event_type")).toEqual(["issue.not_a_type"]); + }); + + it("surfaces a token without a user as a permission error", async () => { + mswServer.use( + http.get(INBOX_URL, () => + HttpResponse.json( + { + detail: { + code: "user-required", + message: "This action requires a user.", + }, + }, + { status: 403 }, + ), + ), + ); + + await expect(getInbox.handler(baseParams, context)).rejects.toBeInstanceOf( + ApiPermissionError, + ); + }); +}); diff --git a/packages/mcp-core/src/tools/catalog/get-inbox.ts b/packages/mcp-core/src/tools/catalog/get-inbox.ts new file mode 100644 index 000000000..eb9024a74 --- /dev/null +++ b/packages/mcp-core/src/tools/catalog/get-inbox.ts @@ -0,0 +1,167 @@ +import { z } from "zod"; +import { UserInputError } from "../../errors"; +import { apiServiceFromContext } from "../../internal/tool-helpers/api"; +import { defineTool } from "../../internal/tool-helpers/define"; +import { structuredResult } from "../../internal/tool-helpers/results"; +import { + ParamCursor, + ParamOrganizationSlug, + ParamRegionUrl, +} from "../../schema"; +import { setTargetTagsAndAttributes } from "../../telem/scope"; +import type { ServerContext } from "../../types"; +import { + formatInboxEvent, + formatInboxItem, + inboxEventOutputSchema, + inboxItemOutputSchema, + ParamInboxItemId, + withInboxNotFoundHint, +} from "../support/inbox"; + +export const getInboxOutputSchema = z.object({ + items: z.array(inboxItemOutputSchema).optional(), + itemId: z.string().optional(), + events: z.array(inboxEventOutputSchema).optional(), + nextCursor: z.string().nullable(), +}); + +export default defineTool({ + name: "get_inbox", + title: "Get Inbox", + // Inbox is behind the organizations:universal-inbox feature flag. + experimental: true, + includeInSkillDefinitions: false, + skills: ["inspect"], + requiredScopes: ["org:read"], + description: + "List your Sentry Inbox: issue assignments, mentions, pull requests ready for review, and Seer investigation updates, newest activity first, with read state and summaries. Can also return one inbox item's event history. Reading does not mark items read; triage them with update_inbox_items.", + inputSchema: { + organizationSlug: ParamOrganizationSlug, + regionUrl: ParamRegionUrl.nullable().default(null), + itemId: ParamInboxItemId.describe( + "Inbox item ID from a previous result. Returns that item's events, newest first, instead of the item list; do not combine with filters.", + ) + .nullable() + .default(null), + isRead: z + .boolean() + .describe("false for unread items only, true for read only.") + .nullable() + .default(null), + // Subject and event types are open registries in Sentry + // (src/sentry/inbox/registry.py), so they stay strings; Sentry rejects + // unknown values with a 400. + subjectType: z + .string() + .trim() + .min(1) + .describe( + "Only items about this kind of subject, such as issue or notebook (a Seer investigation).", + ) + .nullable() + .default(null), + subjectId: z + .string() + .trim() + .min(1) + .describe("Numeric issue or investigation ID; requires subjectType.") + .nullable() + .default(null), + eventTypes: z + .array(z.string().trim().min(1)) + .min(1) + .describe( + "Only items with at least one event of these types, such as issue.user_assigned, issue.user_mentioned, issue.pr_ready_for_review, or notebook.completed.", + ) + .nullable() + .default(null), + recipient: z + .enum(["user", "team"]) + .describe( + "Only items with an event addressed directly to you (user) or to one of your teams (team).", + ) + .nullable() + .default(null), + cursor: ParamCursor.trim().nullable().default(null), + limit: z + .number() + .int() + .min(1) + .max(100) + .describe("Maximum items or events to return.") + .default(25), + }, + annotations: { + readOnlyHint: true, + destructiveHint: false, + openWorldHint: true, + }, + outputSchema: getInboxOutputSchema, + async handler(params, context: ServerContext) { + const apiService = apiServiceFromContext(context, { + regionUrl: params.regionUrl ?? undefined, + }); + const organizationSlug = params.organizationSlug; + setTargetTagsAndAttributes({ organizationSlug }); + + if (params.itemId) { + const filters = [ + params.isRead !== null && "isRead", + params.subjectType && "subjectType", + params.subjectId && "subjectId", + params.eventTypes && "eventTypes", + params.recipient && "recipient", + ].filter(Boolean); + if (filters.length > 0) { + throw new UserInputError( + `Filters apply only to the item list, not to one item's events. Remove ${filters.join(" and ")}, or remove itemId to list items.`, + ); + } + + const itemId = params.itemId; + const { events, nextCursor } = await withInboxNotFoundHint( + { organizationSlug, itemId }, + () => + apiService.listInboxItemEvents({ + organizationSlug, + itemId, + cursor: params.cursor, + limit: params.limit, + }), + ); + return structuredResult({ + itemId, + events: events.map(formatInboxEvent), + nextCursor, + }); + } + + if (params.subjectId && !params.subjectType) { + throw new UserInputError( + "subjectId requires subjectType: `issue` for an issue ID, or `notebook` for a Seer investigation ID.", + ); + } + + const { items, nextCursor } = await withInboxNotFoundHint( + { organizationSlug }, + () => + apiService.listInboxItems({ + organizationSlug, + filters: { + subjectTypes: params.subjectType ? [params.subjectType] : undefined, + subjectId: params.subjectId ?? undefined, + eventTypes: params.eventTypes ?? undefined, + recipients: params.recipient ? [params.recipient] : undefined, + isRead: params.isRead ?? undefined, + }, + cursor: params.cursor, + limit: params.limit, + }), + ); + return structuredResult({ + items: items.map(formatInboxItem), + nextCursor, + }); + }, +}); diff --git a/packages/mcp-core/src/tools/catalog/index.ts b/packages/mcp-core/src/tools/catalog/index.ts index 5af899cc0..941214f75 100644 --- a/packages/mcp-core/src/tools/catalog/index.ts +++ b/packages/mcp-core/src/tools/catalog/index.ts @@ -40,6 +40,8 @@ import getEventAttachment from "./get-event-attachment"; import updateIssue from "./update-issue"; import linkIssue from "./link-issue"; import unlinkIssue from "./unlink-issue"; +import getInbox from "./get-inbox"; +import updateInboxItems from "./update-inbox-items"; import searchEvents from "./search-events"; import searchErrors from "./search-errors"; import searchLogs from "./search-logs"; @@ -167,6 +169,8 @@ const catalogTools = withFreshReadInputs({ update_issue: updateIssue, link_issue: linkIssue, unlink_issue: unlinkIssue, + get_inbox: getInbox, + update_inbox_items: updateInboxItems, search_attributes: searchAttributes, search_errors: searchErrors, search_logs: searchLogs, diff --git a/packages/mcp-core/src/tools/catalog/update-inbox-items.test.ts b/packages/mcp-core/src/tools/catalog/update-inbox-items.test.ts new file mode 100644 index 000000000..b4f5b84fd --- /dev/null +++ b/packages/mcp-core/src/tools/catalog/update-inbox-items.test.ts @@ -0,0 +1,271 @@ +import { mswServer } from "@sentry/mcp-server-mocks"; +import { HttpResponse, http } from "msw"; +import { describe, expect, it } from "vitest"; +import { ApiNotFoundError, ApiPermissionError } from "../../api-client"; +import { UserInputError } from "../../errors"; +import { + assertStructuredOnlyResult, + getStructuredContent, +} from "../../test-utils/structured-content"; +import updateInboxItems, { + updateInboxItemsOutputSchema, +} from "./update-inbox-items"; + +const INBOX_URL = + "https://sentry.io/api/0/organizations/sentry-mcp-evals/inbox/"; + +const context = { + constraints: { organizationSlug: null, projectSlug: null }, + accessToken: "access-token", + userId: "1", +}; + +type CapturedRequest = { + method: string; + path: string; + ids: string[]; + otherParams: string[]; + body: unknown; +}; + +/** Records every inbox request; answers PUT with a count and DELETE with 204. */ +function captureInboxRequests(updatedCount = 2): CapturedRequest[] { + const requests: CapturedRequest[] = []; + mswServer.use( + http.all( + /\/api\/0\/organizations\/sentry-mcp-evals\/inbox\//, + async ({ request }) => { + const url = new URL(request.url); + const text = await request.text(); + requests.push({ + method: request.method, + path: url.pathname, + ids: url.searchParams.getAll("id"), + otherParams: [...url.searchParams.keys()].filter( + (key) => key !== "id", + ), + body: text ? JSON.parse(text) : null, + }); + if (request.method === "DELETE") { + return new HttpResponse(null, { status: 204 }); + } + return HttpResponse.json({ updatedCount }); + }, + ), + ); + return requests; +} + +function parse(result: unknown) { + assertStructuredOnlyResult(result); + const content = getStructuredContent(result); + expect(updateInboxItemsOutputSchema.parse(content)).toEqual(content); + return content; +} + +describe("update_inbox_items", () => { + it("marks the selected items read", async () => { + const requests = captureInboxRequests(); + + const result = await updateInboxItems.handler( + { + organizationSlug: "sentry-mcp-evals", + regionUrl: null, + all: false, + itemIds: ["101", "102"], + action: "mark_read", + }, + context, + ); + + expect(requests).toEqual([ + { + method: "PUT", + path: "/api/0/organizations/sentry-mcp-evals/inbox/", + ids: ["101", "102"], + otherParams: [], + body: { isRead: true }, + }, + ]); + expect(parse(result)).toMatchInlineSnapshot(` + { + "action": "mark_read", + "matchedCount": 2, + "selection": [ + "101", + "102", + ], + } + `); + }); + + it("marks the selected items unread", async () => { + const requests = captureInboxRequests(1); + + const result = await updateInboxItems.handler( + { + organizationSlug: "sentry-mcp-evals", + regionUrl: null, + all: false, + itemIds: ["101"], + action: "mark_unread", + }, + context, + ); + + expect(requests).toEqual([ + { + method: "PUT", + path: "/api/0/organizations/sentry-mcp-evals/inbox/", + ids: ["101"], + otherParams: [], + body: { isRead: false }, + }, + ]); + expect(parse(result)).toEqual({ + action: "mark_unread", + selection: ["101"], + matchedCount: 1, + }); + }); + + it("removes the selected items with a DELETE scoped to their IDs", async () => { + const requests = captureInboxRequests(); + + const result = await updateInboxItems.handler( + { + organizationSlug: "sentry-mcp-evals", + regionUrl: null, + all: false, + itemIds: ["101", "101", "103"], + action: "remove", + }, + context, + ); + + expect(requests).toEqual([ + { + method: "DELETE", + path: "/api/0/organizations/sentry-mcp-evals/inbox/", + ids: ["101", "103"], + otherParams: [], + body: null, + }, + ]); + expect(parse(result)).toEqual({ + action: "remove", + selection: ["101", "103"], + }); + }); + + it.each([ + ["mark_read", "PUT", { isRead: true }], + ["remove", "DELETE", null], + ] as const)( + "applies %s to every item only with all: true", + async (action, method, body) => { + const requests = captureInboxRequests(7); + + const result = await updateInboxItems.handler( + { + organizationSlug: "sentry-mcp-evals", + regionUrl: null, + all: true, + itemIds: null, + action, + }, + context, + ); + + expect(requests).toEqual([ + { + method, + path: "/api/0/organizations/sentry-mcp-evals/inbox/", + ids: [], + otherParams: [], + body, + }, + ]); + expect(parse(result)).toMatchObject({ action, selection: "all" }); + }, + ); + + it.each([ + ["no selection", { all: false, itemIds: null }], + ["an empty selection", { all: false, itemIds: [] }], + ["item IDs with all", { all: true, itemIds: ["101"] }], + ])("rejects %s before sending a mutation", async (_case, selection) => { + const requests = captureInboxRequests(); + + await expect( + updateInboxItems.handler( + { + organizationSlug: "sentry-mcp-evals", + regionUrl: null, + ...selection, + action: "remove", + }, + context, + ), + ).rejects.toThrow(UserInputError); + expect(requests).toEqual([]); + }); + + it("rejects non-numeric item IDs in the schema", () => { + expect( + updateInboxItems.inputSchema.itemIds.safeParse(["101", "all"]).success, + ).toBe(false); + }); + + it("explains a 404 as Inbox not being enabled", async () => { + mswServer.use( + http.put(INBOX_URL, () => + HttpResponse.json( + { detail: "The requested resource does not exist" }, + { status: 404 }, + ), + ), + ); + + const error = await updateInboxItems + .handler( + { + organizationSlug: "sentry-mcp-evals", + regionUrl: null, + all: false, + itemIds: ["101"], + action: "mark_read", + }, + context, + ) + .catch((caught: unknown) => caught); + expect(error).toBeInstanceOf(ApiNotFoundError); + expect((error as Error).message).toBe( + "Inbox is not enabled for organization 'sentry-mcp-evals', or you cannot access it.", + ); + }); + + it("surfaces a permission failure", async () => { + mswServer.use( + http.delete(INBOX_URL, () => + HttpResponse.json( + { detail: "You do not have permission to perform this action." }, + { status: 403 }, + ), + ), + ); + + await expect( + updateInboxItems.handler( + { + organizationSlug: "sentry-mcp-evals", + regionUrl: null, + all: false, + itemIds: ["101"], + action: "remove", + }, + context, + ), + ).rejects.toBeInstanceOf(ApiPermissionError); + }); +}); diff --git a/packages/mcp-core/src/tools/catalog/update-inbox-items.ts b/packages/mcp-core/src/tools/catalog/update-inbox-items.ts new file mode 100644 index 000000000..fdfae24c9 --- /dev/null +++ b/packages/mcp-core/src/tools/catalog/update-inbox-items.ts @@ -0,0 +1,116 @@ +import { z } from "zod"; +import type { InboxSelection, SentryApiService } from "../../api-client"; +import { UserInputError } from "../../errors"; +import { apiServiceFromContext } from "../../internal/tool-helpers/api"; +import { defineTool } from "../../internal/tool-helpers/define"; +import { structuredResult } from "../../internal/tool-helpers/results"; +import { ParamOrganizationSlug, ParamRegionUrl } from "../../schema"; +import { setTargetTagsAndAttributes } from "../../telem/scope"; +import type { ServerContext } from "../../types"; +import { ParamInboxItemId, withInboxNotFoundHint } from "../support/inbox"; + +const INBOX_ACTIONS = ["mark_read", "mark_unread", "remove"] as const; + +type InboxAction = (typeof INBOX_ACTIONS)[number]; + +export const updateInboxItemsOutputSchema = z.object({ + action: z.enum(INBOX_ACTIONS), + // "all" when every active item was selected. + selection: z.union([z.literal("all"), z.array(z.string())]), + // Selected items that matched, including ones already in the requested + // state. Sentry does not report it for removals. + matchedCount: z.number().optional(), +}); + +async function applyInboxAction( + apiService: SentryApiService, + organizationSlug: string, + selection: InboxSelection, + action: InboxAction, +): Promise { + switch (action) { + case "mark_read": + case "mark_unread": { + const { updatedCount } = await apiService.updateInboxItems({ + organizationSlug, + selection, + body: { isRead: action === "mark_read" }, + }); + return updatedCount; + } + case "remove": + await apiService.removeInboxItems({ organizationSlug, selection }); + return undefined; + } +} + +export default defineTool({ + name: "update_inbox_items", + title: "Update Inbox Items", + // Inbox is behind the organizations:universal-inbox feature flag. + experimental: true, + includeInSkillDefinitions: false, + skills: ["triage"], + requiredScopes: ["org:read"], + description: + "Triage your Sentry Inbox: mark selected items, or every item, read or unread, or remove them. Changes only your personal inbox, never the underlying issues or Seer investigations. Removal hides an item at once, and Sentry deletes it after one hour.", + inputSchema: { + organizationSlug: ParamOrganizationSlug, + regionUrl: ParamRegionUrl.nullable().default(null), + itemIds: z + .array(ParamInboxItemId) + .min(1) + .max(100) + .describe("Inbox item IDs from get_inbox. Only these items change.") + .nullable() + .default(null), + all: z + .boolean() + .describe( + "true to change every item in your Inbox instead of itemIds. Set it only when the user asks for all items.", + ) + .default(false), + action: z + .enum(INBOX_ACTIONS) + .describe("Change to apply to the selected items."), + }, + annotations: { + readOnlyHint: false, + destructiveHint: true, + idempotentHint: true, + openWorldHint: true, + }, + outputSchema: updateInboxItemsOutputSchema, + async handler(params, context: ServerContext) { + // Sentry applies an inbox update with no item filter to every item, so + // changing everything takes an explicit `all`, never a missing selection. + const itemIds = [...new Set(params.itemIds ?? [])]; + if (params.all && itemIds.length > 0) { + throw new UserInputError("Pass either itemIds or all: true, not both."); + } + // The error does not suggest `all`, so a mistaken call cannot be + // "fixed" by changing every item. + if (!params.all && itemIds.length === 0) { + throw new UserInputError( + "Select at least one inbox item ID. List items with get_inbox.", + ); + } + const selection = params.all ? ("all" as const) : itemIds; + + const apiService = apiServiceFromContext(context, { + regionUrl: params.regionUrl ?? undefined, + }); + const organizationSlug = params.organizationSlug; + setTargetTagsAndAttributes({ organizationSlug }); + + const matchedCount = await withInboxNotFoundHint({ organizationSlug }, () => + applyInboxAction(apiService, organizationSlug, selection, params.action), + ); + + return structuredResult({ + action: params.action, + selection, + ...(matchedCount === undefined ? {} : { matchedCount }), + }); + }, +}); diff --git a/packages/mcp-core/src/tools/support/inbox.ts b/packages/mcp-core/src/tools/support/inbox.ts new file mode 100644 index 000000000..b69c9dc35 --- /dev/null +++ b/packages/mcp-core/src/tools/support/inbox.ts @@ -0,0 +1,108 @@ +import { z } from "zod"; +import { + ApiNotFoundError, + type InboxItem, + type InboxItemEvent, +} from "../../api-client"; + +/** Inbox item IDs are numeric (`InboxFilterSerializer.id` is an IntegerField). */ +export const ParamInboxItemId = z + .string() + .trim() + .regex(/^\d+$/, "Inbox item IDs are numeric, such as `123`."); + +// Output mirrors the API response (src/sentry/inbox/response_types.py), with +// fields mapped explicitly so the passthrough API schema cannot leak. +const inboxActorSchema = z.object({ + type: z.string(), + id: z.string().nullable(), + name: z.string(), +}); + +export const inboxEventOutputSchema = z.object({ + id: z.string(), + type: z.string(), + actor: inboxActorSchema, + data: z.record(z.string(), z.unknown()), + summary: z.string(), + isUnread: z.boolean(), + dateAdded: z.string(), +}); + +export const inboxItemOutputSchema = z.object({ + id: z.string(), + subjectType: z.string(), + subjectId: z.string(), + title: z.string().nullable(), + url: z.string().nullable(), + subtitle: z.string(), + eventTypes: z.array(z.string()), + eventCount: z.number(), + unreadEventCount: z.number(), + latestEvent: inboxEventOutputSchema, + isUnread: z.boolean(), + lastActivityAt: z.string(), + lastReadAt: z.string().nullable(), +}); + +export function formatInboxEvent( + event: InboxItemEvent, +): z.output { + return { + id: event.id, + type: event.type, + actor: { + type: event.actor.type, + id: event.actor.id, + name: event.actor.name, + }, + data: event.data, + summary: event.summary, + isUnread: event.isUnread, + dateAdded: event.dateAdded, + }; +} + +export function formatInboxItem( + item: InboxItem, +): z.output { + return { + id: item.id, + subjectType: item.subjectType, + subjectId: item.subjectId, + title: item.title, + // Null on Sentry versions before getsentry/sentry#131406. + url: item.url ?? null, + subtitle: item.subtitle, + eventTypes: item.eventTypes, + eventCount: item.eventCount, + unreadEventCount: item.unreadEventCount, + latestEvent: formatInboxEvent(item.latestEvent), + isUnread: item.isUnread, + lastActivityAt: item.lastActivityAt, + lastReadAt: item.lastReadAt, + }; +} + +/** + * Sentry answers every inbox endpoint with 404 while the organization's + * `organizations:universal-inbox` feature is off, and the item events endpoint + * also answers 404 for an item that is not an active item in your inbox. + * Say so instead of the generic "verify the organization" hint. + */ +export async function withInboxNotFoundHint( + { organizationSlug, itemId }: { organizationSlug: string; itemId?: string }, + run: () => Promise, +): Promise { + try { + return await run(); + } catch (error) { + if (!(error instanceof ApiNotFoundError)) { + throw error; + } + const hint = itemId + ? `Inbox item ${itemId} is not an active item in your Inbox in organization '${organizationSlug}', or Inbox is not enabled for that organization. Removed items no longer appear; list current items with get_inbox.` + : `Inbox is not enabled for organization '${organizationSlug}', or you cannot access it.`; + throw new ApiNotFoundError(hint, error.detail, error.responseBody); + } +} diff --git a/plugins/sentry-mcp-experimental/agents/sentry-mcp.md b/plugins/sentry-mcp-experimental/agents/sentry-mcp.md index 76ac3faa9..1bc087ade 100644 --- a/plugins/sentry-mcp-experimental/agents/sentry-mcp.md +++ b/plugins/sentry-mcp-experimental/agents/sentry-mcp.md @@ -42,6 +42,7 @@ allowedTools: - get_doc - get_event_attachment - get_event_stacktrace + - get_inbox - get_issue_activity - get_issue_breadcrumbs - get_issue_details @@ -77,6 +78,7 @@ allowedTools: - unlink_issue - update_alert_rule - update_dsn + - update_inbox_items - update_issue - update_metric_monitor - update_project