Skip to main content
Glama
Use-Tusk
by Use-Tusk

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

TableJSON Schema
NameRequiredDescriptionDefault
observableServiceIdNoService ID to query (required if multiple services available)
whereNoRecursive span filter clause
orderByNoOrdering
limitNoMax results to return
offsetNoPagination offset
includePayloadsNoInclude full inputValue/outputValue (verbose)
maxPayloadLengthNoTruncate payload strings to this length

Implementation Reference

  • 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,
          },
        },
      },
    };
  • 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";
  • Registers querySpansTool in the tools array for MCP tool discovery.
    export const tools: Tool[] = [
      querySpansTool,
  • Maps the handler function to the 'query_spans' key in toolHandlers record for dispatch.
    export const toolHandlers: Record<string, ToolHandler> = {
      query_spans: handleQuerySpans,
  • 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,
      });
    }
  • 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"),
    });
  • Type alias QuerySpansInput mapped to shared protobuf request type.
    export type QuerySpansInput = SharedQuerySpansRequest;
  • 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>;
  • 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,
            };
          }
        }
      );
  • 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}`;
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description must cover behavior. It implies read-only by describing search/filter actions, but does not explicitly mention safety or side effects. The examples show querying, but pagination and performance are not discussed. Adequate but not fully comprehensive.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is clear and well-structured with a purpose statement, use cases, and examples. It is relatively long but each part is useful. It could be slightly more concise without the examples, but the examples provide significant value.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity (nested 'where' clause, 7 parameters, no output schema), the description covers common scenarios and parameter usage well. It does not explain return format, but the examples hint at output fields. Adequate for most use cases.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%, baseline 3. The description adds concrete examples for the 'where' clause, showing how to filter by status, duration, and endpoint name. This adds practical meaning beyond the schema definitions, earning a 4.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states 'Search and filter API traffic span recordings' and provides specific use cases (find by endpoint, errors, slow requests, recent traffic). It distinguishes itself from siblings like aggregate_spans and get_spans_by_ids by focusing on general filtering and searching.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description lists explicit use cases with examples, providing clear guidance on when to use the tool. However, it does not explicitly state when not to use it or compare with alternatives, though the sibling context makes it clear.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Use-Tusk/drift-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server