Skip to main content
Glama
therealsachin

Langfuse MCP Server

get_metrics

Query aggregated metrics like costs, tokens, and counts from Langfuse analytics with flexible filtering and grouping options to analyze usage data.

Instructions

Query aggregated metrics (costs, tokens, counts) with flexible filtering and dimensions.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fromYesStart timestamp (ISO 8601)
toYesEnd timestamp (ISO 8601)
viewNoData view to query (default: traces)
metricsNoMetrics to aggregate
dimensionsNoDimensions to group by
environmentNoOptional environment filter

Implementation Reference

  • The core handler function that executes the get_metrics tool: validates args, calls Langfuse client.getMetrics, processes and aggregates the response data, and returns formatted JSON.
    export async function getMetrics(
      client: LangfuseAnalyticsClient,
      args: z.infer<typeof getMetricsSchema>
    ) {
      const filters: any[] = args.filters || [];
    
      // Add environment filter if specified
      if (args.environment) {
        filters.push({
          column: 'environment',
          operator: 'equals',
          value: args.environment,
          type: 'string',
        });
      }
    
      const response = await client.getMetrics({
        view: args.view,
        from: args.from,
        to: args.to,
        metrics: args.metrics,
        dimensions: args.dimensions,
        filters,
      });
    
      // Process the response into a structured format
      const metricsResult: MetricsResponse = {
        projectId: client.getProjectId(),
        from: args.from,
        to: args.to,
        view: args.view,
        metrics: [],
        dimensions: [],
      };
    
      // Parse metrics data from response
      if (response.data && Array.isArray(response.data)) {
        // Aggregate metrics across all rows
        const aggregatedMetrics: Record<string, number> = {};
    
        response.data.forEach((row: any) => {
          args.metrics.forEach(metric => {
            const key = `${metric.measure}_${metric.aggregation}`;
            // Metrics API returns aggregated field names like 'totalCost_sum', 'count_count'
            const aggregatedFieldName = `${metric.measure}_${metric.aggregation}`;
            if (row[aggregatedFieldName] !== undefined) {
              if (metric.aggregation === 'sum' || metric.aggregation === 'count') {
                aggregatedMetrics[key] = (aggregatedMetrics[key] || 0) + (row[aggregatedFieldName] || 0);
              } else if (metric.aggregation === 'avg') {
                // For average, we'll need to handle this differently
                aggregatedMetrics[key] = row[aggregatedFieldName] || 0;
              }
            }
          });
        });
    
        // Convert aggregated metrics to result format
        metricsResult.metrics = Object.entries(aggregatedMetrics).map(([key, value]) => {
          const [measure, aggregation] = key.split('_');
          return { measure, aggregation, value };
        });
    
        // Extract dimension data if present
        if (args.dimensions && response.data.length > 0) {
          const dimensions = new Set<string>();
          response.data.forEach((row: any) => {
            args.dimensions?.forEach(dim => {
              if (row[dim.field] !== undefined) {
                dimensions.add(`${dim.field}:${row[dim.field]}`);
              }
            });
          });
    
          metricsResult.dimensions = Array.from(dimensions).map(dimStr => {
            const [field, value] = dimStr.split(':');
            return { field, value };
          });
        }
      }
    
      return {
        content: [
          {
            type: 'text' as const,
            text: JSON.stringify(metricsResult, null, 2),
          },
        ],
      };
    }
  • Zod schema defining the input parameters for the get_metrics tool, used for validation in the handler and dispatcher.
    export const getMetricsSchema = z.object({
      from: z.string().datetime(),
      to: z.string().datetime(),
      view: z.enum(['traces', 'observations']).default('traces'),
      metrics: z.array(z.object({
        measure: z.string(),
        aggregation: z.string(),
      })).default([
        { measure: 'totalCost', aggregation: 'sum' },
        { measure: 'totalTokens', aggregation: 'sum' },
        { measure: 'count', aggregation: 'count' },
      ]),
      dimensions: z.array(z.object({
        field: z.string(),
      })).optional(),
      filters: z.array(z.object({
        column: z.string(),
        operator: z.string(),
        value: z.any(),
        type: z.string().optional(),
      })).optional(),
      environment: z.string().optional(),
    });
  • src/index.ts:1036-1039 (registration)
    Tool registration in the main switch dispatcher: parses arguments with schema and invokes the getMetrics handler.
    case 'get_metrics': {
      const args = getMetricsSchema.parse(request.params.arguments);
      return await getMetrics(this.client, args);
    }
  • src/index.ts:298-346 (registration)
    Tool metadata registration including name, description, and JSON inputSchema in the listTools response.
    {
      name: 'get_metrics',
      description: 'Query aggregated metrics (costs, tokens, counts) with flexible filtering and dimensions.',
      inputSchema: {
        type: 'object',
        properties: {
          from: {
            type: 'string',
            format: 'date-time',
            description: 'Start timestamp (ISO 8601)',
          },
          to: {
            type: 'string',
            format: 'date-time',
            description: 'End timestamp (ISO 8601)',
          },
          view: {
            type: 'string',
            enum: ['traces', 'observations'],
            description: 'Data view to query (default: traces)',
          },
          metrics: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                measure: { type: 'string' },
                aggregation: { type: 'string' },
              },
            },
            description: 'Metrics to aggregate',
          },
          dimensions: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                field: { type: 'string' },
              },
            },
            description: 'Dimensions to group by',
          },
          environment: {
            type: 'string',
            description: 'Optional environment filter',
          },
        },
        required: ['from', 'to'],
      },
  • src/index.ts:59-59 (registration)
    Import statement bringing in the getMetrics handler and schema from the tool module.
    import { getMetrics, getMetricsSchema } from './tools/get-metrics.js';
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions 'query aggregated metrics' and 'flexible filtering and dimensions', which implies a read-only operation, but doesn't clarify permissions, rate limits, pagination, or response format. For a tool with 6 parameters and no output schema, this leaves significant behavioral aspects undocumented.

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

Conciseness5/5

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

The description is a single, efficient sentence that front-loads the core purpose ('Query aggregated metrics') and adds qualifying details without waste. Every word earns its place, making it easy to parse quickly while conveying essential information.

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 tool's complexity (6 parameters, no output schema, no annotations), the description is minimally adequate. It states what the tool does but lacks guidance on usage, behavioral details, and output expectations. With no annotations to fill gaps, the description should do more to compensate, but it at least provides a clear starting point.

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 parameters thoroughly. The description adds minimal value beyond the schema by hinting at 'flexible filtering and dimensions', which loosely relates to the 'dimensions' and 'environment' parameters, but doesn't provide additional syntax or usage details. This meets the baseline for high schema coverage.

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

Purpose4/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: 'Query aggregated metrics (costs, tokens, counts) with flexible filtering and dimensions.' It specifies the verb ('query'), resource ('aggregated metrics'), and scope ('costs, tokens, counts'), making it easy to understand what the tool does. However, it doesn't explicitly differentiate from sibling tools like 'get_daily_metrics' or 'usage_by_model', which appear to be related metrics tools.

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?

The description provides no guidance on when to use this tool versus alternatives. It mentions 'flexible filtering and dimensions' but doesn't specify scenarios, prerequisites, or exclusions. With multiple sibling tools that seem related to metrics (e.g., 'get_daily_metrics', 'usage_by_model'), the lack of differentiation leaves the agent guessing about appropriate use cases.

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/therealsachin/langfuse-mcp'

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