Skip to main content
Glama
dragonkhoi

mixpanel

query_segmentation_sum

Sum numeric expressions for events over time in Mixpanel to calculate revenue metrics, track cumulative totals, and aggregate quantitative values across specified time periods.

Instructions

Sum a numeric expression for events over time. Useful for calculating revenue metrics, aggregating quantitative values, and tracking cumulative totals across different time periods.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
eventYesThe event that you wish to get data for (single event name, not an array)
from_dateYesThe date in yyyy-mm-dd format to begin querying from (inclusive)
onYesThe expression to sum per unit time (should result in a numeric value)
project_idNoThe Mixpanel project ID. Optional since it has a default.
to_dateYesThe date in yyyy-mm-dd format to query to (inclusive)
unitNoTime bucket size: 'hour' or 'day'. Default is 'day'
whereNoAn expression to filter events by based on the grammar: <expression> ::= 'properties["' <property> '"]' | <expression> <binary op> <expression> | <unary op> <expression> | <math op> '(' <expression> ')' | <string literal> <binary op> ::= '+' | '-' | '*' | '/' | '%' | '==' | '!=' | '>' | '>=' | '<' | '<=' | 'in' | 'and' | 'or' | <unary op> ::= '-' | 'not'
workspace_idNoThe ID of the workspace if applicable

