Skip to content
Draft
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
32 changes: 32 additions & 0 deletions packages/mcp-core/src/api-client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ import {
TagListSchema,
TeamListSchema,
TeamSchema,
TraceItemDetailsSchema,
TraceMetaSchema,
TraceSchema,
TransactionProfileResponseSchema,
Expand Down Expand Up @@ -268,6 +269,7 @@ import type {
Team,
TeamList,
Trace,
TraceItemDetails,
TraceMeta,
TransactionProfile,
LegacySpeedscopeProfile,
Expand Down Expand Up @@ -4997,6 +4999,36 @@ export class SentryApiService {
return await getTrace(this.target(opts?.host), params, TraceSchema);
}

/**
* Retrieves every recorded attribute of one span from the trace-items
* details endpoint. The trace endpoint does not return them.
*/
async getSpanAttributes(
{
organizationSlug,
projectSlug,
traceId,
spanId,
}: {
organizationSlug: string;
projectSlug: string;
traceId: string;
spanId: string;
},
opts?: RequestOptions,
): Promise<TraceItemDetails> {
const query = new URLSearchParams({
trace_id: traceId,
item_type: "spans",
});
const body = await this.requestJSON(
`${apiPath`/projects/${organizationSlug}/${projectSlug}/trace-items/${spanId}/`}?${query}`,
undefined,
opts,
);
return TraceItemDetailsSchema.parse(body);
}

/**
* Fetches all spans for one AI conversation within a relative or absolute time window.
*/
Expand Down
26 changes: 26 additions & 0 deletions packages/mcp-core/src/api-client/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1901,6 +1901,32 @@ export const TraceSchema = z.array(
z.union([TraceSpanSchema, TraceIssueSchema]),
);

/**
* Schema for one trace item from the trace-items details endpoint.
*
* The trace endpoint only returns a fixed set of span columns, so this is
* where a span's recorded attributes come from. Names are the ones search
* accepts, such as `http.request.method` or `tags[retry_count,number]`.
* Values stay loose: Sentry sends int64 values as strings.
*
* Upstream source of truth in getsentry/sentry:
* - `src/sentry/api/endpoints/project_trace_item_details.py`
*/
export const TraceItemDetailsSchema = z
.object({
itemId: z.string(),
attributes: z.array(
z
.object({
name: z.string(),
type: z.string(),
value: z.unknown(),
})
.passthrough(),
),
})
.passthrough();

const NullableStringOrNumberSchema = z
.union([z.string(), z.number()])
.nullable()
Expand Down
2 changes: 2 additions & 0 deletions packages/mcp-core/src/api-client/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ import type {
TeamListSchema,
TeamSchema,
TraceIssueSchema,
TraceItemDetailsSchema,
TraceMetaSchema,
TraceSchema,
TraceSpanSchema,
Expand Down Expand Up @@ -305,6 +306,7 @@ export type TraceMeta = z.infer<typeof TraceMetaSchema>;
export type TraceSpan = z.infer<typeof TraceSpanSchema>;
export type TraceIssue = z.infer<typeof TraceIssueSchema>;
export type Trace = z.infer<typeof TraceSchema>;
export type TraceItemDetails = z.infer<typeof TraceItemDetailsSchema>;
export type AIConversationSpan = z.infer<typeof AIConversationSpanSchema>;
export type AIConversationSpanList = z.infer<
typeof AIConversationSpanListSchema
Expand Down
101 changes: 101 additions & 0 deletions packages/mcp-core/src/tools/catalog/get-span-details.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,48 @@ function httpGetRegional(
];
}

const TRACE_ID = "b4d1aae7216b47ff8117cf4e09ce9d0b";
const SPAN_ID = "aa8e7f3384ef4ff5";

function mockTrace() {
return [
...httpGetRegional(
`https://sentry.io/api/0/organizations/sentry-mcp-evals/trace-meta/${TRACE_ID}/`,
() =>
HttpResponse.json({
logs: 0,
errors: 2,
performance_issues: 0,
span_count: 4,
transaction_child_count_map: [],
span_count_map: {},
}),
),
...httpGetRegional(
`https://sentry.io/api/0/organizations/sentry-mcp-evals/trace/${TRACE_ID}/`,
() => HttpResponse.json(traceMixedFixture),
),
];
}

async function callGetSpanDetails() {
return await getSpanDetails.handler(
{
organizationSlug: "sentry-mcp-evals",
traceId: TRACE_ID,
spanId: SPAN_ID,
regionUrl: null,
},
{
constraints: {
organizationSlug: null,
},
accessToken: "access-token",
userId: "1",
},
);
}

describe("get_span_details", () => {
it("renders a focused span with child snapshot and attributes", async () => {
mswServer.use(
Expand Down Expand Up @@ -88,6 +130,12 @@ describe("get_span_details", () => {

## Attributes

### Recorded Attributes

\`\`\`json
{}
\`\`\`

### Core Fields

\`\`\`json
Expand Down Expand Up @@ -168,4 +216,57 @@ describe("get_span_details", () => {
- **Search logs**: Use the Sentry tool \`search_logs\`"
`);
});

it("shows the attributes the span recorded, which the trace endpoint omits", async () => {
let requestedUrl: URL | undefined;
mswServer.use(
...mockTrace(),
...httpGetRegional(
`https://sentry.io/api/0/projects/sentry-mcp-evals/mcp-server/trace-items/${SPAN_ID}/`,
({ request }) => {
requestedUrl = new URL(request.url);
return HttpResponse.json({
itemId: SPAN_ID,
timestamp: "2024-04-22T16:51:03.608875Z",
attributes: [
{ name: "http.request.method", type: "str", value: "PUT" },
{ name: "tags[retry_count,number]", type: "int", value: "3" },
],
meta: {},
links: null,
});
},
),
);

const result = await callGetSpanDetails();

expect(requestedUrl?.searchParams.get("trace_id")).toBe(TRACE_ID);
expect(requestedUrl?.searchParams.get("item_type")).toBe("spans");
expect(result).toContain(`### Recorded Attributes

\`\`\`json
{
"http.request.method": "PUT",
"tags[retry_count,number]": "3"
}
\`\`\``);
});

it("still returns the span when Sentry can't return its attributes", async () => {
mswServer.use(
...mockTrace(),
...httpGetRegional(
`https://sentry.io/api/0/projects/sentry-mcp-evals/mcp-server/trace-items/${SPAN_ID}/`,
() => HttpResponse.json({ detail: "Not found" }, { status: 404 }),
),
);

const result = await callGetSpanDetails();

expect(result).toContain(`# Span \`${SPAN_ID}\``);
expect(result).toContain(
"*Sentry did not return this span's recorded attributes.",
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -1395,6 +1395,12 @@ describe("get_trace_details", () => {

## Attributes

### Recorded Attributes

\`\`\`json
{}
\`\`\`

### Core Fields

\`\`\`json
Expand Down
88 changes: 86 additions & 2 deletions packages/mcp-core/src/tools/catalog/get-trace-details.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import type { SentryApiService, Trace, TraceSpan } from "../../api-client";
import { UserInputError } from "../../errors";
import {
ApiClientError,
type SentryApiService,
type Trace,
type TraceSpan,
} from "../../api-client";
import { ConfigurationError, UserInputError } from "../../errors";
import { hasAgentProvider } from "../../internal/agents/provider-factory";
import {
type AIConversationReference,
Expand All @@ -15,6 +20,7 @@ import {
ParamSpanId,
ParamTraceId,
} from "../../schema";
import { logIssue } from "../../telem/logging";
import { setTargetTagsAndAttributes } from "../../telem/scope";
import type { ServerContext } from "../../types";
import { formatSemanticSpanDisplay } from "../support/traces/semantic-display.js";
Expand Down Expand Up @@ -141,10 +147,22 @@ export default defineTool({
});

const aiConversations = collectAIConversationReferencesFromTrace(trace);
const focusedSpan = params.spanId
? findTraceSpan(trace, params.spanId)
: null;
const recordedAttributes = focusedSpan
? await fetchRecordedAttributes({
apiService,
organizationSlug: params.organizationSlug,
traceId: params.traceId,
span: focusedSpan,
})
: null;
const markdown = formatTraceOutput({
organizationSlug: params.organizationSlug,
traceId: params.traceId,
spanId: params.spanId,
recordedAttributes,
summary,
trace,
traceFetchState,
Expand Down Expand Up @@ -651,6 +669,7 @@ function formatTraceOutput({
organizationSlug,
traceId,
spanId,
recordedAttributes,
summary,
trace,
traceFetchState,
Expand All @@ -663,6 +682,7 @@ function formatTraceOutput({
organizationSlug: string;
traceId: string;
spanId?: string | undefined;
recordedAttributes: RecordedAttributes | null;
summary: TraceSummary;
trace: Trace;
traceFetchState: TraceFetchState;
Expand All @@ -677,6 +697,7 @@ function formatTraceOutput({
organizationSlug,
traceId,
spanId,
recordedAttributes,
summary,
trace,
traceFetchState,
Expand Down Expand Up @@ -815,6 +836,7 @@ function formatFocusedSpanOutput({
organizationSlug,
traceId,
spanId,
recordedAttributes,
summary,
trace,
traceFetchState,
Expand All @@ -827,6 +849,7 @@ function formatFocusedSpanOutput({
organizationSlug: string;
traceId: string;
spanId: string;
recordedAttributes: RecordedAttributes | null;
summary: TraceSummary;
trace: Trace;
traceFetchState: TraceFetchState;
Expand Down Expand Up @@ -901,6 +924,7 @@ function formatFocusedSpanOutput({
sections.push("");
sections.push("## Attributes");
sections.push("");
sections.push(...formatRecordedAttributesSection(recordedAttributes));
sections.push(...formatSpanAttributeSections(focusedSpan, traceId));
sections.push(
...formatAIConversationSection({
Expand Down Expand Up @@ -994,6 +1018,66 @@ function buildSpanUrl(traceUrl: string, spanId: string): string {
return url.toString();
}

/** A span's recorded attributes, keyed by the name search accepts. */
type RecordedAttributes = Record<string, unknown>;

/**
* Sentry's trace endpoint only returns fixed span columns, so the attributes
* an SDK recorded (http.request.method, custom data) come from the
* trace-items endpoint. A failure here must not fail the whole span lookup.
*/
async function fetchRecordedAttributes({
apiService,
organizationSlug,
traceId,
span,
}: {
apiService: SentryApiService;
organizationSlug: string;
traceId: string;
span: TraceSpan;
}): Promise<RecordedAttributes | null> {
const spanId = getTraceSpanId(span);
try {
const item = await apiService.getSpanAttributes({
organizationSlug,
projectSlug: span.project_slug,
traceId,
spanId,
});
return Object.fromEntries(
item.attributes.map((attribute) => [attribute.name, attribute.value]),
);
} catch (error) {
if (
!(error instanceof ApiClientError) &&
!(error instanceof ConfigurationError)
) {
logIssue(error, {
loggerScope: ["tools", "get-trace-details", "recorded-attributes"],
contexts: {
request: { organizationSlug, traceId, spanId },
},
});
}
return null;
}
}

function formatRecordedAttributesSection(
recordedAttributes: RecordedAttributes | null,
): string[] {
if (!recordedAttributes) {
return [
"### Recorded Attributes",
"",
"*Sentry did not return this span's recorded attributes. The sections below only have the fixed fields from the trace.*",
"",
];
}
return formatJsonSection("### Recorded Attributes", recordedAttributes);
}

function formatSpanAttributeSections(
span: TraceSpan,
traceId: string,
Expand Down
Loading
Loading