Skip to content
51 changes: 51 additions & 0 deletions packages/mcp-core/src/api-client/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,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", () => {
Expand Down Expand Up @@ -2369,6 +2389,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" });
Expand Down
186 changes: 185 additions & 1 deletion packages/mcp-core/src/api-client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 { omitUndefined } from "../internal/type-guards";
import { logIssue, logWarn } from "../telem/logging";
Expand Down Expand Up @@ -146,6 +146,9 @@ import {
ExternalIssueListSchema,
ExternalIssueSchema,
FlamegraphSchema,
InboxItemEventListSchema,
InboxItemListSchema,
InboxUpdateResponseSchema,
IssueActivityListResponseSchema,
IssueAlertRuleListSchema,
IssueAlertRuleSchema,
Expand Down Expand Up @@ -226,6 +229,8 @@ import type {
ExternalIssue,
ExternalIssueList,
Flamegraph,
InboxItem,
InboxItemEvent,
Issue,
IssueActivityList,
IssueAlertRule,
Expand Down Expand Up @@ -338,6 +343,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[] | undefined;
/** Requires exactly one subject type. */
subjectId?: string | undefined;
eventTypes?: readonly string[] | undefined;
recipients?: readonly ("user" | "team")[] | undefined;
isRead?: boolean | undefined;
};

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`.
Expand Down Expand Up @@ -4841,6 +4913,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<void> {
await this.request(
inboxMutationPath(organizationSlug, selection),
{ method: "DELETE" },
opts,
);
}

// POST https://us.sentry.io/api/0/issues/5485083130/autofix/
async startAutofix(
{
Expand Down
80 changes: 80 additions & 0 deletions packages/mcp-core/src/api-client/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2738,3 +2738,83 @@ 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);

/**
* The issue or Seer investigation (notebook) an inbox item is about. Issue
* metadata carries the short ID and project; notebook metadata is empty.
*/
export const InboxSubjectSchema = z
.object({
id: z.string(),
type: z.string(),
title: z.string(),
metadata: z
.object({
shortId: z.string().optional(),
project: z
.object({ id: z.string(), slug: z.string() })
.passthrough()
.optional(),
})
.passthrough(),
})
.passthrough();

/**
* One item in the authenticated user's personal Inbox, grouping the events
* for one subject. Sentry leaves out items whose subject no longer exists.
*/
export const InboxItemSchema = z
.object({
id: z.string(),
subject: InboxSubjectSchema,
// The latest event's URL, such as a link to the activity on the issue.
url: z.string(),
// 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();
4 changes: 4 additions & 0 deletions packages/mcp-core/src/api-client/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ import type {
FlamegraphProfileSchema,
FlamegraphSchema,
GenericEventSchema,
InboxItemEventSchema,
InboxItemSchema,
IssueActivityListResponseSchema,
IssueActivitySchema,
IssueAlertRuleListSchema,
Expand Down Expand Up @@ -161,6 +163,8 @@ export type AlertActionOption = z.infer<typeof AlertActionOptionSchema>;
export type AlertConditionOption = z.infer<typeof AlertConditionOptionSchema>;
export type AlertRuleProjectScope = z.infer<typeof AlertRuleProjectScopeSchema>;
export type Detector = z.infer<typeof DetectorSchema>;
export type InboxItem = z.infer<typeof InboxItemSchema>;
export type InboxItemEvent = z.infer<typeof InboxItemEventSchema>;
export type MetricMonitorUpdate = {
name?: string;
description?: string | null | undefined;
Expand Down
Loading
Loading