Skip to main content
Glama
dragonkhoi

mixpanel

query_segmentation_average

Calculate average numeric metrics like purchase amounts or session durations over time. Input event data, date range, and expression to analyze trends by hour or day.

Instructions

Averages an expression for events per unit time. Useful for calculating average values like purchase amounts, session durations, or any numeric metric, and tracking how these averages change over time.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
eventYesThe event that you wish to get data for. Note: this is a single event name, not an array
from_dateYesThe date in yyyy-mm-dd format to begin querying from (inclusive)
onYesThe expression to average per unit time. The result of the expression should be 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)
unitNoThe buckets [hour, day] into which the property values are placed. 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

  • The asynchronous handler function that executes the core logic of the 'query_segmentation_average' tool. It constructs a URL for Mixpanel's /api/query/segmentation/average endpoint, authenticates with Basic Auth using service account credentials, fetches the data, and returns it as JSON or an error message.
    async ({ 
      project_id = DEFAULT_PROJECT_ID, 
      workspace_id, 
      event, 
      from_date, 
      to_date, 
      on, 
      unit, 
      where 
    }) => {
      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');
        
        // Construct base URL with required parameters
        let url = `https://mixpanel.com/api/query/segmentation/average?project_id=${project_id}&event=${encodeURIComponent(event)}&from_date=${from_date}&to_date=${to_date}&on=${encodeURIComponent(on)}`;
        
        // Add optional parameters if they exist
        if (workspace_id) url += `&workspace_id=${workspace_id}`;
        if (unit) url += `&unit=${unit}`;
        if (where) url += `&where=${encodeURIComponent(where)}`;
        
        // 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(`API request failed with status ${response.status}: ${errorText}`);
        }
        
        const data = await response.json();
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(data)
            }
          ],
          isError: true
        };
      } catch (error) {
        console.error('Error querying segmentation average:', error);
        return {
          content: [
            {
              type: "text",
              text: `Error querying segmentation average: ${error}`
            }
          ],
          isError: true
        };
      }
    }
  • Zod schema defining the input parameters for the 'query_segmentation_average' tool, including project_id, event, dates, the expression to average ('on'), 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().describe("The ID of the workspace if applicable").optional(),
      event: z.string().describe("The event that you wish to get data for. Note: this is a 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 average per unit time. The result of the expression should be a numeric value"),
      unit: z.enum(["hour", "day"]).describe("The buckets [hour, day] into which the property values are placed. Default is 'day'").optional(),
      where: z.string().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'`).optional(),
    },
  • src/index.ts:1319-1402 (registration)
    The server.tool() registration call that registers the 'query_segmentation_average' tool with the MCP server, providing name, description, input schema, and handler function.
    server.tool(
      "query_segmentation_average",
      "Averages an expression for events per unit time. Useful for calculating average values like purchase amounts, session durations, or any numeric metric, and tracking how these averages change over time.",
      {
        project_id: z.string().describe("The Mixpanel project ID. Optional since it has a default.").optional(),
        workspace_id: z.string().describe("The ID of the workspace if applicable").optional(),
        event: z.string().describe("The event that you wish to get data for. Note: this is a 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 average per unit time. The result of the expression should be a numeric value"),
        unit: z.enum(["hour", "day"]).describe("The buckets [hour, day] into which the property values are placed. Default is 'day'").optional(),
        where: z.string().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'`).optional(),
      },
      async ({ 
        project_id = DEFAULT_PROJECT_ID, 
        workspace_id, 
        event, 
        from_date, 
        to_date, 
        on, 
        unit, 
        where 
      }) => {
        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');
          
          // Construct base URL with required parameters
          let url = `https://mixpanel.com/api/query/segmentation/average?project_id=${project_id}&event=${encodeURIComponent(event)}&from_date=${from_date}&to_date=${to_date}&on=${encodeURIComponent(on)}`;
          
          // Add optional parameters if they exist
          if (workspace_id) url += `&workspace_id=${workspace_id}`;
          if (unit) url += `&unit=${unit}`;
          if (where) url += `&where=${encodeURIComponent(where)}`;
          
          // 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(`API request failed with status ${response.status}: ${errorText}`);
          }
          
          const data = await response.json();
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(data)
              }
            ],
            isError: true
          };
        } catch (error) {
          console.error('Error querying segmentation average:', error);
          return {
            content: [
              {
                type: "text",
                text: `Error querying segmentation average: ${error}`
              }
            ],
            isError: true
          };
        }
      }
    );
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's function but lacks critical details: it doesn't specify whether this is a read-only operation, what permissions are required, how results are returned (e.g., format, pagination), or any rate limits. For a complex 8-parameter tool with 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 core purpose, and the second provides usage examples. There's no wasted verbiage, and it's front-loaded with the key functionality. However, it could be slightly more concise by integrating the examples 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 (8 parameters, no annotations, no output schema), the description is incomplete. It adequately explains the purpose but fails to address behavioral aspects like safety, permissions, or result format. For a tool performing data aggregation with multiple inputs, more context is needed to ensure proper agent usage.

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%, so the schema already documents all parameters thoroughly. The description adds marginal value by clarifying that the expression should be numeric and mentioning 'per unit time' (hinting at the 'unit' parameter), but it doesn't provide additional syntax, format, or constraint details beyond what the schema provides. 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: 'Averages an expression for events per unit time' with specific examples like purchase amounts and session durations. It distinguishes from siblings by focusing on averaging rather than counting, summing, or other aggregation types, though it doesn't explicitly name alternatives.

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 implies usage context with 'Useful for calculating average values... and tracking how these averages change over time,' suggesting temporal analysis applications. However, it doesn't provide explicit guidance on when to choose this tool over similar siblings like query_segmentation_sum or query_segmentation_bucket, nor does it mention 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