Skip to main content
Glama
metrxbots

Metrx MCP Server

by metrxbots

Get Cost Summary

metrx_get_cost_summary
Read-onlyIdempotent

Analyze AI agent fleet costs with total spend, call counts, error rates, and optimization insights for a specified period.

Instructions

Get a comprehensive cost summary for your AI agent fleet. Returns total spend, call counts, error rates, agent breakdown, revenue attribution (if available), and optimization opportunities. Use this as the starting point for understanding your agent economics. Do NOT use for real-time per-request cost checking — use OpenTelemetry spans for that.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
period_daysNoNumber of days to include in the summary (default: 30)

Implementation Reference

  • The main handler implementation for get_cost_summary. This async function (lines 42-60) calls the Metrx API client to fetch dashboard summary data, handles errors, and formats the response using formatDashboard helper. The registration includes input schema (period_days), annotations, and the handler function.
    server.registerTool(
      'get_cost_summary',
      {
        title: 'Get Cost Summary',
        description:
          'Get a comprehensive cost summary for your AI agent fleet. ' +
          'Returns total spend, call counts, error rates, agent breakdown, ' +
          'revenue attribution (if available), and optimization opportunities. ' +
          'Use this as the starting point for understanding your agent economics. ' +
          'Do NOT use for real-time per-request cost checking — use OpenTelemetry spans for that.',
        inputSchema: {
          period_days: z
            .number()
            .int()
            .min(1)
            .max(90)
            .default(30)
            .describe('Number of days to include in the summary (default: 30)'),
        },
        annotations: {
          readOnlyHint: true,
          destructiveHint: false,
          idempotentHint: true,
          openWorldHint: false,
        },
      },
      async ({ period_days }) => {
        const result = await client.get<DashboardSummary>('/dashboard', {
          period_days: period_days ?? 30,
        });
    
        if (result.error) {
          return {
            content: [{ type: 'text', text: `Error fetching cost summary: ${result.error}` }],
            isError: true,
          };
        }
    
        const data = result.data!;
        const text = formatDashboard(data);
    
        return {
          content: [{ type: 'text', text }],
        };
      }
    );
  • DashboardSummary interface defining the output schema for the cost summary. Includes cost breakdown, agent information, revenue attribution, and optimization opportunities data structure.
    export interface DashboardSummary {
      is_preview: boolean;
      stage: string;
      period_days: number;
      agents: { total: number; active: number };
      agents_list: AgentSummary[];
      cost: {
        total_calls: number;
        total_cost_cents: number;
        error_calls: number;
        error_rate: number;
      };
      attribution?: {
        total_outcomes: number;
        total_revenue_cents: number;
        net_value_cents: number;
        roi_multiplier: number;
      };
      optimization?: {
        total_savings_cents: number;
        suggestion_count: number;
        top_suggestion?: string;
      };
    }
  • src/index.ts:79-106 (registration)
    Tool registration and namespace prefixing. Lines 79-103 wrap server.registerTool to add 'metrx_' prefix and rate limiting. Line 106 calls registerDashboardTools which registers get_cost_summary as 'metrx_get_cost_summary'.
    const originalRegisterTool = server.registerTool.bind(server);
    (server as any).registerTool = function (
      name: string,
      config: any,
      handler: (...handlerArgs: any[]) => Promise<any>
    ) {
      const wrappedHandler = async (...handlerArgs: any[]) => {
        if (!rateLimiter.isAllowed(name)) {
          return {
            content: [
              {
                type: 'text' as const,
                text: `Rate limit exceeded for tool '${name}'. Maximum 60 requests per minute allowed.`,
              },
            ],
            isError: true,
          };
        }
        return handler(...handlerArgs);
      };
    
      // Register with metrx_ prefix (only — no deprecated aliases)
      const prefixedName = name.startsWith(METRX_PREFIX) ? name : `${METRX_PREFIX}${name}`;
      originalRegisterTool(prefixedName, config, wrappedHandler);
    };
    
    // ── Register all tool domains ──
    registerDashboardTools(server, apiClient);
  • formatDashboard helper function that converts the DashboardSummary API response into human-readable text format for LLM consumption, including sections for agents, revenue attribution, and optimization opportunities.
    export function formatDashboard(data: DashboardSummary): string {
      const lines: string[] = [
        `## Metrx Dashboard Summary (${data.period_days}-day period)`,
        '',
        `**Agents**: ${data.agents.active} active / ${data.agents.total} total`,
        `**Total LLM Calls**: ${data.cost.total_calls.toLocaleString()}`,
        `**Total Cost**: ${formatCents(data.cost.total_cost_cents)}`,
        `**Error Rate**: ${formatPct(data.cost.error_rate)}`,
      ];
    
      if (data.attribution) {
        lines.push('');
        lines.push('### Revenue Attribution');
        lines.push(`**Outcomes**: ${data.attribution.total_outcomes}`);
        lines.push(`**Revenue**: ${formatCents(data.attribution.total_revenue_cents)}`);
        lines.push(`**Net Value**: ${formatCents(data.attribution.net_value_cents)}`);
        lines.push(`**ROI**: ${data.attribution.roi_multiplier.toFixed(1)}x`);
      }
    
      if (data.optimization) {
        lines.push('');
        lines.push('### Optimization Opportunities');
        lines.push(
          `**Potential Savings**: ${formatCents(data.optimization.total_savings_cents)}/month`
        );
        lines.push(`**Suggestions**: ${data.optimization.suggestion_count}`);
        if (data.optimization.top_suggestion) {
          lines.push(`**Top Suggestion**: ${data.optimization.top_suggestion}`);
        }
      }
    
      if (data.agents_list && data.agents_list.length > 0) {
        lines.push('');
        lines.push('### Agent Breakdown');
        for (const agent of data.agents_list) {
          const cost = agent.monthly_cost_cents ? formatCents(agent.monthly_cost_cents) : 'N/A';
          const roi = agent.roi_multiplier ? `${agent.roi_multiplier.toFixed(1)}x ROI` : 'no ROI data';
          lines.push(`- **${agent.name}** (${agent.status}): ${cost}/mo, ${roi}`);
        }
      }
    
      return lines.join('\n');
    }
  • MetrxApiClient.get method used by the handler to make authenticated GET requests to the /dashboard endpoint. Handles URL construction, retry logic, and error parsing.
    async get<T>(
      path: string,
      params?: Record<string, string | number | boolean>
    ): Promise<ApiResponse<T>> {
      const url = new URL(path, this.baseUrl);
      if (params) {
        for (const [key, value] of Object.entries(params)) {
          if (value !== undefined && value !== null) {
            url.searchParams.set(key, String(value));
          }
        }
      }
    
      try {
        const response = await this.fetchWithRetry(url.toString(), {
          method: 'GET',
          headers: {
            Authorization: `Bearer ${this.apiKey}`,
            'Content-Type': 'application/json',
            'X-MCP-Client': 'metrx-mcp-server/0.1.0',
          },
        });
    
        if (!response.ok) {
          const errorBody = await response.text().catch(() => '');
          const friendlyMessage = this.parseApiError(response.status, errorBody);
          return {
            error: friendlyMessage,
          };
        }
    
        const data = (await response.json()) as T | ApiResponse<T>;
    
        // API may return { data: T } or T directly
        if (data && typeof data === 'object' && 'data' in data) {
          return data as ApiResponse<T>;
        }
    
        return { data: data as T };
      } catch (err) {
        return {
          error: `Network error: ${err instanceof Error ? err.message : String(err)}. See ${API_DOCS_URL} for help`,
        };
      }
    }
