Skip to main content
Glama
dragonkhoi

mixpanel

aggregate_event_counts

Analyze event trends over time by fetching unique, general, or average data for specific events. Supports granularity in minutes, hours, days, weeks, or months for trend analysis and performance comparisons.

Instructions

Get unique, general, or average data for a set of events over N days, weeks, or months. Useful for trend analysis, comparing event performance over time, and creating time-series visualizations.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
eventYesThe event or events that you wish to get data for, a string encoded as a JSON array. Example format: "["play song", "log in", "add playlist"]"
from_dateNoThe date in yyyy-mm-dd format to begin querying from (inclusive)
intervalNoThe number of units to return data for. Specify either interval or from_date and to_date
project_idNoThe Mixpanel project ID. Optional since it has a default.
to_dateNoThe date in yyyy-mm-dd format to query to (inclusive)
typeNoThe type of data to fetch, either general, unique, or average, defaults to general
unitYesThe level of granularity of the data you get back

Implementation Reference

  • The handler function that implements the tool logic: authenticates with Mixpanel using service account credentials, validates and parses input parameters (especially the JSON array of events), constructs query parameters for the /api/query/events endpoint, performs a GET request, parses the JSON response, and returns formatted content or error.
    async ({ project_id = DEFAULT_PROJECT_ID, event, type = "general", unit, interval, from_date, to_date }) => {
      try {
        // Create authorization header using base64 encoding of credentials
        const credentials = `${SERVICE_ACCOUNT_USER_NAME}:${SERVICE_ACCOUNT_PASSWORD}`;
        const encodedCredentials = Buffer.from(credentials).toString('base64');
        
        // Validate parameters
        if (!interval && (!from_date || !to_date)) {
          throw new Error("You must specify either interval or both from_date and to_date");
        }
        
        // Parse events to ensure it's a valid JSON array
        let parsedEvents;
        try {
          parsedEvents = JSON.parse(event);
          if (!Array.isArray(parsedEvents)) {
            throw new Error("Events must be a JSON array");
          }
        } catch (e: any) {
          throw new Error(`Invalid events format: ${e.message}`);
        }
        
        // Build query parameters
        const queryParams = new URLSearchParams({
          project_id: project_id || '',
          type: type,
          unit: unit
        });
        
        // Add either interval or date range
        if (interval) {
          queryParams.append('interval', interval.toString());
        } else {
          queryParams.append('from_date', from_date || '');
          queryParams.append('to_date', to_date || '');
        }
        
        // Add events parameter
        queryParams.append('event', event);
        
        // Construct URL with query parameters
        const url = `https://mixpanel.com/api/query/events?${queryParams.toString()}`;
        
        // Set up request options
        const options = {
          method: 'GET',
          headers: {
            'accept': 'application/json',
            'authorization': `Basic ${encodedCredentials}`
          }
        };
        
        // Make the API request
        const response = await fetch(url, options);
        
        if (!response.ok) {
          const errorText = await response.text();
          throw new Error(`HTTP error! status: ${response.status} - ${errorText}`);
        }
        
        const data = await response.json();
        
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(data)
            }
          ]
        };
      } catch (error: unknown) {
        console.error("Error fetching Mixpanel event counts:", error);
        const errorMessage = error instanceof Error ? error.message : String(error);
        return {
          content: [
            {
              type: "text",
              text: `Error fetching Mixpanel event counts: ${errorMessage}`
            }
          ],
          isError: true
        };
      }
    }
  • Zod schema defining the input parameters for the tool, including project_id (optional), event (JSON string array), type, unit, interval/from_date/to_date options.
    {
      project_id: z.string().describe("The Mixpanel project ID. Optional since it has a default.").optional(),
      event: z.string().describe("The event or events that you wish to get data for, a string encoded as a JSON array. Example format: \"[\"play song\", \"log in\", \"add playlist\"]\""),
      type: z.enum(["general", "unique", "average"]).describe("The type of data to fetch, either general, unique, or average, defaults to general").optional(),
      unit: z.enum(["minute", "hour", "day", "week", "month"]).describe("The level of granularity of the data you get back"),
      interval: z.number().optional().describe("The number of units to return data for. Specify either interval or from_date and to_date"),
      from_date: z.string().optional().describe("The date in yyyy-mm-dd format to begin querying from (inclusive)"),
      to_date: z.string().optional().describe("The date in yyyy-mm-dd format to query to (inclusive)"),
    },
  • src/index.ts:207-303 (registration)
    The server.tool() call that registers the 'aggregate_event_counts' tool with its description, input schema, and handler function on the MCP server.
    server.tool(
      "aggregate_event_counts",
      "Get unique, general, or average data for a set of events over N days, weeks, or months. Useful for trend analysis, comparing event performance over time, and creating time-series visualizations.",
      {
        project_id: z.string().describe("The Mixpanel project ID. Optional since it has a default.").optional(),
        event: z.string().describe("The event or events that you wish to get data for, a string encoded as a JSON array. Example format: \"[\"play song\", \"log in\", \"add playlist\"]\""),
        type: z.enum(["general", "unique", "average"]).describe("The type of data to fetch, either general, unique, or average, defaults to general").optional(),
        unit: z.enum(["minute", "hour", "day", "week", "month"]).describe("The level of granularity of the data you get back"),
        interval: z.number().optional().describe("The number of units to return data for. Specify either interval or from_date and to_date"),
        from_date: z.string().optional().describe("The date in yyyy-mm-dd format to begin querying from (inclusive)"),
        to_date: z.string().optional().describe("The date in yyyy-mm-dd format to query to (inclusive)"),
      },
      async ({ project_id = DEFAULT_PROJECT_ID, event, type = "general", unit, interval, from_date, to_date }) => {
        try {
          // Create authorization header using base64 encoding of credentials
          const credentials = `${SERVICE_ACCOUNT_USER_NAME}:${SERVICE_ACCOUNT_PASSWORD}`;
          const encodedCredentials = Buffer.from(credentials).toString('base64');
          
          // Validate parameters
          if (!interval && (!from_date || !to_date)) {
            throw new Error("You must specify either interval or both from_date and to_date");
          }
          
          // Parse events to ensure it's a valid JSON array
          let parsedEvents;
          try {
            parsedEvents = JSON.parse(event);
            if (!Array.isArray(parsedEvents)) {
              throw new Error("Events must be a JSON array");
            }
          } catch (e: any) {
            throw new Error(`Invalid events format: ${e.message}`);
          }
          
          // Build query parameters
          const queryParams = new URLSearchParams({
            project_id: project_id || '',
            type: type,
            unit: unit
          });
          
          // Add either interval or date range
          if (interval) {
            queryParams.append('interval', interval.toString());
          } else {
            queryParams.append('from_date', from_date || '');
            queryParams.append('to_date', to_date || '');
          }
          
          // Add events parameter
          queryParams.append('event', event);
          
          // Construct URL with query parameters
          const url = `https://mixpanel.com/api/query/events?${queryParams.toString()}`;
          
          // Set up request options
          const options = {
            method: 'GET',
            headers: {
              'accept': 'application/json',
              'authorization': `Basic ${encodedCredentials}`
            }
          };
          
          // Make the API request
          const response = await fetch(url, options);
          
          if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`HTTP error! status: ${response.status} - ${errorText}`);
          }
          
          const data = await response.json();
          
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(data)
              }
            ]
          };
        } catch (error: unknown) {
          console.error("Error fetching Mixpanel event counts:", error);
          const errorMessage = error instanceof Error ? error.message : String(error);
          return {
            content: [
              {
                type: "text",
                text: `Error fetching Mixpanel event counts: ${errorMessage}`
              }
            ],
            isError: true
          };
        }
      }
    )
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions the tool is for 'trend analysis' and 'time-series visualizations,' which hints at read-only, analytical use, but does not explicitly state whether it's read-only, its permissions, rate limits, or what the output format looks like (e.g., pagination, error handling). For a tool with 7 parameters and no annotation coverage, this is a significant gap in transparency.

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 efficiently structured in two sentences: the first states the purpose, and the second provides usage context. It is front-loaded with key information and avoids unnecessary details, though it could be slightly more concise by integrating the two sentences more tightly.

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 (7 parameters, no output schema, no annotations), the description is incomplete. It lacks details on behavioral traits (e.g., read-only status, error conditions), output format, and explicit differentiation from sibling tools. While the schema covers parameters well, the description does not compensate for the absence of annotations and output schema, making it inadequate for full contextual understanding.

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 schema description coverage is 100%, meaning all parameters are well-documented in the input schema itself (e.g., 'event' as a JSON array, 'type' with enum values). The description adds minimal value beyond the schema by mentioning 'unique, general, or average data' (which aligns with the 'type' enum) and 'over N days, weeks, or months' (hinting at 'interval' and 'unit'), but does not provide additional syntax or format details. Baseline 3 is appropriate when the schema does the heavy lifting.

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: 'Get unique, general, or average data for a set of events over N days, weeks, or months.' It specifies the verb ('Get'), resource ('data for a set of events'), and scope ('over N days, weeks, or months'), but does not explicitly differentiate it from sibling tools like 'query_segmentation_report' or 'query_insights_report', which may also involve event data analysis.

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

Usage Guidelines3/5

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

The description provides implied usage guidance by stating it's 'Useful for trend analysis, comparing event performance over time, and creating time-series visualizations.' However, it does not explicitly mention when to use this tool versus alternatives among the many sibling tools (e.g., 'query_frequency_report' or 'get_top_events'), nor does it specify any prerequisites or exclusions.

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

Related 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/dragonkhoi/mixpanel-mcp'

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