Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/mcp-core/src/api-client/client-event.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ describe("getEventForIssue context validation", () => {
);

expect(log).toHaveBeenCalledTimes(1);
const output = String(log.mock.calls[0][0]);
const output = String(log.mock.calls[0]![0]);
const record = JSON.parse(output);
expect(record.message).toBe("Event failed schema validation: error");
expect(record.properties.contextType).toBe(contextType);
Expand Down
24 changes: 12 additions & 12 deletions packages/mcp-core/src/api-client/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1973,7 +1973,7 @@ describe("request headers", () => {
}).getAuthenticatedUser();

const [, requestInit] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock
.calls[0];
.calls[0]!;
expect(new Headers(requestInit.headers).get("User-Agent")).toBe(
"sentry-mcp/0.48.0-test (https://mcp.sentry.dev)",
);
Expand Down Expand Up @@ -2006,7 +2006,7 @@ describe("request headers", () => {
await apiService.getAuthenticatedUser();

const [, requestInit] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock
.calls[0];
.calls[0]!;
expect(new Headers(requestInit.headers).get("X-Sentry-MCP-Client-Id")).toBe(
"abc123",
);
Expand Down Expand Up @@ -2044,7 +2044,7 @@ describe("request headers", () => {
await apiService.getAuthenticatedUser();

const [, requestInit] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock
.calls[0];
.calls[0]!;
expect(
new Headers(requestInit.headers).get("X-Sentry-MCP-Client-Id"),
).toBeNull();
Expand Down Expand Up @@ -2940,7 +2940,7 @@ describe("API query builders", () => {
},
]);
expect(urls).toHaveLength(1);
const params = new URL(urls[0]).searchParams;
const params = new URL(urls[0]!).searchParams;
expect(params.get("itemType")).toBe("spans");
expect(params.get("project")).toBe("123");
expect(params.get("statsPeriod")).toBe("7d");
Expand Down Expand Up @@ -2978,7 +2978,7 @@ describe("API query builders", () => {
});

expect(urls).toHaveLength(1);
const params = new URL(urls[0]).searchParams;
const params = new URL(urls[0]!).searchParams;
expect(params.get("itemType")).toBe("spans");
expect(params.get("expand")).toBe("context");
});
Expand Down Expand Up @@ -3419,7 +3419,7 @@ describe("API query builders", () => {
expect.any(Object),
);
expect(repos).toHaveLength(1);
expect(repos[0].name).toBe("getsentry/sentry");
expect(repos[0]?.name).toBe("getsentry/sentry");
});

it("should paginate repos", async () => {
Expand Down Expand Up @@ -3469,8 +3469,8 @@ describe("API query builders", () => {
"getsentry/sentry-javascript",
]);
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(fetchMock.mock.calls[0][0]).toContain("per_page=100");
expect(fetchMock.mock.calls[1][0]).toContain("cursor=cursor-2");
expect(fetchMock.mock.calls[0]?.[0]).toContain("per_page=100");
expect(fetchMock.mock.calls[1]?.[0]).toContain("cursor=cursor-2");
});

it("should include query parameter when provided", async () => {
Expand Down Expand Up @@ -3547,8 +3547,8 @@ describe("API query builders", () => {
});

expect(repos).toHaveLength(1);
expect(repos[0].externalSlug).toBeNull();
expect(repos[0].externalId).toBeNull();
expect(repos[0]!.externalSlug).toBeNull();
expect(repos[0]!.externalId).toBeNull();
});
});

Expand Down Expand Up @@ -3614,7 +3614,7 @@ describe("API query builders", () => {
}),
);
expect(result.created).toBe(1);
expect(result.mappings[0].status).toBe("created");
expect(result.mappings[0]?.status).toBe("created");
});

it("should handle updated mappings response", async () => {
Expand Down Expand Up @@ -3647,7 +3647,7 @@ describe("API query builders", () => {
});

expect(result.updated).toBe(1);
expect(result.mappings[0].status).toBe("updated");
expect(result.mappings[0]?.status).toBe("updated");
});
});

