Skip to main content
Glama
r-huijts
by r-huijts

get_cost_analytics

Retrieve detailed cost analytics data over time to analyze spending patterns, track total costs, and calculate averages per request for API usage monitoring.

Instructions

Retrieve detailed cost analytics data over time, including total costs and averages per request

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
time_of_generation_minYesStart time for the analytics period (ISO8601 format, e.g., '2024-01-01T00:00:00Z')
time_of_generation_maxYesEnd time for the analytics period (ISO8601 format, e.g., '2024-02-01T00:00:00Z')
total_units_minNoMinimum number of total tokens to filter by
total_units_maxNoMaximum number of total tokens to filter by
cost_minNoMinimum cost in cents to filter by
cost_maxNoMaximum cost in cents to filter by
prompt_token_minNoMinimum number of prompt tokens
prompt_token_maxNoMaximum number of prompt tokens
completion_token_minNoMinimum number of completion tokens
completion_token_maxNoMaximum number of completion tokens
status_codeNoFilter by specific HTTP status codes (comma-separated)
weighted_feedback_minNoMinimum weighted feedback score (-10 to 10)
weighted_feedback_maxNoMaximum weighted feedback score (-10 to 10)
virtual_keysNoFilter by specific virtual key slugs (comma-separated)
configsNoFilter by specific config slugs (comma-separated)
workspace_slugNoFilter by specific workspace
api_key_idsNoFilter by specific API key UUIDs (comma-separated)
metadataNoFilter by metadata (stringified JSON object)
ai_org_modelNoFilter by AI provider and model (comma-separated, use __ as separator)
trace_idNoFilter by trace IDs (comma-separated)
span_idNoFilter by span IDs (comma-separated)