Behavior4/5

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

Annotations already indicate this is a read-only, idempotent, non-destructive operation with closed-world data. The description adds valuable context beyond annotations by specifying the scope ('comprehensive cost summary for your AI agent fleet'), mentioning data availability constraints ('revenue attribution (if available)'), and hinting at optimization insights. No contradiction with annotations exists.

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 efficiently structured in three sentences: the first states purpose and return data, the second provides usage context, and the third gives an explicit exclusion. Every sentence adds essential information without redundancy or fluff, making it front-loaded and appropriately sized.

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

Completeness4/5

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

Given the tool's moderate complexity (single parameter, no output schema), the description is largely complete. It covers purpose, usage guidelines, and behavioral context well. However, without an output schema, it could benefit from more detail on the structure of returned data (e.g., format of 'optimization opportunities'), though the listed data points provide reasonable clarity.

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?

The input schema has 100% description coverage for its single parameter 'period_days', fully documenting its type, range, and default. The description doesn't add any parameter-specific details beyond what the schema provides, so it meets the baseline of 3 for high schema coverage without extra value.

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 explicitly states the tool retrieves a 'comprehensive cost summary for your AI agent fleet' and lists specific data points returned (total spend, call counts, error rates, etc.). It clearly distinguishes from siblings like 'metrx_get_agent_detail' or 'metrx_get_budget_status' by focusing on aggregated fleet-wide economics rather than granular details or budget-specific metrics.

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

Usage Guidelines5/5

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

The description provides explicit guidance: 'Use this as the starting point for understanding your agent economics' and 'Do NOT use for real-time per-request cost checking — use OpenTelemetry spans for that.' This clearly defines when to use this tool (high-level economic analysis) and when to use alternatives (real-time monitoring via other systems), directly addressing sibling differentiation.

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/metrxbots/metrx-mcp-server'

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