Skip to main content
Glama
therealsachin

Langfuse MCP Server

top_expensive_traces

Identify high-cost traces within a specified timeframe to analyze spending patterns and optimize resource allocation in Langfuse projects.

Instructions

Find the most expensive traces by cost over a time period.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fromYesStart timestamp (ISO 8601)
toYesEnd timestamp (ISO 8601)
limitNoMaximum number of traces to return (default: 10)
environmentNoOptional environment filter

Implementation Reference

  • Main handler function that implements the tool logic: queries Langfuse API for traces ordered by cost, filters and formats the top expensive ones.
    export async function topExpensiveTraces(
      client: LangfuseAnalyticsClient,
      args: z.infer<typeof topExpensiveTracesSchema>
    ) {
      const tags = args.environment ? [`environment:${args.environment}`] : undefined;
    
      const response = await client.listTraces({
        fromTimestamp: args.from,
        toTimestamp: args.to,
        orderBy: 'totalCost',
        orderDirection: 'desc', // Most expensive first
        limit: args.limit,
        tags,
      });
    
      const traces: ExpensiveTrace[] = [];
    
      // Parse the response data - correct structure based on Langfuse API
      if (response.data && Array.isArray(response.data)) {
        response.data
          .filter((trace: any) => (trace.totalCost || 0) > 0) // Only include traces with cost
          .sort((a: any, b: any) => (b.totalCost || 0) - (a.totalCost || 0)) // Sort by cost descending
          .slice(0, args.limit) // Limit results
          .forEach((trace: any) => {
            traces.push({
              traceId: trace.id,
              name: trace.name || 'Unnamed trace',
              totalCost: trace.totalCost || 0,
              totalTokens: trace.totalTokens || 0,
              timestamp: trace.timestamp || trace.startTime,
              userId: trace.userId,
              tags: trace.tags || [],
              metadata: trace.metadata,
            });
          });
      }
    
      return {
        content: [
          {
            type: 'text' as const,
            text: JSON.stringify(
              {
                projectId: client.getProjectId(),
                from: args.from,
                to: args.to,
                environment: args.environment,
                traces,
              },
              null,
              2
            ),
          },
        ],
      };
    }
  • Zod schema defining the input parameters for the tool.
    export const topExpensiveTracesSchema = z.object({
      from: z.string().datetime(),
      to: z.string().datetime(),
      limit: z.number().optional().default(10),
      environment: z.string().optional(),
    });
  • src/index.ts:1020-1023 (registration)
    Dispatch case in the MCP callToolRequest handler that validates input with schema and invokes the handler function.
    case 'top_expensive_traces': {
      const args = topExpensiveTracesSchema.parse(request.params.arguments);
      return await topExpensiveTraces(this.client, args);
    }
  • src/index.ts:245-273 (registration)
    Tool metadata and input schema exposed in the MCP listToolsRequest handler.
    {
      name: 'top_expensive_traces',
      description:
        'Find the most expensive traces by cost over a time period.',
      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)',
          },
          limit: {
            type: 'number',
            description: 'Maximum number of traces to return (default: 10)',
          },
          environment: {
            type: 'string',
            description: 'Optional environment filter',
          },
        },
        required: ['from', 'to'],
      },
    },
  • src/index.ts:56-56 (registration)
    Import of the handler function and schema into the main server file.
    import { topExpensiveTraces, topExpensiveTracesSchema } from './tools/top-expensive-traces.js';
Behavior2/5

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

No annotations are provided, so the description carries full burden. It mentions 'find' and 'most expensive traces by cost', implying a read-only query, but lacks details on permissions, rate limits, pagination, or output format. For a tool with no annotations and four parameters, this leaves significant behavioral gaps.

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. Every word earns its place with no redundancy or fluff, 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.

Completeness2/5

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

Given no annotations, no output schema, and a tool with four parameters that queries trace data, the description is insufficient. It doesn't explain what 'expensive' means (e.g., monetary cost, latency), how results are ordered, or what the output contains. For a ranking/query tool in this context, more completeness is needed.

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 four parameters. The description adds minimal value beyond the schema by implying time-based filtering and cost ranking, but doesn't explain parameter interactions or default behaviors beyond the schema's 'limit' default. Baseline 3 is appropriate given 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 verb 'find' and resource 'most expensive traces by cost', specifying the ranking criterion. It distinguishes from siblings like 'get_traces' by focusing on cost ranking, though it doesn't explicitly name alternatives. The purpose is specific and actionable.

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 like 'get_traces' or 'usage_by_model'. It mentions a time period requirement but offers no context about prerequisites, exclusions, or comparative use cases with sibling tools. Usage is implied only by the description's scope.

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