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

get_user_stats

Retrieve user analytics data including request counts and costs within a specified time range, with filtering options for detailed insights.

Instructions

Retrieve detailed analytics data about user activity within a specified time range, including request counts and costs

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
status_codeNoFilter by specific HTTP status codes (comma-separated)
virtual_keysNoFilter by specific virtual key slugs (comma-separated)
page_sizeNoNumber of results per page (for pagination)

Implementation Reference

  • The inline handler function for the 'get_user_stats' tool that delegates to PortkeyService.getUserGroupedData and returns formatted JSON response or error.
    async (params) => {
      try {
        const stats = await portkeyService.getUserGroupedData(params);
        return {
          content: [{ 
            type: "text", 
            text: JSON.stringify(stats, null, 2)
          }]
        };
      } catch (error) {
        return {
          content: [{ 
            type: "text", 
            text: `Error fetching user statistics: ${error instanceof Error ? error.message : 'Unknown error'}`
          }]
        };
      }
    }
  • Zod schema defining the input parameters for the get_user_stats tool.
    {
      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"),
      status_code: z.string().optional().describe("Filter by specific HTTP status codes (comma-separated)"),
      virtual_keys: z.string().optional().describe("Filter by specific virtual key slugs (comma-separated)"),
      page_size: z.number().positive().optional().describe("Number of results per page (for pagination)")
    },
  • src/index.ts:77-109 (registration)
    Registration of the 'get_user_stats' tool using McpServer.tool method, including name, description, schema, and handler.
    server.tool(
      "get_user_stats",
      "Retrieve detailed analytics data about user activity within a specified time range, including request counts and costs",
      {
        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"),
        status_code: z.string().optional().describe("Filter by specific HTTP status codes (comma-separated)"),
        virtual_keys: z.string().optional().describe("Filter by specific virtual key slugs (comma-separated)"),
        page_size: z.number().positive().optional().describe("Number of results per page (for pagination)")
      },
      async (params) => {
        try {
          const stats = await portkeyService.getUserGroupedData(params);
          return {
            content: [{ 
              type: "text", 
              text: JSON.stringify(stats, null, 2)
            }]
          };
        } catch (error) {
          return {
            content: [{ 
              type: "text", 
              text: `Error fetching user statistics: ${error instanceof Error ? error.message : 'Unknown error'}`
            }]
          };
        }
      }
    );
  • Core helper method in PortkeyService that makes the API request to Portkey's /analytics/groups/users endpoint to retrieve user stats data.
    async getUserGroupedData(params: UserGroupedDataParams): Promise<UserGroupedData> {
      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() }),
          // Add other optional parameters as needed
        });
    
        const response = await fetch(
          `${this.baseUrl}/analytics/groups/users?${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 UserGroupedData;
      } catch (error) {
        console.error('PortkeyService Error:', error);
        throw new Error('Failed to fetch user grouped data from Portkey API');
      }
    }
Behavior2/5

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

With no annotations, the description carries full burden but provides minimal behavioral insight. It mentions retrieval of analytics data but doesn't disclose pagination behavior (implied by 'page_size' parameter), rate limits, authentication requirements, or whether the operation is read-only (implied by 'retrieve'). The description adds little beyond the basic operation.

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, well-structured sentence that efficiently conveys the core purpose without redundancy. It front-loads key information ('retrieve detailed analytics data') and uses precise terminology, with no wasted words or unnecessary elaboration.

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?

For a 9-parameter analytics tool with no annotations and no output schema, the description is inadequate. It doesn't explain the return format, pagination behavior, error conditions, or how filters interact. The agent lacks sufficient context to use this tool effectively beyond basic parameter passing.

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 9 parameters. The description adds no parameter-specific details beyond implying time-range filtering, which is already covered in the schema. Baseline score of 3 is appropriate as the schema does the heavy lifting, but the description doesn't enhance parameter understanding.

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 ('retrieve') and resource ('detailed analytics data about user activity'), specifying the data types ('request counts and costs') and temporal scope ('within a specified time range'). It distinguishes from siblings like 'get_cost_analytics' by focusing on user-level metrics rather than cost aggregation, though the distinction could be more explicit.

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?

No guidance is provided on when to use this tool versus alternatives like 'get_cost_analytics' or 'list_all_users'. The description mentions a time range but doesn't specify prerequisites, exclusions, or comparative use cases with sibling tools, leaving the agent to infer usage context.

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