Implementation Reference

  • src/index.ts:272-327 (registration)
    MCP tool registration for 'get_cost_analytics', including input schema (Zod), description, and handler function that delegates to PortkeyService
    server.tool(
      "get_cost_analytics",
      "Retrieve detailed cost analytics data over time, including total costs and averages per request",
      {
        time_of_generation_min: z.string().describe("Start time for the analytics period (ISO8601 format, e.g., '2024-01-01T00:00:00Z')"),
        time_of_generation_max: z.string().describe("End time for the analytics period (ISO8601 format, e.g., '2024-02-01T00:00:00Z')"),
        total_units_min: z.number().positive().optional().describe("Minimum number of total tokens to filter by"),
        total_units_max: z.number().positive().optional().describe("Maximum number of total tokens to filter by"),
        cost_min: z.number().positive().optional().describe("Minimum cost in cents to filter by"),
        cost_max: z.number().positive().optional().describe("Maximum cost in cents to filter by"),
        prompt_token_min: z.number().positive().optional().describe("Minimum number of prompt tokens"),
        prompt_token_max: z.number().positive().optional().describe("Maximum number of prompt tokens"),
        completion_token_min: z.number().positive().optional().describe("Minimum number of completion tokens"),
        completion_token_max: z.number().positive().optional().describe("Maximum number of completion tokens"),
        status_code: z.string().optional().describe("Filter by specific HTTP status codes (comma-separated)"),
        weighted_feedback_min: z.number().min(-10).max(10).optional().describe("Minimum weighted feedback score (-10 to 10)"),
        weighted_feedback_max: z.number().min(-10).max(10).optional().describe("Maximum weighted feedback score (-10 to 10)"),
        virtual_keys: z.string().optional().describe("Filter by specific virtual key slugs (comma-separated)"),
        configs: z.string().optional().describe("Filter by specific config slugs (comma-separated)"),
        workspace_slug: z.string().optional().describe("Filter by specific workspace"),
        api_key_ids: z.string().optional().describe("Filter by specific API key UUIDs (comma-separated)"),
        metadata: z.string().optional().describe("Filter by metadata (stringified JSON object)"),
        ai_org_model: z.string().optional().describe("Filter by AI provider and model (comma-separated, use __ as separator)"),
        trace_id: z.string().optional().describe("Filter by trace IDs (comma-separated)"),
        span_id: z.string().optional().describe("Filter by span IDs (comma-separated)")
      },
      async (params) => {
        try {
          const analytics = await portkeyService.getCostAnalytics(params);
          return {
            content: [{ 
              type: "text", 
              text: JSON.stringify({
                summary: {
                  total_cost: analytics.summary.total,
                  average_cost_per_request: analytics.summary.avg
                },
                data_points: analytics.data_points.map(point => ({
                  timestamp: point.timestamp,
                  total_cost: point.total,
                  average_cost: point.avg
                })),
                object: analytics.object
              }, null, 2)
            }]
          };
        } catch (error) {
          return {
            content: [{ 
              type: "text", 
              text: `Error fetching cost analytics: ${error instanceof Error ? error.message : 'Unknown error'}`
            }]
          };
        }
      }
    );
  • Core handler function in PortkeyService that constructs query parameters and fetches cost analytics data from Portkey API endpoint /analytics/graphs/cost
    async getCostAnalytics(params: CostAnalyticsParams): Promise<CostAnalyticsResponse> {
      try {
        const queryParams = new URLSearchParams({
          time_of_generation_min: params.time_of_generation_min,
          time_of_generation_max: params.time_of_generation_max,
          ...(params.total_units_min && { total_units_min: params.total_units_min.toString() }),
          ...(params.total_units_max && { total_units_max: params.total_units_max.toString() }),
          ...(params.cost_min && { cost_min: params.cost_min.toString() }),
          ...(params.cost_max && { cost_max: params.cost_max.toString() }),
          ...(params.prompt_token_min && { prompt_token_min: params.prompt_token_min.toString() }),
          ...(params.prompt_token_max && { prompt_token_max: params.prompt_token_max.toString() }),
          ...(params.completion_token_min && { completion_token_min: params.completion_token_min.toString() }),
          ...(params.completion_token_max && { completion_token_max: params.completion_token_max.toString() }),
          ...(params.status_code && { status_code: params.status_code }),
          ...(params.weighted_feedback_min && { weighted_feedback_min: params.weighted_feedback_min.toString() }),
          ...(params.weighted_feedback_max && { weighted_feedback_max: params.weighted_feedback_max.toString() }),
          ...(params.virtual_keys && { virtual_keys: params.virtual_keys }),
          ...(params.configs && { configs: params.configs }),
          ...(params.workspace_slug && { workspace_slug: params.workspace_slug }),
          ...(params.api_key_ids && { api_key_ids: params.api_key_ids }),
          ...(params.metadata && { metadata: params.metadata }),
          ...(params.ai_org_model && { ai_org_model: params.ai_org_model }),
          ...(params.trace_id && { trace_id: params.trace_id }),
          ...(params.span_id && { span_id: params.span_id })
        });
    
        const response = await fetch(
          `${this.baseUrl}/analytics/graphs/cost?${queryParams.toString()}`,
          {
            method: 'GET',
            headers: {
              'x-portkey-api-key': this.apiKey,
              'Accept': 'application/json'
            }
          }
        );
    
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
    
        return await response.json() as CostAnalyticsResponse;
      } catch (error) {
        console.error('PortkeyService Error:', error);
        throw new Error('Failed to fetch cost analytics from Portkey API');
      }
    }
  • TypeScript interfaces defining input parameters (CostAnalyticsParams), response (CostAnalyticsResponse), data points, and summary for cost analytics
    interface CostDataPoint {
      timestamp: string;
      total: number;
      avg: number;
    }
    
    interface CostSummary {
      total: number;
      avg: number;
    }
    
    interface CostAnalyticsResponse {
      object: 'analytics-graph';
      data_points: CostDataPoint[];
      summary: CostSummary;
    }
    
    interface CostAnalyticsParams {
      time_of_generation_min: string;  // ISO8601 format
      time_of_generation_max: string;  // ISO8601 format
      total_units_min?: number;
      total_units_max?: number;
      cost_min?: number;
      cost_max?: number;
      prompt_token_min?: number;
      prompt_token_max?: number;
      completion_token_min?: number;
      completion_token_max?: number;
      status_code?: string;
      weighted_feedback_min?: number;
      weighted_feedback_max?: number;
      virtual_keys?: string;
      configs?: string;
      workspace_slug?: string;
      api_key_ids?: string;
      metadata?: string;
      ai_org_model?: string;
      trace_id?: string;
      span_id?: string;
    }
  • Zod schema for input validation of the 'get_cost_analytics' tool parameters in MCP registration
    {
      time_of_generation_min: z.string().describe("Start time for the analytics period (ISO8601 format, e.g., '2024-01-01T00:00:00Z')"),
      time_of_generation_max: z.string().describe("End time for the analytics period (ISO8601 format, e.g., '2024-02-01T00:00:00Z')"),
      total_units_min: z.number().positive().optional().describe("Minimum number of total tokens to filter by"),
      total_units_max: z.number().positive().optional().describe("Maximum number of total tokens to filter by"),
      cost_min: z.number().positive().optional().describe("Minimum cost in cents to filter by"),
      cost_max: z.number().positive().optional().describe("Maximum cost in cents to filter by"),
      prompt_token_min: z.number().positive().optional().describe("Minimum number of prompt tokens"),
      prompt_token_max: z.number().positive().optional().describe("Maximum number of prompt tokens"),
      completion_token_min: z.number().positive().optional().describe("Minimum number of completion tokens"),
      completion_token_max: z.number().positive().optional().describe("Maximum number of completion tokens"),
      status_code: z.string().optional().describe("Filter by specific HTTP status codes (comma-separated)"),
      weighted_feedback_min: z.number().min(-10).max(10).optional().describe("Minimum weighted feedback score (-10 to 10)"),
      weighted_feedback_max: z.number().min(-10).max(10).optional().describe("Maximum weighted feedback score (-10 to 10)"),
      virtual_keys: z.string().optional().describe("Filter by specific virtual key slugs (comma-separated)"),
      configs: z.string().optional().describe("Filter by specific config slugs (comma-separated)"),
      workspace_slug: z.string().optional().describe("Filter by specific workspace"),
      api_key_ids: z.string().optional().describe("Filter by specific API key UUIDs (comma-separated)"),
      metadata: z.string().optional().describe("Filter by metadata (stringified JSON object)"),
      ai_org_model: z.string().optional().describe("Filter by AI provider and model (comma-separated, use __ as separator)"),
      trace_id: z.string().optional().describe("Filter by trace IDs (comma-separated)"),
      span_id: z.string().optional().describe("Filter by span IDs (comma-separated)")
    },
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions the tool retrieves data 'over time' and includes specific metrics, but doesn't describe important behaviors: whether this is a read-only operation, if it requires specific permissions, how results are formatted (aggregated vs. raw), pagination, rate limits, or error conditions. For a complex analytics tool with 21 parameters, this is a significant gap.

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

Conciseness4/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 contributes to understanding what the tool does. However, for such a complex tool with many parameters, additional context about usage or behavior might be warranted, making it slightly too concise.

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 the tool's complexity (21 parameters, no output schema, no annotations), the description is inadequate. It doesn't explain the return format, aggregation methods, or how the numerous filtering parameters interact. For an analytics tool that likely returns structured data, the description should provide more context about what 'detailed cost analytics data' actually includes and how it's organized.

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 21 parameters thoroughly. The description adds minimal value beyond the schema - it mentions 'over time' which aligns with the time range parameters, and 'total costs and averages per request' which relates to cost and token parameters. However, it doesn't provide additional context about parameter interactions or filtering logic beyond what's in the schema descriptions.

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 with specific verbs ('retrieve') and resources ('detailed cost analytics data'), including what data is returned ('total costs and averages per request'). However, it doesn't differentiate this tool from potential sibling analytics tools (none are listed as siblings, but the description doesn't mention this uniqueness).

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. There's no mention of prerequisites, appropriate contexts, or comparisons to other tools (like get_user_stats or get_workspace that might provide related data). The agent must infer usage from the tool name and parameters alone.

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/r-huijts/portkey-admin-mcp-server'

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