Implementation Reference

  • src/index.ts:855-932 (registration)
    Registration of the 'query_segmentation_sum' MCP tool using server.tool(), including name, description, input schema, and handler function.
      "query_segmentation_sum",
      "Sum a numeric expression for events over time. Useful for calculating revenue metrics, aggregating quantitative values, and tracking cumulative totals across different time periods.",
      {
        project_id: z.string().describe("The Mixpanel project ID. Optional since it has a default.").optional(),
        workspace_id: z.string().optional().describe("The ID of the workspace if applicable"),
        event: z.string().describe("The event that you wish to get data for (single event name, not an array)"),
        from_date: z.string().describe("The date in yyyy-mm-dd format to begin querying from (inclusive)"),
        to_date: z.string().describe("The date in yyyy-mm-dd format to query to (inclusive)"),
        on: z.string().describe("The expression to sum per unit time (should result in a numeric value)"),
        unit: z.enum(["hour", "day"]).optional().describe("Time bucket size: 'hour' or 'day'. Default is 'day'"),
        where: z.string().optional().describe(`An expression to filter events by based on the grammar: <expression> ::= 'properties["' <property> '"]'
                    | <expression> <binary op> <expression>
                    | <unary op> <expression>
                    | <math op> '(' <expression> ')'
                    | <string literal>
       <binary op> ::= '+' | '-' | '*' | '/' | '%' | '==' | '!=' |
                      '>' | '>=' | '<' | '<=' | 'in' | 'and' | 'or'
                    | <unary op> ::= '-' | 'not'`),
      },
      async ({ project_id = DEFAULT_PROJECT_ID, workspace_id, event, from_date, to_date, on, unit, where }) => {
        try {
          const credentials = `${SERVICE_ACCOUNT_USER_NAME}:${SERVICE_ACCOUNT_PASSWORD}`;
          const encodedCredentials = Buffer.from(credentials).toString('base64');
          
          const queryParams = new URLSearchParams({
            project_id: project_id || '',
            event: event,
            from_date: from_date,
            to_date: to_date,
            on: on
          });
          
          if (workspace_id) queryParams.append('workspace_id', workspace_id);
          if (unit) queryParams.append('unit', unit);
          if (where) queryParams.append('where', where);
          
          const url = `https://mixpanel.com/api/query/segmentation/sum?${queryParams.toString()}`;
          
          const options = {
            method: 'GET',
            headers: {
              'accept': 'application/json',
              'authorization': `Basic ${encodedCredentials}`
            }
          };
          
          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 segmentation sum data:", error);
          const errorMessage = error instanceof Error ? error.message : String(error);
          return {
            content: [
              {
                type: "text",
                text: `Error fetching Mixpanel segmentation sum data: ${errorMessage}`
              }
            ],
            isError: true
          };
        }
      }
    );
  • The core handler logic that authenticates with Mixpanel using service account credentials, builds the query URL for the /segmentation/sum endpoint, fetches the data, and returns the JSON response or error.
    async ({ project_id = DEFAULT_PROJECT_ID, workspace_id, event, from_date, to_date, on, unit, where }) => {
      try {
        const credentials = `${SERVICE_ACCOUNT_USER_NAME}:${SERVICE_ACCOUNT_PASSWORD}`;
        const encodedCredentials = Buffer.from(credentials).toString('base64');
        
        const queryParams = new URLSearchParams({
          project_id: project_id || '',
          event: event,
          from_date: from_date,
          to_date: to_date,
          on: on
        });
        
        if (workspace_id) queryParams.append('workspace_id', workspace_id);
        if (unit) queryParams.append('unit', unit);
        if (where) queryParams.append('where', where);
        
        const url = `https://mixpanel.com/api/query/segmentation/sum?${queryParams.toString()}`;
        
        const options = {
          method: 'GET',
          headers: {
            'accept': 'application/json',
            'authorization': `Basic ${encodedCredentials}`
          }
        };
        
        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 segmentation sum data:", error);
        const errorMessage = error instanceof Error ? error.message : String(error);
        return {
          content: [
            {
              type: "text",
              text: `Error fetching Mixpanel segmentation sum data: ${errorMessage}`
            }
          ],
          isError: true
        };
      }
    }
  • Zod input schema validating parameters like project_id, event, dates, 'on' expression for summing, unit, and optional where filter.
    {
      project_id: z.string().describe("The Mixpanel project ID. Optional since it has a default.").optional(),
      workspace_id: z.string().optional().describe("The ID of the workspace if applicable"),
      event: z.string().describe("The event that you wish to get data for (single event name, not an array)"),
      from_date: z.string().describe("The date in yyyy-mm-dd format to begin querying from (inclusive)"),
      to_date: z.string().describe("The date in yyyy-mm-dd format to query to (inclusive)"),
      on: z.string().describe("The expression to sum per unit time (should result in a numeric value)"),
      unit: z.enum(["hour", "day"]).optional().describe("Time bucket size: 'hour' or 'day'. Default is 'day'"),
      where: z.string().optional().describe(`An expression to filter events by based on the grammar: <expression> ::= 'properties["' <property> '"]'
                  | <expression> <binary op> <expression>
                  | <unary op> <expression>
                  | <math op> '(' <expression> ')'
                  | <string literal>
     <binary op> ::= '+' | '-' | '*' | '/' | '%' | '==' | '!=' |
                    '>' | '>=' | '<' | '<=' | 'in' | 'and' | 'or'
                  | <unary op> ::= '-' | 'not'`),
    },
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. While it mentions the tool sums numeric expressions over time, it doesn't describe critical behaviors: whether this is a read-only operation, what permissions are required, how results are formatted (e.g., time-series data), if there are rate limits, or error conditions. The description adds minimal context 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.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized with two sentences. The first sentence states the core purpose, and the second provides usage examples. There's no wasted text, and it's front-loaded with the essential function. However, it could be slightly more structured by explicitly separating purpose from guidelines.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (8 parameters, no output schema, no annotations), the description is moderately complete. It covers the basic purpose and usage examples but lacks behavioral details (e.g., output format, error handling) and explicit differentiation from siblings. For a tool with rich parameter documentation but no other structured context, this leaves gaps in guiding the agent effectively.

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 8 parameters thoroughly. The description doesn't add any parameter-specific information beyond what's in the schema (e.g., it doesn't explain the 'on' parameter's syntax or provide examples for the 'where' expression). With high schema coverage, the baseline is 3 even without param details in the description.

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: 'Sum a numeric expression for events over time.' It specifies the verb ('sum'), resource ('numeric expression for events'), and scope ('over time'). However, it doesn't explicitly differentiate from sibling tools like query_segmentation_average or query_segmentation_bucket, which likely perform different aggregation functions on similar data.

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 through examples: 'Useful for calculating revenue metrics, aggregating quantitative values, and tracking cumulative totals across different time periods.' This suggests appropriate contexts but doesn't explicitly state when to use this tool versus alternatives like query_segmentation_average (for averages) or query_segmentation_bucket (for bucketing). No exclusions or prerequisites are mentioned.

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