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');
      }
    }

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