Skip to main content
Glama
Nozomuts

Datadog MCP Server

by Nozomuts

aggregate_spans

Aggregate Datadog trace spans by attributes like service or status to analyze performance patterns and identify issues through time-series or total summaries.

Instructions

Tool for aggregating Datadog trace spans

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filterQueryNoQuery string to search for (optional, default is '*')*
filterFromNoSearch start time (UNIX timestamp in seconds, optional, default is 15 minutes ago)
filterToNoSearch end time (UNIX timestamp in seconds, optional, default is current time)
groupByNoAttributes to group by (example: ['service', 'resource_name'])
intervalNoTime interval to group results by (optional, only used when type is timeseries)
typeNoResult type - timeseries or total (optional, default is 'timeseries')timeseries

Implementation Reference

  • Handler function for the aggregate_spans tool. Validates input using Zod schema, calls the core aggregateSpans function, formats the response with summary and Datadog link.
    export const aggregateSpansHandler = async (
      parameters: z.infer<typeof aggregateSpansZodSchema>
    ): Promise<ToolResponse> => {
      const validation = aggregateSpansZodSchema.safeParse(parameters);
    
      if (!validation.success) {
        return createErrorResponse(
          `Parameter validation error: ${validation.error.message}`
        );
      }
    
      try {
        // Convert to Date objects after validation
        const validatedParams = {
          ...validation.data,
          filterFrom: new Date(validation.data.filterFrom * 1000),
          filterTo: new Date(validation.data.filterTo * 1000),
        };
    
        const result = await aggregateSpans(validatedParams);
        const formattedResult = generateSummaryText(validation.data, result);
        const urlText = `[View in Datadog](https://app.datadoghq.com/apm/traces?query=${encodeURIComponent(
          validation.data.filterQuery
        )}&start=${validation.data.filterFrom}&end=${
          validation.data.filterTo
        }&viz=${
          validation.data.type === "total" ? "toplist" : validation.data.type
        }&agg_q=${validation.data.groupBy?.join(",") || ""})`;
        return createSuccessResponse([formattedResult, urlText]);
      } catch (error: unknown) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        return createErrorResponse(`Span aggregation error: ${errorMessage}`);
      }
    };
  • Zod schema defining input parameters for the aggregate_spans tool, including query filters, time range, grouping, interval, and aggregation type.
    export const aggregateSpansZodSchema = z.object({
      filterQuery: z
        .string()
        .optional()
        .default("*")
        .describe("Query string to search for (optional, default is '*')"),
      filterFrom: z
        .number()
        .optional()
        .default(Date.now() / 1000 - 15 * 60)
        .describe(
          "Search start time (UNIX timestamp in seconds, optional, default is 15 minutes ago)"
        ),
      filterTo: z
        .number()
        .optional()
        .default(Date.now() / 1000)
        .describe(
          "Search end time (UNIX timestamp in seconds, optional, default is current time)"
        ),
      groupBy: z
        .array(
          z.enum([
            "service",
            "resource_name",
            "env",
            "status",
            "operation_name",
            "type",
            "@version",
            "@http.status_code",
            "@http.client_ip",
            "@http.url",
            "@http.method",
            "@http.host",
            "@http.user_agent",
            "@http.path_group",
            "@http.route",
          ])
        )
        .optional()
        .describe("Attributes to group by (example: ['service', 'resource_name'])"),
      interval: z
        .string()
        .optional()
        .describe(
          "Time interval to group results by (optional, only used when type is timeseries)"
        ),
      type: z
        .enum(["timeseries", "total"])
        .default("timeseries")
        .describe(
          "Result type - timeseries or total (optional, default is 'timeseries')"
        ),
    });
  • src/index.ts:32-37 (registration)
    Registers the 'aggregate_spans' tool on the MCP server using the schema and handler.
    server.tool(
      "aggregate_spans",
      "Tool for aggregating Datadog trace spans",
      aggregateSpansZodSchema.shape,
      aggregateSpansHandler
    );
  • Core helper function that makes the Datadog API call to aggregate spans, constructs the request body, processes the response into structured buckets.
    export const aggregateSpans = async (
      params: SpanAggregationParams
    ): Promise<SpanAggregationResult> => {
      try {
        const configuration = createConfiguration();
        const spansApi = new v2.SpansApi(configuration);
    
        const { filterFrom, filterTo, filterQuery, interval, type } = params;
    
        const requestBody: v2.SpansApiAggregateSpansRequest = {
          body: {
            data: {
              attributes: {
                compute: [
                  {
                    aggregation: "count",
                    interval: interval,
                    type: type,
                  },
                ],
                filter: {
                  from: filterFrom.toISOString(),
                  to: filterTo.toISOString(),
                  query: filterQuery,
                },
                groupBy: params.groupBy?.length
                  ? params.groupBy.map((field) => ({
                      facet: field,
                      limit: 10,
                    }))
                  : undefined,
              },
              type: "aggregate_request",
            },
          },
        };
    
        const response = await spansApi.aggregateSpans(requestBody);
    
        if (!response.data || response.data.length === 0) {
          return { buckets: [] };
        }
    
        const buckets: SpanBucket[] = response.data.map((bucket) => ({
          id: bucket.id || "",
          by: bucket.attributes?.by || {},
          compute: bucket.attributes?.compute || {},
          computes: bucket.attributes?.computes || {},
        }));
    
        return {
          buckets,
          elapsed: response.meta?.elapsed,
          requestId: response.meta?.requestId,
          status: response.meta?.status?.toString(),
          warnings: response.meta?.warnings?.map((warning) => ({
            code: warning.code,
            detail: warning.detail,
            title: warning.title,
          })),
        };
      } catch (error: unknown) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        console.error(`Error aggregating spans: ${errorMessage}`);
        throw new Error(`Datadog API error: ${errorMessage}`);
      }
    };
Behavior2/5

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

With no annotations, the description carries full burden but provides minimal behavioral insight. It doesn't disclose whether this is a read-only operation, its performance characteristics, rate limits, or what the aggregation output looks like. The description only states the tool's purpose without behavioral traits.

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 a single, efficient sentence with no wasted words. It's appropriately sized for a tool with a clear name and detailed schema. However, it could be more front-loaded with key details like aggregation type.

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

Completeness2/5

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

For a 6-parameter aggregation tool with no annotations and no output schema, the description is incomplete. It doesn't explain the return format, aggregation metrics, or how results are structured. The schema handles parameters well, but behavioral and output context is missing.

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 fully documents all 6 parameters. The description adds no parameter-specific information beyond what's in the schema. Baseline 3 is appropriate as the schema does the heavy lifting, but the description doesn't compensate or add value.

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

Purpose3/5

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

The description states the tool aggregates Datadog trace spans, which is a clear purpose. However, it doesn't specify what aggregation means (e.g., counting, averaging, summing) or how it differs from sibling tools like search_spans. The verb 'aggregating' is specific but lacks operational detail.

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

Usage Guidelines2/5

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

No guidance is provided on when to use this tool versus alternatives like search_spans. The description doesn't mention any prerequisites, exclusions, or contextual cues for selection. Usage is implied only by the tool name and basic purpose.

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/Nozomuts/datadog-mcp'

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