Skip to main content
Glama
metrxbots

Metrx MCP Server

by metrxbots

metrx_get_cost_summary

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`,
        };
      }
    }

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