query_spans
Find and filter API traffic spans to locate specific endpoints, errors, or slow requests. Debug API calls by searching recent recordings with flexible filters.
Instructions
Search and filter API traffic span recordings.
Use this tool to:
Find specific API calls by endpoint name, HTTP method, or status code
Search for errors or slow requests
Get recent traffic for a specific endpoint
Debug specific API calls
Examples:
Find failed requests: where = { fields: { "outputValue.statusCode": { gte: 400, access: { castAs: "int" } } } }
Find slow requests: where = { fields: { duration: { gt: 1000 } } }
Recent traffic for endpoint: where = { fields: { name: { eq: "/api/orders" } } }, limit = 10, orderBy = [{ field: "timestamp", direction: "DESC" }]
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| observableServiceId | No | Service ID to query (required if multiple services available) | |
| where | No | Recursive span filter clause | |
| orderBy | No | Ordering | |
| limit | No | Max results to return | |
| offset | No | Pagination offset | |
| includePayloads | No | Include full inputValue/outputValue (verbose) | |
| maxPayloadLength | No | Truncate payload strings to this length |
Implementation Reference
- src/tools/querySpans.ts:9-72 (schema)Tool definition/schema for 'query_spans' - declares the MCP tool name, description, and inputSchema with properties like observableServiceId, where, orderBy, limit, offset, includePayloads, maxPayloadLength.
export const querySpansTool: Tool = { name: "query_spans", description: `Search and filter API traffic span recordings. Use this tool to: - Find specific API calls by endpoint name, HTTP method, or status code - Search for errors or slow requests - Get recent traffic for a specific endpoint - Debug specific API calls Examples: - Find failed requests: where = { fields: { "outputValue.statusCode": { gte: 400, access: { castAs: "int" } } } } - Find slow requests: where = { fields: { duration: { gt: 1000 } } } - Recent traffic for endpoint: where = { fields: { name: { eq: "/api/orders" } } }, limit = 10, orderBy = [{ field: "timestamp", direction: "DESC" }]`, inputSchema: { type: "object", properties: { observableServiceId: { type: "string", description: "Service ID to query. Required if multiple services are available.", }, where: { type: "object", description: "Recursive filter clause. Use where.fields for field predicates and where.and/or/not for boolean composition.", }, orderBy: { type: "array", description: "Order results", items: { type: "object", properties: { field: { type: "string", enum: [...spanSortFieldCodec.names], }, direction: { type: "string", enum: [...sortDirectionCodec.names] }, }, required: ["field", "direction"], }, }, limit: { type: "number", description: "Maximum results to return (1-100, default 20)", default: 20, }, offset: { type: "number", description: "Pagination offset", default: 0, }, includePayloads: { type: "boolean", description: "Include full inputValue/outputValue in results (can be verbose)", default: false, }, maxPayloadLength: { type: "number", description: "Truncate payload strings to this length", default: 500, }, }, }, }; - src/tools/querySpans.ts:74-119 (handler)Main handler function 'handleQuerySpans' - parses input via parseQuerySpansInput, calls client.querySpans(), then formats the results (spans with ID, trace, duration, status, optional payloads) into a text response.
export async function handleQuerySpans( client: TuskDriftApiClient, args: Record<string, unknown> ): Promise<{ content: Array<{ type: "text"; text: string }> }> { const input = parseQuerySpansInput(args); const result = await client.querySpans(input); const summary = [ `Found ${result.total} spans (showing ${result.spans.length})`, result.hasMore ? `More results available (offset: ${(input.offset || 0) + result.spans.length})` : "", ] .filter(Boolean) .join("\n"); const spansText = result.spans .map((span, i) => { const lines = [ `[${i + 1}] ${span.name}`, ` ID: ${span.id}`, ` Trace: ${span.traceId}`, ` Package: ${span.packageName}`, ` Duration: ${span.duration.toFixed(2)}ms`, ` Status: ${span.status.code === 0 ? "OK" : span.status.code === 1 ? "UNSET" : "ERROR"}`, ` Timestamp: ${span.timestamp}`, ]; if (span.inputValue && input.includePayloads) { lines.push(` Input: ${JSON.stringify(span.inputValue, null, 2).split("\n").join("\n ")}`); } if (span.outputValue && input.includePayloads) { lines.push(` Output: ${JSON.stringify(span.outputValue, null, 2).split("\n").join("\n ")}`); } return lines.join("\n"); }) .join("\n\n"); return { content: [ { type: "text", text: `${summary}\n\n${spansText}`, }, ], }; } - src/tools/index.ts:3-3 (registration)Imports querySpansTool and handleQuerySpans from querySpans.ts.
import { querySpansTool, handleQuerySpans } from "./querySpans.js"; - src/tools/index.ts:10-11 (registration)Registers querySpansTool in the tools array for MCP tool discovery.
export const tools: Tool[] = [ querySpansTool, - src/tools/index.ts:24-25 (registration)Maps the handler function to the 'query_spans' key in toolHandlers record for dispatch.
export const toolHandlers: Record<string, ToolHandler> = { query_spans: handleQuerySpans, - src/types.ts:349-363 (helper)Helper function 'parseQuerySpansInput' - validates input args with Zod schema and converts to protobuf QuerySpansRequest format.
export function parseQuerySpansInput(args: Record<string, unknown>): QuerySpansInput { const input: QuerySpansArgs = querySpansInputSchema.parse(args); return SharedQuerySpansRequest.create({ observableServiceId: input.observableServiceId ?? "", where: input.where ? toProtoWhereClause(input.where) : undefined, orderBy: (input.orderBy ?? []).map((orderBy) => ({ field: spanSortFieldCodec.byName[orderBy.field], direction: sortDirectionCodec.byName[orderBy.direction], })), limit: input.limit, offset: input.offset, includePayloads: input.includePayloads, maxPayloadLength: input.maxPayloadLength, }); } - src/types.ts:213-229 (schema)Zod input schema 'querySpansInputSchema' for validating query_spans tool arguments (observableServiceId, where, orderBy, limit, offset, includePayloads, maxPayloadLength).
export const querySpansInputSchema = z.object({ observableServiceId: z.string().optional().describe("Service ID to query (required if multiple services available)"), where: spanWhereClauseSchema.optional().describe("Recursive span filter clause"), orderBy: z .array( z.object({ field: enumNameSchema(spanSortFieldCodec), direction: enumNameSchema(sortDirectionCodec), }) ) .optional() .describe("Ordering"), limit: z.number().min(1).max(100).default(20).describe("Max results to return"), offset: z.number().min(0).default(0).describe("Pagination offset"), includePayloads: z.boolean().default(false).describe("Include full inputValue/outputValue (verbose)"), maxPayloadLength: z.number().min(0).default(500).describe("Truncate payload strings to this length"), }); - src/types.ts:291-291 (helper)Type alias QuerySpansInput mapped to shared protobuf request type.
export type QuerySpansInput = SharedQuerySpansRequest; - src/provider.ts:27-31 (schema)QuerySpansResult interface - defines response shape with spans array, total count, and hasMore flag.
export interface QuerySpansResult { spans: SpanRecording[]; total: number; hasMore: boolean; } - src/provider.ts:57-61 (registration)DriftDataProvider interface declares the querySpans method signature.
export interface DriftDataProvider { /** * Query span recordings with filters. */ querySpans(input: QuerySpansInput): Promise<QuerySpansResult>; - src/apiClient.ts:100-122 (handler)API client implementation of querySpans - sends request to /api/drift/query/spans endpoint and processes the response.
async querySpans(input: QuerySpansInput): Promise<QuerySpansResult> { const result = await this.request<QuerySpansApiResponse>( "/spans", QuerySpansRequest.toJson( QuerySpansRequest.create({ ...input, observableServiceId: this.resolveServiceId(input.observableServiceId || undefined), }), PROTO_JSON_OPTIONS ) ); const total = result.total ?? result.totalCount; if (total === undefined) { throw new Error("API response for /api/drift/query/spans is missing total/totalCount"); } return { spans: result.spans, total, hasMore: result.hasMore, }; } - src/server.ts:200-247 (registration)MCP server registration of query_spans tool via server.registerTool with description, inputSchema, and handler callback.
// ============================================ // Tool: query_spans // ============================================ server.registerTool( "query_spans", { description: `Search and filter API traffic span recordings. Use this tool to: - Find specific API calls by endpoint name, HTTP method, or status code - Search for errors or slow requests - Get recent traffic for a specific endpoint - Debug specific API calls Examples: - Find failed requests: where = { fields: { "outputValue.statusCode": { gte: 400, access: { castAs: "int" } } } } - Find slow requests: where = { fields: { duration: { gt: 1000 } } } - Recent traffic for endpoint: where = { fields: { name: { eq: "/api/orders" } } }, limit = 10, orderBy = [{ field: "timestamp", direction: "DESC" }]`, inputSchema: querySpansInputSchema.shape, }, async (args) => { const input = parseQuerySpansInput(args); if (input.observableServiceId && !(await checkAccess(input.observableServiceId))) { return { content: [{ type: "text" as const, text: "Error: Access denied to observable service" }], isError: true, }; } try { const result = await provider.querySpans(input); return { content: [ { type: "text" as const, text: formatQuerySpansResult(result, input.includePayloads ?? false), }, ], }; } catch (error) { return { content: [{ type: "text" as const, text: `Error executing query_spans: ${error}` }], isError: true, }; } } ); - src/server.ts:42-78 (helper)formatQuerySpansResult helper - formats query results into human-readable text output.
function formatQuerySpansResult(result: QuerySpansResult, includePayloads: boolean): string { const summary = [ `Found ${result.total} spans (showing ${result.spans.length})`, result.hasMore ? `More results available (offset: ${result.spans.length})` : "", ] .filter(Boolean) .join("\n"); const spansText = result.spans .map((span, i) => { const lines = [ `[${i + 1}] ${span.name}`, ` ID: ${span.id}`, ` Trace: ${span.traceId}`, ` Package: ${span.packageName}`, ` Duration: ${span.duration?.toFixed(2) ?? "N/A"}ms`, ` Status: ${span.status?.code === 0 ? "OK" : span.status?.code === 1 ? "UNSET" : "ERROR"}`, ` Timestamp: ${span.timestamp}`, ]; if (span.inputValue && includePayloads) { lines.push( ` Input: ${JSON.stringify(span.inputValue, null, 2).split("\n").join("\n ")}` ); } if (span.outputValue && includePayloads) { lines.push( ` Output: ${JSON.stringify(span.outputValue, null, 2).split("\n").join("\n ")}` ); } return lines.join("\n"); }) .join("\n\n"); return `${summary}\n\n${spansText}`; }