Expand Down
16 changes: 9 additions & 7 deletions packages/mcp-core/src/api-client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1059,8 +1059,9 @@ export class SentryApiService {
if (isAggregate) {
urlParams.set("mode", "aggregate");
// For aggregate queries in Discover, set yAxis to the first aggregate function
if (aggregateFunctions && aggregateFunctions.length > 0) {
urlParams.set("yAxis", aggregateFunctions[0]);
const firstAggregate = aggregateFunctions?.[0];
if (firstAggregate !== undefined) {
urlParams.set("yAxis", firstAggregate);
}
} else {
urlParams.set("yAxis", "count()");
Expand Down Expand Up @@ -3561,7 +3562,7 @@ export class SentryApiService {
uri: string;
query?: string;
projectId?: string;
dependentData?: Record<string, string | number>;
dependentData?: Record<string, string | number | undefined>;
},
opts?: RequestOptions,
): Promise<SentryAppExternalRequestOptions> {
Expand Down Expand Up @@ -4003,7 +4004,7 @@ export class SentryApiService {
// the two share the same DB source but the download header reflects any
// server-side correction (getsentry/sentry#115977) applied at request time.
const contentType =
downloadResponse.headers.get("content-type")?.split(";")[0].trim() ||
downloadResponse.headers.get("content-type")?.split(";")[0]?.trim() ||
attachment.mimetype ||
"application/octet-stream";

Expand Down Expand Up @@ -5073,7 +5074,8 @@ export class SentryApiService {
ProfileChunkResponseSchema,
);
// Normalize the Sentry {chunk: ...} wrapper to the internal chunks array.
if (response.chunks.length === 0) {
const [chunk] = response.chunks;
if (chunk === undefined) {
throw new ApiNotFoundError(
`No profile chunk found for profiler_id ${params.profilerId}`,
undefined,
Expand All @@ -5082,10 +5084,10 @@ export class SentryApiService {
}

return {
...response.chunks[0],
...chunk,
// Sentry's frontend does the same query-param backfill for continuous
// profile chunks because profiling-service may omit profiler_id.
profiler_id: response.chunks[0].profiler_id ?? params.profilerId,
profiler_id: chunk.profiler_id ?? params.profilerId,
};
}

Expand Down
2 changes: 1 addition & 1 deletion packages/mcp-core/src/api-client/schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -711,7 +711,7 @@ describe("AutofixRunStateSchema", () => {

expect(state.autofix?.status).toBe("processing");
expect(state.autofix?.blocks).toHaveLength(1);
expect(state.autofix?.blocks[0].todos).toEqual([
expect(state.autofix?.blocks[0]?.todos).toEqual([
{ content: "Investigate failing request", status: "completed" },
{ content: "Draft fix plan", status: "in_progress" },
]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ function extractJsonCandidates(text: string): string[] {
const codeBlockRegex = /```(?:json)?\s*\n?([\s\S]*?)\n?```/g;
const allMatches = [...text.matchAll(codeBlockRegex)];
for (const match of allMatches) {
candidates.add(match[1].trim());
candidates.add(match[1]!.trim());
}

// Strategy 2: Find balanced JSON objects anywhere in the text.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,10 @@ describe("dataset-fields agent tool", () => {

expect(result.dataset).toBe("search_issues");
expect(result.fields).toHaveLength(2); // sentry:user should be filtered out
expect(result.fields[0].key).toBe("level");
expect(result.fields[0].name).toBe("Level");
expect(result.fields[0].totalValues).toBe(5);
expect(result.fields[1].key).toBe("is");
expect(result.fields[0]?.key).toBe("level");
expect(result.fields[0]?.name).toBe("Level");
expect(result.fields[0]?.totalValues).toBe(5);
expect(result.fields[1]?.key).toBe("is");
expect(result.commonPatterns).toContainEqual({
pattern: "is:unresolved",
description: "Open issues",
Expand Down Expand Up @@ -116,15 +116,15 @@ describe("dataset-fields agent tool", () => {

expect(result.dataset).toBe("events");
expect(result.fields).toHaveLength(2);
expect(result.fields[0].key).toBe("http.method");
expect(result.fields[0].examples).toEqual([
expect(result.fields[0]?.key).toBe("http.method");
expect(result.fields[0]?.examples).toEqual([
"GET",
"POST",
"PUT",
"DELETE",
]);
expect(result.fields[1].key).toBe("environment");
expect(result.fields[1].examples).toEqual([
expect(result.fields[1]?.key).toBe("environment");
expect(result.fields[1]?.examples).toEqual([
"production",
"staging",
"development",
Expand Down Expand Up @@ -270,12 +270,12 @@ describe("dataset-fields agent tool", () => {
"search_issues",
);

expect(issuesResult.fields[0].examples).toEqual([
expect(issuesResult.fields[0]?.examples).toEqual([
"email@example.com",
"team-slug",
"me",
]);
expect(issuesResult.fields[1].examples).toEqual([
expect(issuesResult.fields[1]?.examples).toEqual([
"unresolved",
"resolved",
"ignored",
Expand Down Expand Up @@ -304,13 +304,13 @@ describe("dataset-fields agent tool", () => {
"events",
);

expect(eventsResult.fields[0].examples).toEqual([
expect(eventsResult.fields[0]?.examples).toEqual([
"GET",
"POST",
"PUT",
"DELETE",
]);
expect(eventsResult.fields[1].examples).toEqual([
expect(eventsResult.fields[1]?.examples).toEqual([
"postgresql",
"mysql",
"redis",
Expand Down
10 changes: 4 additions & 6 deletions packages/mcp-core/src/internal/formatting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1226,16 +1226,14 @@ function renderPerformanceSpanTree(spans: PerformanceSpan[]): string[] {
lines.push(line);

// Render children
for (let i = 0; i < span.children.length; i++) {
const child = span.children[i];
for (const [i, child] of span.children.entries()) {
const isLastChild = i === span.children.length - 1;
const childPrefix = prefix + (isLast ? " " : "│ ");
renderSpan(child, childPrefix, isLastChild);
}
}

for (let i = 0; i < spans.length; i++) {
const span = spans[i];
for (const [i, span] of spans.entries()) {
const isLastRoot = i === spans.length - 1;
renderSpan(span, "", isLastRoot);
}
Expand Down Expand Up @@ -1418,7 +1416,7 @@ function formatN1QueryEvidence(

// Show the query pattern - if single line, render as SQL block; if multiple, as list
if (repeatingLines.length === 1) {
parts.push(codeBlock(repeatingLines[0], "sql"));
parts.push(codeBlock(repeatingLines[0]!, "sql"));
parts.push("");
} else {
parts.push("**Repeated operations:**");
Expand Down Expand Up @@ -2692,7 +2690,7 @@ function buildAIConversationResponseNotes({
});

if (aiConversations.length === 1) {
const [conversation] = aiConversations;
const conversation = aiConversations[0]!;
const spanSuffix = conversation.spanId
? ` Matching span: \`${conversation.spanId}\`.`
: "";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ export async function mapCredentialContexts<T>(
const results: Array<{ entry: CredentialContext; value: T }> = [];
let firstError: unknown;
for (const [index, result] of settled.entries()) {
const entry = entries[index];
const entry = entries[index]!;
if (result.status === "fulfilled") {
results.push({ entry, value: result.value });
continue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ describe("applyDefaultOrganization", () => {
requiredOrgTool,
getServerContext(),
);
expect(unscoped.organizationSlug.safeParse(undefined).success).toBe(true);
expect(unscoped.organizationSlug.safeParse("").success).toBe(false);
expect(unscoped.organizationSlug?.safeParse(undefined).success).toBe(true);
expect(unscoped.organizationSlug?.safeParse("").success).toBe(false);

const scoped = getFilteredInputSchema(
requiredOrgTool,
Expand Down Expand Up @@ -282,7 +282,7 @@ describe("applyDefaultOrganization", () => {
const context = getServerContext({
sentryHost: "sentry.io",
credentialRouter: {
resolve: async () => credentials[0],
resolve: async () => credentials[0]!,
list: async () => credentials,
},
});
Expand Down Expand Up @@ -317,7 +317,7 @@ describe("applyDefaultOrganization", () => {
{ id: "personal", accessToken: "personal-token" },
];
const credentialRouter: CredentialRouter = {
resolve: async () => credentials[0],
resolve: async () => credentials[0]!,
list: async () => credentials,
};
const context = getServerContext({
Expand Down
4 changes: 2 additions & 2 deletions packages/mcp-core/src/internal/tool-helpers/seer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,8 +339,8 @@ export function getAutofixArtifactSummaries(autofix: AutofixRun): {
* a run is processing.
*/
export function getActiveAutofixTodo(autofix: AutofixRun): string | null {
for (let i = autofix.blocks.length - 1; i >= 0; i--) {
const todos = autofix.blocks[i].todos;
for (const block of autofix.blocks.toReversed()) {
const todos = block.todos;
if (!todos?.length) {
continue;
}
Expand Down
19 changes: 13 additions & 6 deletions packages/mcp-core/src/internal/url-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,12 +174,14 @@ function extractOrganizationSlug(parsedUrl: URL, pathParts: string[]): string {
"insights",
"preprod",
];
const [firstPathPart, secondPathPart] = pathParts;
if (
pathParts.length > 1 &&
!knownSegments.includes(pathParts[0]) &&
knownSegments.includes(pathParts[1])
firstPathPart !== undefined &&
secondPathPart !== undefined &&
!knownSegments.includes(firstPathPart) &&
knownSegments.includes(secondPathPart)
) {
return pathParts[0];
return firstPathPart;
}

// Check for subdomain (e.g., my-org.sentry.io)
Expand All @@ -188,8 +190,13 @@ function extractOrganizationSlug(parsedUrl: URL, pathParts: string[]): string {
const regionPrefixes = ["us", "eu", "de", "www"];

// Non-region subdomain (e.g., my-org.sentry.io or sentry.mycompany.com)
if (hostParts.length >= 2 && !regionPrefixes.includes(hostParts[0])) {
return hostParts[0];
const [subdomain] = hostParts;
if (
subdomain !== undefined &&
hostParts.length >= 2 &&
!regionPrefixes.includes(subdomain)
) {
return subdomain;
}

// If we reach here with region-prefixed URL, we couldn't determine the org
Expand Down
2 changes: 1 addition & 1 deletion packages/mcp-core/src/server.metadata.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ describe("outputSchema skip lists", () => {
...Object.keys(OUTPUT_SCHEMA_EXEMPT).map((name) => ["EXEMPT", name]),
...Object.keys(OUTPUT_SCHEMA_PENDING).map((name) => ["PENDING", name]),
].flatMap(([list, name]) => {
const tools = listings(name);
const tools = listings(name!);
if (tools.length === 0) {
return [`${name}: in OUTPUT_SCHEMA_${list} but not listed`];
}
Expand Down
Loading
Loading