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

query_spans

Search and filter API traffic span recordings to find specific API calls, identify errors or slow requests, and debug API performance issues.

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.name = { contains: "/api/users" }, jsonbFilters = [{ column: "outputValue", jsonPath: "$.statusCode", gte: 400, castAs: "int" }]

  • Find slow requests: where.duration = { gt: 1000 }

  • Recent traffic for endpoint: where.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)
whereNoFilter conditions for spans
jsonbFiltersNoJSONB path filters for inputValue/outputValue
orderByNoOrdering
limitNoMax results to return
offsetNoPagination offset
includeInputOutputNoInclude full inputValue/outputValue (verbose)
maxPayloadLengthNoTruncate payload strings to this length

Implementation Reference

  • The handler function for the query_spans tool. Parses input using the schema, calls the API client's querySpans method, formats the spans into a readable text summary, and returns it as MCP content.
    export async function handleQuerySpans(
      client: TuskDriftApiClient,
      args: Record<string, unknown>
    ): Promise<{ content: Array<{ type: "text"; text: string }> }> {
      const input = querySpansInputSchema.parse(args) as QuerySpansInput;
      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.includeInputOutput) {
            lines.push(`    Input: ${JSON.stringify(span.inputValue, null, 2).split("\n").join("\n    ")}`);
          }
          if (span.outputValue && input.includeInputOutput) {
            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}`,
          },
        ],
      };
    }
  • Zod schema defining the input structure and validation for the query_spans tool, including filters, ordering, pagination, and payload options.
    export const querySpansInputSchema = z.object({
      observableServiceId: z.string().optional().describe("Service ID to query (required if multiple services available)"),
      where: spanWhereClauseSchema.optional().describe("Filter conditions for spans"),
      jsonbFilters: z.array(jsonbFilterSchema).optional().describe("JSONB path filters for inputValue/outputValue"),
      orderBy: z
        .array(
          z.object({
            field: z.enum(["timestamp", "duration", "name"]),
            direction: z.enum(["ASC", "DESC"]),
          })
        )
        .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"),
      includeInputOutput: z.boolean().default(false).describe("Include full inputValue/outputValue (verbose)"),
      maxPayloadLength: z.number().min(0).default(500).describe("Truncate payload strings to this length"),
    });
  • Registration of the query_spans handler in the toolHandlers map, linking the tool name to its execution function.
    export const toolHandlers: Record<string, ToolHandler> = {
      query_spans: handleQuerySpans,
      get_schema: handleGetSchema,
      list_distinct_values: handleListDistinctValues,
      aggregate_spans: handleAggregateSpans,
      get_trace: handleGetTrace,
      get_spans_by_ids: handleGetSpansByIds,
    };
  • Registration of the querySpansTool in the exported tools array for MCP tool discovery.
    export const tools: Tool[] = [
      querySpansTool,
      getSchemaTool,
      listDistinctValuesTool,
      aggregateSpansTool,
      getTraceTool,
      getSpansByIdsTool,
    ];
  • Definition of the querySpansTool object, including name, description, and JSON inputSchema for MCP tool protocol.
    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.name = { contains: "/api/users" }, jsonbFilters = [{ column: "outputValue", jsonPath: "$.statusCode", gte: 400, castAs: "int" }]
    - Find slow requests: where.duration = { gt: 1000 }
    - Recent traffic for endpoint: where.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: "Filter conditions for spans",
            properties: {
              name: {
                type: "object",
                description: "Filter by span/endpoint name",
                properties: {
                  eq: { type: "string" },
                  contains: { type: "string" },
                  startsWith: { type: "string" },
                  in: { type: "array", items: { type: "string" } },
                },
              },
              packageName: {
                type: "object",
                description: "Filter by instrumentation package (http, pg, fetch, grpc, etc.)",
                properties: {
                  eq: { type: "string" },
                  in: { type: "array", items: { type: "string" } },
                },
              },
              instrumentationName: {
                type: "object",
                description: "Filter by instrumentation name",
                properties: { eq: { type: "string" } },
              },
              duration: {
                type: "object",
                description: "Filter by duration in milliseconds",
                properties: {
                  gt: { type: "number" },
                  gte: { type: "number" },
                  lt: { type: "number" },
                  lte: { type: "number" },
                },
              },
              traceId: {
                type: "object",
                description: "Filter by trace ID",
                properties: { eq: { type: "string" } },
              },
              isRootSpan: {
                type: "object",
                description: "Filter by root span status",
                properties: { eq: { type: "boolean" } },
              },
              AND: {
                type: "array",
                description: "Combine conditions with AND",
              },
              OR: {
                type: "array",
                description: "Combine conditions with OR",
              },
            },
          },
          jsonbFilters: {
            type: "array",
            description: "Filters for JSONB columns (inputValue, outputValue, metadata)",
            items: {
              type: "object",
              properties: {
                column: {
                  type: "string",
                  enum: ["inputValue", "outputValue", "metadata", "status"],
                  description: "JSONB column to filter",
                },
                jsonPath: {
                  type: "string",
                  description: "JSONPath expression starting with $ (e.g., $.statusCode, $.body.userId)",
                },
                eq: { description: "Equals value" },
                neq: { description: "Not equals value" },
                gt: { type: "number", description: "Greater than" },
                gte: { type: "number", description: "Greater than or equal" },
                lt: { type: "number", description: "Less than" },
                lte: { type: "number", description: "Less than or equal" },
                contains: { type: "string", description: "String contains" },
                castAs: {
                  type: "string",
                  enum: ["text", "int", "float", "boolean"],
                  description: "Cast JSONB value to type for comparison",
                },
                decodeBase64: {
                  type: "boolean",
                  description: "Decode base64 string before applying filter",
                },
                thenPath: {
                  type: "string",
                  description: "Additional JSONPath to apply after base64 decoding",
                },
              },
              required: ["column", "jsonPath"],
            },
          },
          orderBy: {
            type: "array",
            description: "Order results",
            items: {
              type: "object",
              properties: {
                field: { type: "string", enum: ["timestamp", "duration", "name"] },
                direction: { type: "string", enum: ["ASC", "DESC"] },
              },
              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,
          },
          includeInputOutput: {
            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,
          },
        },
      },
    };
Behavior3/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It describes the tool's functionality (searching and filtering) and provides examples of use cases, but it lacks details on permissions, rate limits, error handling, or response format. It adds practical context but misses key behavioral traits for a query tool.

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 well-structured with a clear opening sentence, bulleted use cases, and detailed examples. It is appropriately sized and front-loaded, though the examples are lengthy, which slightly reduces efficiency but adds value for clarity.

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

Completeness3/5

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

Given the complexity (8 parameters, nested objects) and no annotations or output schema, the description is moderately complete. It covers purpose and usage with examples but lacks details on behavioral aspects like permissions or response format, leaving gaps for a query tool with rich input schema.

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

Parameters3/5

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

Schema description coverage is 100%, so the schema already documents all 8 parameters thoroughly. The description adds minimal parameter semantics through examples (e.g., using 'where.name' and 'jsonbFilters'), but it does not provide significant additional meaning beyond what the schema provides, aligning with the baseline for high coverage.

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 the tool's purpose with specific verbs ('search and filter') and resource ('API traffic span recordings'), distinguishing it from siblings like 'aggregate_spans' (aggregation) and 'get_spans_by_ids' (ID-based retrieval). The bullet points further clarify its use cases for finding, searching, getting, and debugging.

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 provides clear context for when to use this tool (e.g., 'Find specific API calls by endpoint name, HTTP method, or status code'), but it does not explicitly state when not to use it or name specific alternatives among the sibling tools. The examples imply usage scenarios without explicit exclusions.

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