Skip to main content
Glama
therealsachin

Langfuse MCP Server

usage_by_service

Analyze usage and cost breakdown by service or feature tag over a specified time period to identify spending patterns and optimize resource allocation.

Instructions

Analyze usage and cost by service/feature tag over a time period.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fromYesStart timestamp (ISO 8601)
toYesEnd timestamp (ISO 8601)
serviceTagKeyNoTag key for service identification (default: "service")
environmentNoOptional environment filter
limitNoMaximum number of services to return (default: 20)

Implementation Reference

  • The core handler function implementing the usage_by_service tool. It queries trace metrics grouped by tags, extracts service names from tags (e.g., 'service:chatbot'), aggregates cost/tokens/count per service, sorts by cost, and returns formatted JSON.
    export async function usageByService(
      client: LangfuseAnalyticsClient,
      args: z.infer<typeof usageByServiceSchema>
    ) {
      const filters: any[] = [];
    
      if (args.environment) {
        filters.push({
          column: 'environment',
          operator: 'equals',
          value: args.environment,
          type: 'string',
        });
      }
    
      const response = await client.getMetrics({
        view: 'traces',
        from: args.from,
        to: args.to,
        metrics: [
          { measure: 'totalCost', aggregation: 'sum' },
          { measure: 'totalTokens', aggregation: 'sum' },
          { measure: 'count', aggregation: 'count' },
        ],
        dimensions: [{ field: 'tags' }],
        filters,
      });
    
      // Post-process to extract service from tags
      const serviceMap = new Map<string, ServiceUsage>();
    
      if (response.data && Array.isArray(response.data)) {
        response.data.forEach((row: any) => {
          const tags = Array.isArray(row.tags) ? row.tags : [];
    
          // Find service tag
          const serviceTag = tags.find((tag: string) =>
            typeof tag === 'string' && tag.startsWith(`${args.serviceTagKey}:`)
          );
    
          if (serviceTag) {
            const service = serviceTag.split(':')[1];
            const existing = serviceMap.get(service) || {
              service,
              totalCost: 0,
              totalTokens: 0,
              traceCount: 0,
            };
    
            serviceMap.set(service, {
              service,
              totalCost: existing.totalCost + (row.totalCost_sum || 0),
              totalTokens: existing.totalTokens + (row.totalTokens_sum || 0),
              traceCount: existing.traceCount + (row.count_count || 0),
            });
          }
        });
      }
    
      const serviceUsages = Array.from(serviceMap.values())
        .sort((a, b) => b.totalCost - a.totalCost)
        .slice(0, args.limit);
    
      return {
        content: [
          {
            type: 'text' as const,
            text: JSON.stringify(
              {
                projectId: client.getProjectId(),
                from: args.from,
                to: args.to,
                serviceTagKey: args.serviceTagKey,
                services: serviceUsages,
              },
              null,
              2
            ),
          },
        ],
      };
    }
  • Zod input schema defining parameters for the usage_by_service tool: datetime range, service tag key, optional environment filter and limit.
    export const usageByServiceSchema = z.object({
      from: z.string().datetime(),
      to: z.string().datetime(),
      serviceTagKey: z.string().default('service'),
      environment: z.string().optional(),
      limit: z.number().optional().default(20),
    });
  • src/index.ts:1015-1018 (registration)
    Registration in the main tool dispatcher switch statement: parses arguments using the schema and invokes the handler.
    case 'usage_by_service': {
      const args = usageByServiceSchema.parse(request.params.arguments);
      return await usageByService(this.client, args);
    }
  • src/index.ts:212-244 (registration)
    Tool metadata registration in the listTools response, including name, description, and input schema for client discovery.
    {
      name: 'usage_by_service',
      description:
        'Analyze usage and cost by service/feature tag 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)',
          },
          serviceTagKey: {
            type: 'string',
            description: 'Tag key for service identification (default: "service")',
          },
          environment: {
            type: 'string',
            description: 'Optional environment filter',
          },
          limit: {
            type: 'number',
            description: 'Maximum number of services to return (default: 20)',
          },
        },
        required: ['from', 'to'],
      },
    },
  • src/index.ts:55-55 (registration)
    Import statement bringing in the handler function and schema for use in the server.
    import { usageByService, usageByServiceSchema } from './tools/usage-by-service.js';

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-server'

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