#
tokens: 34401/50000 13/15 files (page 1/3)
lines: off (toggle) GitHub
raw markdown copy
This is page 1 of 3. Use http://codebase.md/dragonkhoi/mixpanel-mcp?lines=false&page={x} to view the full context.

# Directory Structure

```
├── .api
│   ├── api.json
│   └── apis
│       └── mixpaneldevdocs
│           ├── index.d.ts
│           ├── index.js
│           ├── openapi.json
│           ├── package.json
│           ├── schemas.d.ts
│           └── types.d.ts
├── .gitignore
├── Dockerfile
├── LICENSE
├── mcp-docs.txt
├── package.json
├── README.md
├── smithery.yaml
├── src
│   └── index.ts
└── tsconfig.json
```

# Files

--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------

```
# Dependency Directories and Files
node_modules/
jspm_packages/
bower_components
web_modules/
package-lock.json
yarn.lock
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
.yarn-integrity
.npm

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Environment Variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local

# Build and Output Directories
dist/
build/
build/Release
coverage/
.next/
out/
.nuxt
.vuepress/dist
.docusaurus
.serverless/

# Test and Coverage
coverage
*.lcov
.nyc_output
lib-cov

# Cache Files
.cache/
.parcel-cache
.temp
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
.eslintcache
.stylelintcache
.dynamodb/
.fusebox/

# TypeScript
*.tsbuildinfo

# Runtime data
pids
*.pid
*.seed
*.pid.lock
.grunt
.lock-wscript

# Editor directories and files
.idea/
.vscode/
.vscode-test
*.swp
*.swo
.history/
.tern-port

# Misc files
.DS_Store
Thumbs.db
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
.node_repl_history
*.tgz

# Gatsby files
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

```

--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------

```markdown
# Mixpanel MCP
[![smithery badge](https://smithery.ai/badge/@dragonkhoi/mixpanel-mcp)](https://smithery.ai/server/@dragonkhoi/mixpanel-mcp)

Simple MCP server that interfaces with the Mixpanel API, allowing you to talk to your Mixpanel events data from any MCP client like Cursor or Claude Desktop. Query events data, retention, and funnels. Great for on-demand look ups like: "What's the weekly retention for users in the Feb 1 cohort?"

<a href="https://glama.ai/mcp/servers/3ymkqswmp4">
  <img width="380" height="200" src="https://glama.ai/mcp/servers/3ymkqswmp4/badge" alt="mixpanel MCP server" />
</a>

I am adding more coverage of the Mixpanel API over time, let me know which tools you need or just open a PR.

## Installation
Make sure to go to your Mixpanel Organization Settings to set up a [Mixpanel Service Account](https://developer.mixpanel.com/reference/service-accounts), get the username, password, and your project ID (in Mixpanel Project Settings).

### Installing via Smithery

To install mixpanel-mcp for Claude Desktop automatically via [Smithery](https://smithery.ai/server/@dragonkhoi/mixpanel-mcp):

```bash
npx -y @smithery/cli install @dragonkhoi/mixpanel-mcp --client claude
```

To install mixpanel-mcp for Cursor, go to Settings -> Cursor Settings -> Features -> MCP Servers -> + Add

Select Type: command and paste the below, using the arguments `<USERNAME> <PW> <PROJECT_ID>` from Mixpanel
```
npx -y @smithery/cli@latest run @dragonkhoi/mixpanel-mcp --config "{\"username\":\"YOUR_SERVICE_ACCT_USERNAME\",\"password\":\"YOUR_SERVICE_ACCT_PASSWORD\",\"projectId\":\"YOUR_MIXPANEL_PROJECT_ID\"}"
```

### Clone and run locally
Clone this repo
Run `npm run build`
Paste this command into Cursor (or whatever MCP Client)
`node /ABSOLUTE/PATH/TO/mixpanel-mcp/build/index.js YOUR_SERVICE_ACCOUNT_USERNAME YOUR_SERVICE_ACCOUNT_PASSWORD YOUR_PROJECT_ID`

## Examples
- Ask about retention numbers

<img width="500" alt="IMG_3675" src="https://github.com/user-attachments/assets/5999958e-d4f6-4824-b226-50ad416ab064" />


- Ask for an overview of events

<img width="500" alt="IMG_9968" src="https://github.com/user-attachments/assets/c05cd932-5ca8-4a5b-a31c-7da2c4f2fa77" />
```

--------------------------------------------------------------------------------
/.api/apis/mixpaneldevdocs/package.json:
--------------------------------------------------------------------------------

```json
{
  "name": "@api/mixpaneldevdocs",
  "version": "1.0.0",
  "main": "./index.js",
  "types": "./index.d.ts",
  "dependencies": {
    "api": "^6.1.3",
    "json-schema-to-ts": "^2.8.0-beta.0",
    "oas": "^20.11.0"
  },
  "type": "module"
}

```

--------------------------------------------------------------------------------
/.api/api.json:
--------------------------------------------------------------------------------

```json
{
  "version": "1.0",
  "apis": [
    {
      "identifier": "mixpaneldevdocs",
      "source": "@mixpaneldevdocs/v3.27#j9225im36ixttm",
      "integrity": "sha512-53f+rttLOk7nwNQAjOHGtmrwGwasncr6Cwz65bnoGLxTfZSRRzrxltfWqZFby5YvWxlAojkrI3f7TWJiFPkzOw==",
      "installerVersion": "6.1.3"
    }
  ]
}
```

--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "Node16",
    "moduleResolution": "Node16",
    "outDir": "./build",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

```

--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------

```dockerfile
# Generated by https://smithery.ai. See: https://smithery.ai/docs/config#dockerfile
FROM node:lts-alpine
WORKDIR /app

# Copy package files and install dependencies
COPY package.json ./
COPY tsconfig.json ./
RUN npm install --ignore-scripts

# Copy the rest of the source code and build
COPY . .
RUN npm run build

# Expose MCP default port if needed (MCP over stdio, so not exposing ports)

# Default command: Expecting user to provide Mixpanel credentials
CMD ["node", "build/index.js", "YOUR_SERVICE_ACCOUNT_USERNAME", "YOUR_SERVICE_ACCOUNT_PASSWORD", "YOUR_PROJECT_ID"]

```

--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------

```json
{
  "name": "mcp-mixpanel",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "tsc && node -e \"require('fs').chmodSync('build/index.js', '755')\"",
    "postinstall": "npm run build"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "@modelcontextprotocol/sdk": "^1.6.1",
    "zod": "^3.24.2"
  },
  "devDependencies": {
    "@types/node": "^22.13.5",
    "typescript": "^5.8.2"
  },
  "type": "module",
  "bin": {
    "mcp-mixpanel": "./build/index.js"
  },
  "files": [
    "build"
  ]
}

```

--------------------------------------------------------------------------------
/smithery.yaml:
--------------------------------------------------------------------------------

```yaml
# Smithery configuration file: https://smithery.ai/docs/config#smitheryyaml

startCommand:
  type: stdio
  configSchema:
    # JSON Schema defining the configuration options for the MCP.
    type: object
    required:
      - username
      - password
      - projectId
    properties:
      username:
        type: string
        description: Mixpanel Service Account username.
      password:
        type: string
        description: Mixpanel Service Account password.
      projectId:
        type: string
        description: Mixpanel Project ID.
  commandFunction:
    # A JS function that produces the CLI command based on the given config to start the MCP on stdio.
    |-
    (config) => ({
      command: 'node',
      args: ['build/index.js', config.username, config.password, config.projectId]
    })
  exampleConfig:
    username: demoUser
    password: demoPass
    projectId: "123456"

```

--------------------------------------------------------------------------------
/.api/apis/mixpaneldevdocs/types.d.ts:
--------------------------------------------------------------------------------

```typescript
import type { FromSchema } from 'json-schema-to-ts';
import * as schemas from './schemas';
export type ActivityStreamQueryMetadataParam = FromSchema<typeof schemas.ActivityStreamQuery.metadata>;
export type ActivityStreamQueryResponse200 = FromSchema<typeof schemas.ActivityStreamQuery.response['200']>;
export type CohortsListMetadataParam = FromSchema<typeof schemas.CohortsList.metadata>;
export type CohortsListResponse200 = FromSchema<typeof schemas.CohortsList.response['200']>;
export type EngageQueryFormDataParam = FromSchema<typeof schemas.EngageQuery.formData>;
export type EngageQueryMetadataParam = FromSchema<typeof schemas.EngageQuery.metadata>;
export type EngageQueryResponse200 = FromSchema<typeof schemas.EngageQuery.response['200']>;
export type FunnelsListSavedMetadataParam = FromSchema<typeof schemas.FunnelsListSaved.metadata>;
export type FunnelsListSavedResponse200 = FromSchema<typeof schemas.FunnelsListSaved.response['200']>;
export type FunnelsQueryMetadataParam = FromSchema<typeof schemas.FunnelsQuery.metadata>;
export type FunnelsQueryResponse200 = FromSchema<typeof schemas.FunnelsQuery.response['200']>;
export type InsightsQueryMetadataParam = FromSchema<typeof schemas.InsightsQuery.metadata>;
export type InsightsQueryResponse200 = FromSchema<typeof schemas.InsightsQuery.response['200']>;
export type ListRecentEventsMetadataParam = FromSchema<typeof schemas.ListRecentEvents.metadata>;
export type ListRecentEventsResponse200 = FromSchema<typeof schemas.ListRecentEvents.response['200']>;
export type QueryEventPropertiesMetadataParam = FromSchema<typeof schemas.QueryEventProperties.metadata>;
export type QueryEventPropertiesResponse200 = FromSchema<typeof schemas.QueryEventProperties.response['200']>;
export type QueryEventsTopPropertiesMetadataParam = FromSchema<typeof schemas.QueryEventsTopProperties.metadata>;
export type QueryEventsTopPropertiesResponse200 = FromSchema<typeof schemas.QueryEventsTopProperties.response['200']>;
export type QueryEventsTopPropertyValuesMetadataParam = FromSchema<typeof schemas.QueryEventsTopPropertyValues.metadata>;
export type QueryEventsTopPropertyValuesResponse200 = FromSchema<typeof schemas.QueryEventsTopPropertyValues.response['200']>;
export type QueryJqlFormDataParam = FromSchema<typeof schemas.QueryJql.formData>;
export type QueryJqlMetadataParam = FromSchema<typeof schemas.QueryJql.metadata>;
export type QueryJqlResponse200 = FromSchema<typeof schemas.QueryJql.response['200']>;
export type QueryMonthsTopEventNamesMetadataParam = FromSchema<typeof schemas.QueryMonthsTopEventNames.metadata>;
export type QueryMonthsTopEventNamesResponse200 = FromSchema<typeof schemas.QueryMonthsTopEventNames.response['200']>;
export type QueryTopEventsMetadataParam = FromSchema<typeof schemas.QueryTopEvents.metadata>;
export type QueryTopEventsResponse200 = FromSchema<typeof schemas.QueryTopEvents.response['200']>;
export type RetentionFrequencyQueryMetadataParam = FromSchema<typeof schemas.RetentionFrequencyQuery.metadata>;
export type RetentionFrequencyQueryResponse200 = FromSchema<typeof schemas.RetentionFrequencyQuery.response['200']>;
export type RetentionQueryMetadataParam = FromSchema<typeof schemas.RetentionQuery.metadata>;
export type RetentionQueryResponse200 = FromSchema<typeof schemas.RetentionQuery.response['200']>;
export type SegmentationNumericQueryMetadataParam = FromSchema<typeof schemas.SegmentationNumericQuery.metadata>;
export type SegmentationNumericQueryResponse200 = FromSchema<typeof schemas.SegmentationNumericQuery.response['200']>;
export type SegmentationQueryAverageMetadataParam = FromSchema<typeof schemas.SegmentationQueryAverage.metadata>;
export type SegmentationQueryAverageResponse200 = FromSchema<typeof schemas.SegmentationQueryAverage.response['200']>;
export type SegmentationQueryMetadataParam = FromSchema<typeof schemas.SegmentationQuery.metadata>;
export type SegmentationQueryResponse200 = FromSchema<typeof schemas.SegmentationQuery.response['200']>;
export type SegmentationSumQueryMetadataParam = FromSchema<typeof schemas.SegmentationSumQuery.metadata>;
export type SegmentationSumQueryResponse200 = FromSchema<typeof schemas.SegmentationSumQuery.response['200']>;

```

--------------------------------------------------------------------------------
/.api/apis/mixpaneldevdocs/index.js:
--------------------------------------------------------------------------------

```javascript
import Oas from 'oas';
import APICore from 'api/dist/core';
import definition from './openapi.json';
class SDK {
    constructor() {
        this.spec = Oas.init(definition);
        this.core = new APICore(this.spec, 'mixpaneldevdocs/1.0.0 (api/6.1.3)');
    }
    /**
     * Optionally configure various options that the SDK allows.
     *
     * @param config Object of supported SDK options and toggles.
     * @param config.timeout Override the default `fetch` request timeout of 30 seconds. This number
     * should be represented in milliseconds.
     */
    config(config) {
        this.core.setConfig(config);
    }
    /**
     * If the API you're using requires authentication you can supply the required credentials
     * through this method and the library will magically determine how they should be used
     * within your API request.
     *
     * With the exception of OpenID and MutualTLS, it supports all forms of authentication
     * supported by the OpenAPI specification.
     *
     * @example <caption>HTTP Basic auth</caption>
     * sdk.auth('username', 'password');
     *
     * @example <caption>Bearer tokens (HTTP or OAuth 2)</caption>
     * sdk.auth('myBearerToken');
     *
     * @example <caption>API Keys</caption>
     * sdk.auth('myApiKey');
     *
     * @see {@link https://spec.openapis.org/oas/v3.0.3#fixed-fields-22}
     * @see {@link https://spec.openapis.org/oas/v3.1.0#fixed-fields-22}
     * @param values Your auth credentials for the API; can specify up to two strings or numbers.
     */
    auth(...values) {
        this.core.setAuth(...values);
        return this;
    }
    /**
     * If the API you're using offers alternate server URLs, and server variables, you can tell
     * the SDK which one to use with this method. To use it you can supply either one of the
     * server URLs that are contained within the OpenAPI definition (along with any server
     * variables), or you can pass it a fully qualified URL to use (that may or may not exist
     * within the OpenAPI definition).
     *
     * @example <caption>Server URL with server variables</caption>
     * sdk.server('https://{region}.api.example.com/{basePath}', {
     *   name: 'eu',
     *   basePath: 'v14',
     * });
     *
     * @example <caption>Fully qualified server URL</caption>
     * sdk.server('https://eu.api.example.com/v14');
     *
     * @param url Server URL
     * @param variables An object of variables to replace into the server URL.
     */
    server(url, variables = {}) {
        this.core.setServer(url, variables);
    }
    /**
     * Get data from your Insights reports. The Query API has a rate limit of 60 queries per
     * hour and a maximum of 5 concurrent queries.
     *
     * @summary Query Saved Report
     */
    insightsQuery(metadata) {
        return this.core.fetch('/insights', 'get', metadata);
    }
    /**
     * Get data for a funnel. The Query API has a rate limit of 60 queries per hour and a
     * maximum of 5 concurrent queries.
     *
     * @summary Query Saved Report
     */
    funnelsQuery(metadata) {
        return this.core.fetch('/funnels', 'get', metadata);
    }
    /**
     * Get the names and funnel_ids of your funnels.
     *
     * @summary List Saved Funnels
     */
    funnelsListSaved(metadata) {
        return this.core.fetch('/funnels/list', 'get', metadata);
    }
    /**
     * Query Retention Report
     *
     */
    retentionQuery(metadata) {
        return this.core.fetch('/retention', 'get', metadata);
    }
    /**
     * Query Frequency Report
     *
     */
    retentionFrequencyQuery(metadata) {
        return this.core.fetch('/retention/addiction', 'get', metadata);
    }
    /**
     * Get data for an event, segmented and filtered by properties. The Query API has a rate
     * limit of 60 queries per hour and a maximum of 5 concurrent queries.
     *
     * @summary Query Segmentation Report
     */
    segmentationQuery(metadata) {
        return this.core.fetch('/segmentation', 'get', metadata);
    }
    /**
     * Get data for an event, segmented and filtered by properties, with values placed into
     * numeric buckets.
     * The Query API has a rate limit of 60 queries per hour and a maximum of 5 concurrent
     * queries.
     *
     * @summary Numerically Bucket
     */
    segmentationNumericQuery(metadata) {
        return this.core.fetch('/segmentation/numeric', 'get', metadata);
    }
    /**
     * Sums an expression for events per unit time. The Query API has a rate limit of 60
     * queries per hour and a maximum of 5 concurrent queries.
     *
     * @summary Numerically Sum
     */
    segmentationSumQuery(metadata) {
        return this.core.fetch('/segmentation/sum', 'get', metadata);
    }
    /**
     * Averages an expression for events per unit time. The Query API has a rate limit of 60
     * queries per hour and a maximum of 5 concurrent queries.
     *
     * @summary Numerically Average
     */
    segmentationQueryAverage(metadata) {
        return this.core.fetch('/segmentation/average', 'get', metadata);
    }
    /**
     * This endpoint returns the activity feed for specified users. The Query API has a rate
     * limit of 60 queries per hour and a maximum of 5 concurrent queries.
     *
     * @summary Profile Event Activity
     */
    activityStreamQuery(metadata) {
        return this.core.fetch('/stream/query', 'get', metadata);
    }
    /**
     * The list endpoint returns all of the cohorts in a given project. The JSON formatted
     * return contains the cohort name, id, count, description, creation date, and visibility
     * for every cohort in the project.
     *
     * If you're trying to get a list of users in a cohort, you can use the [`/engage` endpoint
     * with the `filter_by_cohort` parameter](ref:engage#engage-query).
     * The Query API has a rate limit of 60 queries per hour and a maximum of 5 concurrent
     * queries.
     *
     * @summary List Saved Cohorts
     */
    cohortsList(metadata) {
        return this.core.fetch('/cohorts/list', 'post', metadata);
    }
    engageQuery(body, metadata) {
        return this.core.fetch('/engage', 'post', body, metadata);
    }
    /**
     * Get unique, total, or average data for a set of events over N days, weeks, or months.
     * The Query API has a rate limit of 60 queries per hour and a maximum of 5 concurrent
     * queries.
     *
     * @summary Aggregate Event Counts
     */
    listRecentEvents(metadata) {
        return this.core.fetch('/events', 'get', metadata);
    }
    /**
     * Get the top events for today, with their counts and the normalized percent change from
     * yesterday.
     * The Query API has a rate limit of 60 queries per hour and a maximum of 5 concurrent
     * queries.
     *
     * @summary Today's Top Events
     */
    queryTopEvents(metadata) {
        return this.core.fetch('/events/top', 'get', metadata);
    }
    /**
     * Get a list of the most common events over the last 31 days. The Query API has a rate
     * limit of 60 queries per hour and a maximum of 5 concurrent queries.
     *
     * @summary Top Events
     */
    queryMonthsTopEventNames(metadata) {
        return this.core.fetch('/events/names', 'get', metadata);
    }
    /**
     * Get unique, total, or average data for of a single event and property over days, weeks,
     * or months.
     * The Query API has a rate limit of 60 queries per hour and a maximum of 5 concurrent
     * queries.
     *
     * @summary Aggregrated Event Property Values
     */
    queryEventProperties(metadata) {
        return this.core.fetch('/events/properties', 'get', metadata);
    }
    /**
     * Get the top property names for an event. The Query API has a rate limit of 60 queries
     * per hour and a maximum of 5 concurrent queries.
     *
     * @summary Top Event Properties
     */
    queryEventsTopProperties(metadata) {
        return this.core.fetch('/events/properties/top', 'get', metadata);
    }
    /**
     * Get the top values for a property. The Query API has a rate limit of 60 queries per hour
     * and a maximum of 5 concurrent queries.
     *
     * @summary Top Event Property Values
     */
    queryEventsTopPropertyValues(metadata) {
        return this.core.fetch('/events/properties/values', 'get', metadata);
    }
    /**
     * Custom JQL Query
     *
     */
    queryJql(body, metadata) {
        return this.core.fetch('/jql', 'post', body, metadata);
    }
}
const createSDK = (() => { return new SDK(); })();
export default createSDK;

```

--------------------------------------------------------------------------------
/.api/apis/mixpaneldevdocs/index.d.ts:
--------------------------------------------------------------------------------

```typescript
import type * as types from './types';
import type { ConfigOptions, FetchResponse } from 'api/dist/core';
import Oas from 'oas';
import APICore from 'api/dist/core';
declare class SDK {
    spec: Oas;
    core: APICore;
    constructor();
    /**
     * Optionally configure various options that the SDK allows.
     *
     * @param config Object of supported SDK options and toggles.
     * @param config.timeout Override the default `fetch` request timeout of 30 seconds. This number
     * should be represented in milliseconds.
     */
    config(config: ConfigOptions): void;
    /**
     * If the API you're using requires authentication you can supply the required credentials
     * through this method and the library will magically determine how they should be used
     * within your API request.
     *
     * With the exception of OpenID and MutualTLS, it supports all forms of authentication
     * supported by the OpenAPI specification.
     *
     * @example <caption>HTTP Basic auth</caption>
     * sdk.auth('username', 'password');
     *
     * @example <caption>Bearer tokens (HTTP or OAuth 2)</caption>
     * sdk.auth('myBearerToken');
     *
     * @example <caption>API Keys</caption>
     * sdk.auth('myApiKey');
     *
     * @see {@link https://spec.openapis.org/oas/v3.0.3#fixed-fields-22}
     * @see {@link https://spec.openapis.org/oas/v3.1.0#fixed-fields-22}
     * @param values Your auth credentials for the API; can specify up to two strings or numbers.
     */
    auth(...values: string[] | number[]): this;
    /**
     * If the API you're using offers alternate server URLs, and server variables, you can tell
     * the SDK which one to use with this method. To use it you can supply either one of the
     * server URLs that are contained within the OpenAPI definition (along with any server
     * variables), or you can pass it a fully qualified URL to use (that may or may not exist
     * within the OpenAPI definition).
     *
     * @example <caption>Server URL with server variables</caption>
     * sdk.server('https://{region}.api.example.com/{basePath}', {
     *   name: 'eu',
     *   basePath: 'v14',
     * });
     *
     * @example <caption>Fully qualified server URL</caption>
     * sdk.server('https://eu.api.example.com/v14');
     *
     * @param url Server URL
     * @param variables An object of variables to replace into the server URL.
     */
    server(url: string, variables?: {}): void;
    /**
     * Get data from your Insights reports. The Query API has a rate limit of 60 queries per
     * hour and a maximum of 5 concurrent queries.
     *
     * @summary Query Saved Report
     */
    insightsQuery(metadata: types.InsightsQueryMetadataParam): Promise<FetchResponse<200, types.InsightsQueryResponse200>>;
    /**
     * Get data for a funnel. The Query API has a rate limit of 60 queries per hour and a
     * maximum of 5 concurrent queries.
     *
     * @summary Query Saved Report
     */
    funnelsQuery(metadata: types.FunnelsQueryMetadataParam): Promise<FetchResponse<200, types.FunnelsQueryResponse200>>;
    /**
     * Get the names and funnel_ids of your funnels.
     *
     * @summary List Saved Funnels
     */
    funnelsListSaved(metadata: types.FunnelsListSavedMetadataParam): Promise<FetchResponse<200, types.FunnelsListSavedResponse200>>;
    /**
     * Query Retention Report
     *
     */
    retentionQuery(metadata: types.RetentionQueryMetadataParam): Promise<FetchResponse<200, types.RetentionQueryResponse200>>;
    /**
     * Query Frequency Report
     *
     */
    retentionFrequencyQuery(metadata: types.RetentionFrequencyQueryMetadataParam): Promise<FetchResponse<200, types.RetentionFrequencyQueryResponse200>>;
    /**
     * Get data for an event, segmented and filtered by properties. The Query API has a rate
     * limit of 60 queries per hour and a maximum of 5 concurrent queries.
     *
     * @summary Query Segmentation Report
     */
    segmentationQuery(metadata: types.SegmentationQueryMetadataParam): Promise<FetchResponse<200, types.SegmentationQueryResponse200>>;
    /**
     * Get data for an event, segmented and filtered by properties, with values placed into
     * numeric buckets.
     * The Query API has a rate limit of 60 queries per hour and a maximum of 5 concurrent
     * queries.
     *
     * @summary Numerically Bucket
     */
    segmentationNumericQuery(metadata: types.SegmentationNumericQueryMetadataParam): Promise<FetchResponse<200, types.SegmentationNumericQueryResponse200>>;
    /**
     * Sums an expression for events per unit time. The Query API has a rate limit of 60
     * queries per hour and a maximum of 5 concurrent queries.
     *
     * @summary Numerically Sum
     */
    segmentationSumQuery(metadata: types.SegmentationSumQueryMetadataParam): Promise<FetchResponse<200, types.SegmentationSumQueryResponse200>>;
    /**
     * Averages an expression for events per unit time. The Query API has a rate limit of 60
     * queries per hour and a maximum of 5 concurrent queries.
     *
     * @summary Numerically Average
     */
    segmentationQueryAverage(metadata: types.SegmentationQueryAverageMetadataParam): Promise<FetchResponse<200, types.SegmentationQueryAverageResponse200>>;
    /**
     * This endpoint returns the activity feed for specified users. The Query API has a rate
     * limit of 60 queries per hour and a maximum of 5 concurrent queries.
     *
     * @summary Profile Event Activity
     */
    activityStreamQuery(metadata: types.ActivityStreamQueryMetadataParam): Promise<FetchResponse<200, types.ActivityStreamQueryResponse200>>;
    /**
     * The list endpoint returns all of the cohorts in a given project. The JSON formatted
     * return contains the cohort name, id, count, description, creation date, and visibility
     * for every cohort in the project.
     *
     * If you're trying to get a list of users in a cohort, you can use the [`/engage` endpoint
     * with the `filter_by_cohort` parameter](ref:engage#engage-query).
     * The Query API has a rate limit of 60 queries per hour and a maximum of 5 concurrent
     * queries.
     *
     * @summary List Saved Cohorts
     */
    cohortsList(metadata: types.CohortsListMetadataParam): Promise<FetchResponse<200, types.CohortsListResponse200>>;
    /**
     * Query Profiles
     *
     */
    engageQuery(body: types.EngageQueryFormDataParam, metadata: types.EngageQueryMetadataParam): Promise<FetchResponse<200, types.EngageQueryResponse200>>;
    engageQuery(metadata: types.EngageQueryMetadataParam): Promise<FetchResponse<200, types.EngageQueryResponse200>>;
    /**
     * Get unique, total, or average data for a set of events over N days, weeks, or months.
     * The Query API has a rate limit of 60 queries per hour and a maximum of 5 concurrent
     * queries.
     *
     * @summary Aggregate Event Counts
     */
    listRecentEvents(metadata: types.ListRecentEventsMetadataParam): Promise<FetchResponse<200, types.ListRecentEventsResponse200>>;
    /**
     * Get the top events for today, with their counts and the normalized percent change from
     * yesterday.
     * The Query API has a rate limit of 60 queries per hour and a maximum of 5 concurrent
     * queries.
     *
     * @summary Today's Top Events
     */
    queryTopEvents(metadata: types.QueryTopEventsMetadataParam): Promise<FetchResponse<200, types.QueryTopEventsResponse200>>;
    /**
     * Get a list of the most common events over the last 31 days. The Query API has a rate
     * limit of 60 queries per hour and a maximum of 5 concurrent queries.
     *
     * @summary Top Events
     */
    queryMonthsTopEventNames(metadata: types.QueryMonthsTopEventNamesMetadataParam): Promise<FetchResponse<200, types.QueryMonthsTopEventNamesResponse200>>;
    /**
     * Get unique, total, or average data for of a single event and property over days, weeks,
     * or months.
     * The Query API has a rate limit of 60 queries per hour and a maximum of 5 concurrent
     * queries.
     *
     * @summary Aggregrated Event Property Values
     */
    queryEventProperties(metadata: types.QueryEventPropertiesMetadataParam): Promise<FetchResponse<200, types.QueryEventPropertiesResponse200>>;
    /**
     * Get the top property names for an event. The Query API has a rate limit of 60 queries
     * per hour and a maximum of 5 concurrent queries.
     *
     * @summary Top Event Properties
     */
    queryEventsTopProperties(metadata: types.QueryEventsTopPropertiesMetadataParam): Promise<FetchResponse<200, types.QueryEventsTopPropertiesResponse200>>;
    /**
     * Get the top values for a property. The Query API has a rate limit of 60 queries per hour
     * and a maximum of 5 concurrent queries.
     *
     * @summary Top Event Property Values
     */
    queryEventsTopPropertyValues(metadata: types.QueryEventsTopPropertyValuesMetadataParam): Promise<FetchResponse<200, types.QueryEventsTopPropertyValuesResponse200>>;
    /**
     * Custom JQL Query
     *
     */
    queryJql(body: types.QueryJqlFormDataParam, metadata: types.QueryJqlMetadataParam): Promise<FetchResponse<200, types.QueryJqlResponse200>>;
}
declare const createSDK: SDK;
export default createSDK;

```

--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------

```typescript
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({
    name: "mixpanel",
    version: "1.0.0"
})

const args = process.argv.slice(2);

if (args.length === 0) {
  console.error("Please provide a Mixpanel service account username and password and a project ID");
  process.exit(1);
}

const SERVICE_ACCOUNT_USER_NAME = process.env.SERVICE_ACCOUNT_USER_NAME || args[0] || "YOUR SERVICE ACCOUNT USERNAME";
const SERVICE_ACCOUNT_PASSWORD = process.env.SERVICE_ACCOUNT_PASSWORD || args[1] || "YOUR SERVICE ACCOUNT PASSWORD";
const DEFAULT_PROJECT_ID = process.env.DEFAULT_PROJECT_ID || args[2] || "YOUR PROJECT ID";

server.tool(
  "get_today_top_events",
  "Get today's top events from Mixpanel. Useful for quickly identifying the most active events happening today, spotting trends, and monitoring real-time user activity.",
  {
    project_id: z.string().describe("The Mixpanel project ID. Optional since it has a default.").optional(),
    type: z.enum(["general", "average", "unique"]).describe("The type of events to fetch, either general, average, or unique, defaults to general").optional(),
    limit: z.number().optional().describe("Maximum number of events to return"),
  },
  async ({ project_id = DEFAULT_PROJECT_ID, type = "general", limit = 10 }) => {
    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 URL with query parameters
      const url = `https://mixpanel.com/api/query/events/top?project_id=${project_id}&type=${type}${limit ? `&limit=${limit}` : ''}`;
      
      // 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 events:", error);
      const errorMessage = error instanceof Error ? error.message : String(error);
      return {
        content: [
          {
            type: "text",
            text: `Error fetching Mixpanel events: ${errorMessage}`
          }
        ],
        isError: true
      };
    }
  }
)

server.tool(
  "profile_event_activity",
  "Get data for a profile's event activity. Useful for understanding individual user journeys, troubleshooting user-specific issues, and analyzing behavior patterns of specific users.",
  {
    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(),
    distinct_ids: z.string().describe("A JSON array as a string representing the `distinct_ids` to return activity feeds for. Example: `[\"12a34aa567eb8d-9ab1c26f345b67-89123c45-6aeaa7-89f12af345f678\"]`"),
    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)"),
  },
  async ({ project_id = DEFAULT_PROJECT_ID, workspace_id, distinct_ids, 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');
      
      // Construct URL with query parameters
      let url = `https://mixpanel.com/api/query/stream/query?project_id=${project_id}&distinct_ids=${encodeURIComponent(distinct_ids)}&from_date=${from_date}&to_date=${to_date}`;
      
      // Add optional workspace_id if provided
      if (workspace_id) {
        url += `&workspace_id=${workspace_id}`;
      }
      
      // 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)
          }
        ]
      };
    } catch (error) {
      console.error('Error fetching profile event activity:', error);
      const errorMessage = error instanceof Error ? error.message : String(error);
      return {
        content: [
          {
            type: "text",
            text: `Error fetching profile event activity: ${errorMessage}`
          }
        ],
        isError: true
      };
    }
  }
);

server.tool(
  "get_top_events",
  "Get a list of the most common events over the last 31 days. Useful for identifying key user actions, prioritizing feature development, and understanding overall platform usage patterns.",
  {
    project_id: z.string().describe("The Mixpanel project ID. Optional since it has a default.").optional(),
    type: z.enum(["general", "average", "unique"]).describe("The type of events to fetch, either general, average, or unique, defaults to general").optional(),
    limit: z.number().optional().describe("Maximum number of events to return"),
  },
  async ({ project_id = DEFAULT_PROJECT_ID, type = "general", limit = 10 }) => {
    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 URL with query parameters
      const url = `https://mixpanel.com/api/query/events/names?project_id=${project_id}&type=${type}${limit ? `&limit=${limit}` : ''}`;
      
      // 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 events:", error);
      const errorMessage = error instanceof Error ? error.message : String(error);
      return {
        content: [
          {
            type: "text",
            text: `Error fetching Mixpanel events: ${errorMessage}`
          }
        ],
        isError: true
      };
    }
  }
)

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

server.tool(
  "aggregated_event_property_values",
  "Get unique, general, or average data for a single event and property over days, weeks, or months. Useful for analyzing how specific properties affect event performance, segmenting users, and identifying valuable user attributes.",
  {
    project_id: z.string().describe("The Mixpanel project ID. Optional since it has a default.").optional(),
    event: z.string().describe("The event that you wish to get data for (a single event name, not an array)"),
    name: z.string().describe("The name of the property you would like to get data for"),
    values: z.string().optional().describe("The specific property values to get data for, encoded as a JSON array. Example: \"[\"female\", \"unknown\"]\""),
    type: z.enum(["general", "unique", "average"]).describe("The analysis type - general, unique, or average events, defaults to general").optional(),
    unit: z.enum(["minute", "hour", "day", "week", "month"]).describe("The level of granularity of the data (minute, hour, day, week, or month)"),
    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)"),
    limit: z.number().optional().describe("The maximum number of values to return (default: 255)"),
  },
  async ({ project_id = DEFAULT_PROJECT_ID, event, name, values, type = "general", unit, interval, from_date, to_date, limit }) => {
    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 values if provided
      let parsedValues;
      if (values) {
        try {
          parsedValues = JSON.parse(values);
          if (!Array.isArray(parsedValues)) {
            throw new Error("Values must be a JSON array");
          }
        } catch (e) {
          throw new Error(`Invalid values format: ${e instanceof Error ? e.message : String(e)}`);
        }
      }
      
      // Build query parameters
      const queryParams = new URLSearchParams({
        project_id: project_id || '',
        event: event,
        name: name,
        type: type,
        unit: unit
      });
      
      // Add values if provided
      if (values) {
        queryParams.append('values', values);
      }
      
      // 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 limit if provided
      if (limit) {
        queryParams.append('limit', limit.toString());
      }
      
      // Construct URL with query parameters
      const url = `https://mixpanel.com/api/query/events/properties?${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 property values:", error);
      const errorMessage = error instanceof Error ? error.message : String(error);
      return {
        content: [
          {
            type: "text",
            text: `Error fetching Mixpanel event property values: ${errorMessage}`
          }
        ],
        isError: true
      };
    }
  }
)

server.tool(
  "query_insights_report",
  "Get data from your Insights reports. Useful for accessing saved analyses, sharing standardized metrics across teams, and retrieving complex pre-configured visualizations.",
  {
    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"),
    bookmark_id: z.string().describe("The ID of your Insights report"),
  },
  async ({ project_id = DEFAULT_PROJECT_ID, workspace_id, bookmark_id }) => {
    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 || '',
        bookmark_id: bookmark_id
      });
      
      if (workspace_id) {
        queryParams.append('workspace_id', workspace_id);
      }
      
      const url = `https://mixpanel.com/api/query/insights?${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 insights:", error);
      const errorMessage = error instanceof Error ? error.message : String(error);
      return {
        content: [
          {
            type: "text",
            text: `Error fetching Mixpanel insights: ${errorMessage}`
          }
        ],
        isError: true
      };
    }
  }
);

server.tool(
  "query_funnel_report",
  "Get data for a funnel based on a funnel_id. Useful for analyzing user conversion paths, identifying drop-off points in user journeys, and optimizing multi-step processes. Funnel IDs should be retrieved using the list_saved_funnels tool. ",
  {
    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"),
    funnel_id: z.string().describe("The Mixpanel funnel ID that you wish to get data for"),
    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)"),
    length: z.number().optional().describe("The number of units each user has to complete the funnel"),
    length_unit: z.enum(["day", "hour", "minute", "second"]).optional().describe("The unit applied to the length parameter"),
    interval: z.number().optional().describe("The number of days you want each bucket to contain"),
    unit: z.enum(["day", "week", "month"]).optional().describe("Alternate way of specifying interval"),
  },
  async ({ project_id = DEFAULT_PROJECT_ID, workspace_id, funnel_id, from_date, to_date, length, length_unit, interval, unit }) => {
    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 || '',
        funnel_id: funnel_id,
        from_date: from_date,
        to_date: to_date
      });
      
      if (workspace_id) queryParams.append('workspace_id', workspace_id);
      if (length) queryParams.append('length', length.toString());
      if (length_unit) queryParams.append('length_unit', length_unit);
      if (interval) queryParams.append('interval', interval.toString());
      if (unit) queryParams.append('unit', unit);
      
      const url = `https://mixpanel.com/api/query/funnels?${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 funnel data:", error);
      const errorMessage = error instanceof Error ? error.message : String(error);
      return {
        content: [
          {
            type: "text",
            text: `Error fetching Mixpanel funnel data: ${errorMessage}`
          }
        ],
        isError: true
      };
    }
  }
);

server.tool(
  "list_saved_funnels",
  "Get the names and IDs of your saved funnels. Useful for discovering available funnels for analysis and retrieving funnel IDs needed for the query_funnel_report tool.",
  {
    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"),
  },
  async ({ project_id = DEFAULT_PROJECT_ID, workspace_id }) => {
    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 || ''
      });
      
      if (workspace_id) {
        queryParams.append('workspace_id', workspace_id);
      }
      
      const url = `https://mixpanel.com/api/query/funnels/list?${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 funnels list:", error);
      const errorMessage = error instanceof Error ? error.message : String(error);
      return {
        content: [
          {
            type: "text",
            text: `Error fetching Mixpanel funnels list: ${errorMessage}`
          }
        ],
        isError: true
      };
    }
  }
);

server.tool(
  "list_saved_cohorts",
  "Get all cohorts in a given project. Useful for discovering user segments, planning targeted analyses, and retrieving cohort IDs for filtering in other reports.",
  {
    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"),
  },
  async ({ project_id = DEFAULT_PROJECT_ID, workspace_id }) => {
    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 || ''
      });
      
      if (workspace_id) {
        queryParams.append('workspace_id', workspace_id);
      }
      
      const url = `https://mixpanel.com/api/query/cohorts/list?${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 cohorts list:", error);
      const errorMessage = error instanceof Error ? error.message : String(error);
      return {
        content: [
          {
            type: "text",
            text: `Error fetching Mixpanel cohorts list: ${errorMessage}`
          }
        ],
        isError: true
      };
    }
  }
);

server.tool(
  "query_retention_report",
  "Get data from your Retention reports. Useful for analyzing user engagement over time, measuring product stickiness, and understanding how well your product retains users after specific actions. Only use params interval or unit, not both.",
  {
    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"),
    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)"),
    retention_type: z.enum(["birth", "compounded"]).optional().describe("Type of retention: 'birth' (first time) or 'compounded' (recurring). Defaults to 'birth'"),
    born_event: z.string().optional().describe("The first event a user must do to be counted in a birth retention cohort, required if retention_type is 'birth'. Can use $mp_web_page_view as the born_event for general cases."),
    event: z.string().optional().describe("The event to generate returning counts for. If not specified, looks across all events"),
    born_where: z.string().optional().describe(`An expression to filter born_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'`),
    return_where: z.string().optional().describe(`An expression to filter return 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'`),
    interval: z.number().optional().describe("The number of units per individual bucketed interval. Default is 1. DO NOT USE IF ALREADY PROVIDING UNIT."),
    interval_count: z.number().optional().describe("The number of individual buckets/intervals to return. Default is 1. DO NOT USE IF ALREADY PROVIDING UNIT."),
    unit: z.enum(["day", "week", "month"]).optional().describe("The interval unit: 'day' (eg use if asked for D7 or D30), 'week' (eg use if asked for W12), or 'month' (eg use if asked for M6). Default is 'day'. DO NOT USE IF ALREADY PROVIDING INTERVAL."),
    on: z.string().optional().describe("The property expression to segment the second event on"),
    limit: z.number().optional().describe("Return the top limit segmentation values. Only applies when 'on' is specified")
  },
  async ({ project_id = DEFAULT_PROJECT_ID, workspace_id, from_date, to_date, retention_type, born_event, event, born_where, return_where, interval, interval_count, unit, on, limit }) => {
    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 || '',
        from_date: from_date,
        to_date: to_date
      });
      
      if (workspace_id) queryParams.append('workspace_id', workspace_id);
      if (retention_type) queryParams.append('retention_type', retention_type);
      if (born_event) queryParams.append('born_event', born_event);
      if (event) queryParams.append('event', event);
      if (born_where) queryParams.append('born_where', born_where);
      if (return_where) queryParams.append('where', return_where);
      if (interval) queryParams.append('interval', interval.toString());
      if (interval_count) queryParams.append('interval_count', interval_count.toString());
      if (unit) queryParams.append('unit', unit);
      if (on) queryParams.append('on', on);
      if (limit) queryParams.append('limit', limit.toString());
      
      const url = `https://mixpanel.com/api/query/retention?${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 retention data:", error);
      const errorMessage = error instanceof Error ? error.message : String(error);
      return {
        content: [
          {
            type: "text",
            text: `Error fetching Mixpanel retention data: ${errorMessage}`
          }
        ],
        isError: true
      };
    }
  }
);

server.tool(
  "custom_jql",
  "Run a custom JQL (JSON Query Language) script against your Mixpanel data. Useful for complex custom analyses, advanced data transformations, and queries that can't be handled by standard report types.",
  {
    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"),
    script: z.string().describe("The JQL script to run (JavaScript code that uses Mixpanel's JQL functions)"),
    params: z.string().optional().describe("A JSON string containing parameters to pass to the script (will be available as the 'params' variable)")
  },
  async ({ project_id = DEFAULT_PROJECT_ID, workspace_id, script, params }) => {
    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 URL with query parameters
      const queryParams = new URLSearchParams();
      queryParams.append('project_id', project_id);
      if (workspace_id) queryParams.append('workspace_id', workspace_id);
      
      const url = `https://mixpanel.com/api/query/jql?${queryParams.toString()}`;
      
      // Prepare form data for POST request
      const formData = new URLSearchParams();
      formData.append('script', script);
      if (params) formData.append('params', params);
      
      // Set up request options
      const options = {
        method: 'POST',
        headers: {
          'accept': 'application/json',
          'authorization': `Basic ${encodedCredentials}`,
          'content-type': 'application/x-www-form-urlencoded'
        },
        body: formData
      };
      
      // 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 executing JQL query:", error);
      const errorMessage = error instanceof Error ? error.message : String(error);
      return {
        content: [
          {
            type: "text",
            text: `Error executing JQL query: ${errorMessage}`
          }
        ],
        isError: true
      };
    }
  }
);

server.tool(
  "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
      };
    }
  }
);

server.tool(
  "query_profiles",
  "Query Mixpanel user profiles with filtering options. Useful for retrieving detailed user profiles, filtering by specific properties, and analyzing user behavior across different dimensions.",
  {
    project_id: z.string().describe("The Mixpanel project ID. Optional since it has a default.. Optional since it has a default.").optional(),
    workspace_id: z.string().describe("The ID of the workspace if applicable").optional(),
    distinct_id: z.string().describe("A unique identifier used to distinguish an individual profile").optional(),
    distinct_ids: z.string().describe("A JSON array of distinct_ids to retrieve profiles for. Example: '[\"id1\", \"id2\"]'").optional(),
    data_group_id: z.string().describe("The ID of the group key, used when querying group profiles").optional(),
    where: z.string().describe(`An expression to filter users (or groups) by. Using the following grammar: <expression> ::= 'properties["' <property> '"]'
                | <expression> <binary op> <expression>
                | <unary op> <expression>
                | <math op> '(' <expression> ')'
                | <typecast op> '(' <expression> ')'
                | '(' <expression> ')'
                | <boolean literal>
                | <numeric literal>
                | <string literal>
  <binary op> ::= '+' | '-' | '*' | '/' | '%' | '==' | '!=' |
                  '>' | '>=' | '<' | '<=' | 'in' | 'and' | 'or'
   <unary op> ::= '-' | 'not'
    <math op> ::= 'floor' | 'round' | 'ceil'
<typecast op> ::= 'boolean' | 'number' | 'string'
   <property> ::= 'properties["' <property name> '"]'`).optional(),
    output_properties: z.string().describe("A JSON array of names of properties you want returned. Example: '[\"$last_name\", \"$email\", \"Total Spent\"]'").optional(),
    session_id: z.string().describe("A string id provided in the results of a previous query. Using a session_id speeds up api response, and allows paging through results").optional(),
    page: z.number().describe("Which page of the results to retrieve. Pages start at zero. If the 'page' parameter is provided, the session_id parameter must also be provided").optional(),
    behaviors: z.number().describe("If you are exporting user profiles using an event selector, you use a 'behaviors' parameter in your request").optional(),
    as_of_timestamp: z.number().describe("This parameter is only useful when also using 'behaviors'").optional(),
    filter_by_cohort: z.string().describe("Takes a JSON object with a single key called 'id' whose value is the cohort ID. Example: '{\"id\":12345}'").optional(),
    include_all_users: z.boolean().describe("Only applicable with 'filter_by_cohort' parameter. Default is true").optional(),
  },
  async ({ 
    project_id = DEFAULT_PROJECT_ID, 
    workspace_id, 
    distinct_id, 
    distinct_ids, 
    data_group_id, 
    where, 
    output_properties, 
    session_id, 
    page, 
    behaviors, 
    as_of_timestamp, 
    filter_by_cohort, 
    include_all_users 
  }) => {
    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 project_id
      let url = `https://mixpanel.com/api/query/engage?project_id=${project_id}`;
      
      // Add optional workspace_id if provided
      if (workspace_id) {
        url += `&workspace_id=${workspace_id}`;
      }
      
      // Create form data for POST request
      const formData = new URLSearchParams();
      
      // Add optional parameters to form data if they exist
      if (distinct_id) formData.append('distinct_id', distinct_id);
      if (distinct_ids) formData.append('distinct_ids', distinct_ids);
      if (data_group_id) formData.append('data_group_id', data_group_id);
      if (where) formData.append('where', where);
      if (output_properties) formData.append('output_properties', output_properties);
      if (session_id) formData.append('session_id', session_id);
      if (page !== undefined) formData.append('page', page.toString());
      if (behaviors !== undefined) formData.append('behaviors', behaviors.toString());
      if (as_of_timestamp !== undefined) formData.append('as_of_timestamp', as_of_timestamp.toString());
      if (filter_by_cohort) formData.append('filter_by_cohort', filter_by_cohort);
      if (include_all_users !== undefined) formData.append('include_all_users', include_all_users.toString());
      
      // Set up request options
      const options = {
        method: 'POST',
        headers: {
          'accept': 'application/json',
          'authorization': `Basic ${encodedCredentials}`,
          'content-type': 'application/x-www-form-urlencoded'
        },
        body: formData
      };
      
      // 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)
          }
        ]
      };
    } catch (error) {
      console.error('Error querying profiles:', error);
      return {
        content: [
          {
            type: "text",
            text: `Error querying profiles: ${error}`
          }
        ],
        isError: true
      };
    }
  }
);

server.tool(
  "query_frequency_report",
  "Get data for frequency of actions over time. Useful for analyzing how often users perform specific actions, identifying patterns of behavior, and tracking user engagement 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(),
    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)"),
    unit: z.enum(["day", "week", "month"]).describe("The overall time period to return frequency of actions for"),
    addiction_unit: z.enum(["hour", "day"]).describe("The granularity to return frequency of actions at"),
    event: z.string().describe("The event to generate returning counts for").optional(),
    where: z.string().describe(`An expression to filter the returning 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'`),
    on: z.string().describe("The property expression to segment the second event on").optional(),
    limit: z.number().describe("Return the top limit segmentation values. This parameter does nothing if 'on' is not specified").optional(),
  },
  async ({ 
    project_id = DEFAULT_PROJECT_ID, 
    workspace_id, 
    from_date, 
    to_date, 
    unit, 
    addiction_unit, 
    event, 
    where, 
    on, 
    limit 
  }) => {
    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/retention/addiction?project_id=${project_id}&from_date=${from_date}&to_date=${to_date}&unit=${unit}&addiction_unit=${addiction_unit}`;
      
      // Add optional parameters if they exist
      if (workspace_id) url += `&workspace_id=${workspace_id}`;
      if (event) url += `&event=${encodeURIComponent(event)}`;
      if (where) url += `&where=${encodeURIComponent(where)}`;
      if (on) url += `&on=${encodeURIComponent(on)}`;
      if (limit !== undefined) url += `&limit=${limit}`;
      
      // 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)
          }
        ]
      };
    } catch (error) {
      console.error('Error querying frequency report:', error);
      return {
        content: [
          {
            type: "text",
            text: `Error querying frequency report: ${error}`
          }
        ],
        isError: true
      };
    }
  }
);

server.tool(
  "query_segmentation_report",
  "Get data for an event, segmented and filtered by properties. Useful for breaking down event data by user attributes, comparing performance across segments, and identifying which user groups perform specific actions.",
  {
    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 property expression to segment the event on").optional(),
    unit: z.enum(["minute", "hour", "day", "month"]).describe("The buckets into which the property values that you segment on are placed. Default is 'day'").optional(),
    interval: z.number().describe("Optional parameter in lieu of 'unit' when 'type' is not 'general'. Determines the number of days your results are bucketed into").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'`),
    limit: z.number().describe("Return the top property values. Defaults to 60. Maximum value 10,000. This parameter does nothing if 'on' is not specified").optional(),
    type: z.enum(["general", "unique", "average"]).describe("The type of analysis to perform, either general, unique, or average, defaults to general").optional(),
    format: z.enum(["csv"]).describe("Can be set to 'csv'").optional(),
  },
  async ({ 
    project_id = DEFAULT_PROJECT_ID, 
    workspace_id, 
    event, 
    from_date, 
    to_date, 
    on, 
    unit, 
    interval, 
    where, 
    limit, 
    type, 
    format 
  }) => {
    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?project_id=${project_id}&event=${encodeURIComponent(event)}&from_date=${from_date}&to_date=${to_date}`;
      
      // Add optional parameters if they exist
      if (workspace_id) url += `&workspace_id=${workspace_id}`;
      if (on) url += `&on=${encodeURIComponent(on)}`;
      if (unit) url += `&unit=${unit}`;
      if (interval !== undefined) url += `&interval=${interval}`;
      if (where) url += `&where=${encodeURIComponent(where)}`;
      if (limit !== undefined) url += `&limit=${limit}`;
      if (type) url += `&type=${type}`;
      if (format) url += `&format=${format}`;
      
      // 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)
          }
        ]
      };
    } catch (error) {
      console.error('Error querying segmentation report:', error);
      throw error;
    }
  }
);

server.tool(
  "query_segmentation_bucket",
  "Get data for an event, segmented and filtered by properties, with values placed into numeric buckets. Useful for analyzing distributions of numeric values, creating histograms, and understanding the range of quantitative metrics.",
  {
    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 property expression to segment the event on. This expression must be a numeric property"),
    unit: z.enum(["hour", "day"]).describe("The buckets into which the property values that you segment on 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'`),
    type: z.enum(["general", "unique", "average"]).describe("The type of analysis to perform, either general, unique, or average, defaults to general").optional(),
  },
  async ({ 
    project_id = DEFAULT_PROJECT_ID, 
    workspace_id, 
    event, 
    from_date, 
    to_date, 
    on, 
    unit, 
    where, 
    type 
  }) => {
    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/numeric?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)}`;
      if (type) url += `&type=${type}`;
      
      // 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)
          }
        ]
      };
    } catch (error) {
      console.error('Error querying segmentation bucket:', error);
      return {
        content: [
          {
            type: "text",
            text: `Error querying segmentation bucket: ${error}`
          }
        ],
        isError: true
      };
    }
  }
);

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

server.tool(
  "top_event_properties",
  "Get the top property names for an event. Useful for discovering which properties are most commonly associated with an event, prioritizing which dimensions to analyze, and understanding event structure.",
  {
    project_id: z.string().describe("The Mixpanel project ID").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"),
    limit: z.number().describe("The maximum number of properties to return. Defaults to 10").optional(),
  },
  async ({ 
    project_id = DEFAULT_PROJECT_ID, 
    workspace_id, 
    event, 
    limit 
  }) => {
    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/events/properties/top?project_id=${project_id}&event=${encodeURIComponent(event)}`;
      
      // Add optional parameters if they exist
      if (workspace_id) url += `&workspace_id=${workspace_id}`;
      if (limit !== undefined) url += `&limit=${limit}`;
      
      // 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)
          }
        ]
      };
    } catch (error) {
      console.error('Error fetching top event properties:', error);
      return {
        content: [
          {
            type: "text",
            text: `Error fetching top event properties: ${error}`
          }
        ],
        isError: true
      };
    }
  }
);

server.tool(
  "top_event_property_values",
  "Get the top values for a property. Useful for understanding the distribution of values for a specific property, identifying the most common categories or segments, and planning further targeted analyses.",
  {
    project_id: z.string().describe("The Mixpanel project ID").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"),
    name: z.string().describe("The name of the property you would like to get data for"),
    limit: z.number().describe("The maximum number of values to return. Defaults to 255").optional(),
  },
  async ({ 
    project_id = DEFAULT_PROJECT_ID, 
    workspace_id, 
    event, 
    name,
    limit 
  }) => {
    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/events/properties/values?project_id=${project_id}&event=${encodeURIComponent(event)}&name=${encodeURIComponent(name)}`;
      
      // Add optional parameters if they exist
      if (workspace_id) url += `&workspace_id=${workspace_id}`;
      if (limit !== undefined) url += `&limit=${limit}`;
      
      // 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)
          }
        ]
      };
    } catch (error) {
      console.error('Error fetching top event property values:', error);
      return {
        content: [
          {
            type: "text",
            text: `Error fetching top event property values: ${error}`
          }
        ],
        isError: true
      };
    }
  }
);

async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("MIXPANEL MCP SERVER RUNNING ON STDIO")
}

main().catch((error) => {
  console.error("Fatal error in main(): ", error);
  process.exit(1);
})
```

--------------------------------------------------------------------------------
/.api/apis/mixpaneldevdocs/schemas.d.ts:
--------------------------------------------------------------------------------

```typescript
declare const ActivityStreamQuery: {
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
                readonly distinct_ids: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "A JSON array as a string representing the `distinct_ids` to return activity feeds for. For example: `[\"12a34aa567eb8d-9ab1c26f345b67-89123c45-6aeaa7-89f12af345f678\"]`";
                };
                readonly from_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to begin querying from. This date is inclusive.";
                };
                readonly to_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to query to. This date is inclusive.";
                };
            };
            readonly required: readonly ["project_id", "distinct_ids", "from_date", "to_date"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "object";
            readonly properties: {
                readonly status: {
                    readonly type: "string";
                };
                readonly results: {
                    readonly type: "object";
                    readonly properties: {
                        readonly events: {
                            readonly type: "array";
                            readonly items: {
                                readonly type: "object";
                                readonly properties: {
                                    readonly event: {
                                        readonly type: "string";
                                    };
                                    readonly properties: {
                                        readonly type: "object";
                                        readonly additionalProperties: true;
                                    };
                                };
                            };
                        };
                    };
                };
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
declare const CohortsList: {
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
            };
            readonly required: readonly ["project_id"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "array";
            readonly items: {
                readonly type: "object";
                readonly properties: {
                    readonly count: {
                        readonly type: "integer";
                    };
                    readonly is_visible: {
                        readonly type: "integer";
                        readonly description: "0 if not visible. 1 if visible";
                    };
                    readonly description: {
                        readonly type: "string";
                    };
                    readonly created: {
                        readonly type: "string";
                    };
                    readonly project_id: {
                        readonly type: "integer";
                    };
                    readonly id: {
                        readonly type: "integer";
                    };
                    readonly name: {
                        readonly type: "string";
                    };
                };
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
declare const EngageQuery: {
    readonly formData: {
        readonly properties: {
            readonly distinct_id: {
                readonly type: "string";
                readonly description: "A unique identifier used to distinguish an individual profile.";
            };
            readonly distinct_ids: {
                readonly type: "string";
                readonly description: "A JSON array of distinct_ids to retrieve profiles for.\nExample: `distinct_ids=[\"id1\", \"id2\"]`\n";
            };
            readonly data_group_id: {
                readonly type: "string";
                readonly description: "The ID of the group key, used when querying group profiles, click [here](https://docs.mixpanel.com/docs/data-structure/group-analytics#exporting-group-profiles-via-api) for more info.";
            };
            readonly where: {
                readonly type: "string";
                readonly description: "An expression to filter users (or groups) by. See the [expressions section](ref:segmentation-expressions) above.";
            };
            readonly output_properties: {
                readonly type: "array";
                readonly items: {
                    readonly type: "string";
                };
                readonly description: "A JSON array of names of properties you want returned.\nExample: `output_properties=[\"$last_name\", \"$email\", \"Total Spent\"]`\n\nThis parameter can drastically reduce the amount of data returned by the API when you're not interested in all properties and can speed up queries significantly.\n";
            };
            readonly session_id: {
                readonly type: "string";
                readonly description: "A string id provided in the results of a previous query. Using a session_id speeds up api response, and allows paging through results.";
            };
            readonly page: {
                readonly type: "integer";
                readonly description: "Which page of the results to retrieve. Pages start at zero. If the \"page\" parameter is provided, the session_id parameter must also be provided.";
            };
            readonly behaviors: {
                readonly type: "integer";
                readonly description: "If you are exporting user profiles using an event selector, you use a `behaviors` parameter in your request. `behaviors` and `filter_by_cohort` are mutually exclusive.";
            };
            readonly as_of_timestamp: {
                readonly type: "integer";
                readonly description: "This parameter is only useful when also using `behaviors`.\nIf you try to export more than 1k profiles using a `behaviors` parameter and you don't included the parameter `as_of_timestamp`, you'll see the following error:\n\n`request for page in uncached query for params`\n";
            };
            readonly filter_by_cohort: {
                readonly type: "string";
                readonly description: "Takes a JSON object with a single key called `id` whose value is the cohort ID. `behaviors` and `filter_by_cohort` are mutually exclusive.\n\nExample: `filter_by_cohort='{\"id\":12345}'`\n";
            };
            readonly include_all_users: {
                readonly type: "boolean";
                readonly description: "*\\*only applicable with `filter_by_cohort` parameter*\n\n`include_all_users=true` (default) include all distinct_ids even if they don’t have a user (or group) profile.\n\n`include_all_users=false` include only distinct_ids with user (or group) profile.\n";
            };
        };
        readonly type: "object";
        readonly $schema: "http://json-schema.org/draft-04/schema#";
    };
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
            };
            readonly required: readonly ["project_id"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "object";
            readonly properties: {
                readonly page: {
                    readonly type: "integer";
                    readonly description: "The page number of the results";
                };
                readonly page_size: {
                    readonly type: "integer";
                    readonly description: "The max number of results in a single page.";
                };
                readonly session_id: {
                    readonly type: "string";
                };
                readonly status: {
                    readonly type: "string";
                    readonly description: "Indicates whether the request was successful";
                };
                readonly total: {
                    readonly type: "integer";
                    readonly description: "The number of users in the results payload.";
                };
                readonly results: {
                    readonly type: "array";
                    readonly items: {
                        readonly type: "object";
                        readonly properties: {
                            readonly $distinct_id: {
                                readonly type: "integer";
                                readonly description: "The ID of the user";
                            };
                            readonly $properties: {
                                readonly type: "object";
                                readonly description: "The properties associated with the user";
                                readonly additionalProperties: true;
                            };
                        };
                    };
                };
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
declare const FunnelsListSaved: {
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
            };
            readonly required: readonly ["project_id"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "array";
            readonly items: {
                readonly type: "object";
                readonly properties: {
                    readonly funnel_id: {
                        readonly type: "integer";
                        readonly description: "The id of the funnel.";
                    };
                    readonly name: {
                        readonly type: "string";
                        readonly description: "The name of the funnel";
                    };
                };
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
declare const FunnelsQuery: {
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
                readonly funnel_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The funnel that you wish to get data for.";
                };
                readonly from_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to begin querying from. This date is inclusive.";
                };
                readonly to_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to query to. This date is inclusive.";
                };
                readonly length: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The number of units (defined by length_unit) each user has to complete the funnel, starting from the time they triggered the first step in the funnel. May not be greater than 90 days. Note that we will query for events past the end of to_date to look for funnel completions. This defaults to the value that was previously saved in the UI for this funnel.";
                };
                readonly length_unit: {
                    readonly type: "string";
                    readonly enum: readonly ["day", "hour", "minute", "second"];
                    readonly description: "The unit applied to the length parameter can be \"second\", \"minute\", \"hour\", or \"day\". Defaults to the value that was previously saved in the UI for this funnel.";
                    readonly examples: readonly ["day"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                };
                readonly interval: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The number of days you want each bucket to contain. The default value is 1.";
                };
                readonly unit: {
                    readonly type: "string";
                    readonly enum: readonly ["day", "week", "month"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "This is an alternate way of specifying interval and can be \"day\", \"week\", or \"month\".";
                };
                readonly on: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The property expression to segment the event on. See the [expression to segment](ref:segmentation-expressions) below.";
                };
                readonly where: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "An expression to filter events by. See the [expression to segment](ref:segmentation-expressions) below.";
                };
                readonly limit: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Return the top property values. Defaults to 255 if not explicitly included. Maximum value 10,000. This parameter does nothing if \\\"on\\\" is not specified.";
                };
            };
            readonly required: readonly ["project_id", "funnel_id", "from_date", "to_date"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "object";
            readonly properties: {
                readonly meta: {
                    readonly type: "object";
                    readonly properties: {
                        readonly dates: {
                            readonly type: "array";
                            readonly items: {
                                readonly type: "string";
                                readonly description: "Date in YYYY-mm-dd format";
                            };
                        };
                    };
                };
                readonly data: {
                    readonly type: "object";
                    readonly additionalProperties: {
                        readonly type: "object";
                        readonly properties: {
                            readonly steps: {
                                readonly type: "array";
                                readonly items: {
                                    readonly type: "object";
                                    readonly properties: {
                                        readonly count: {
                                            readonly type: "integer";
                                            readonly description: "Number of conversions.";
                                        };
                                        readonly goal: {
                                            readonly type: "string";
                                            readonly description: "The name of the event";
                                        };
                                        readonly step_conv_ratio: {
                                            readonly type: "number";
                                            readonly format: "float";
                                            readonly description: "Conversion from previous step";
                                            readonly minimum: -3.402823669209385e+38;
                                            readonly maximum: 3.402823669209385e+38;
                                        };
                                        readonly overall_conv_ratio: {
                                            readonly type: "number";
                                            readonly format: "float";
                                            readonly description: "Conversion from start of funnel";
                                            readonly minimum: -3.402823669209385e+38;
                                            readonly maximum: 3.402823669209385e+38;
                                        };
                                        readonly avg_time: {
                                            readonly type: "integer";
                                            readonly description: "mean time to convert; null for step 0.";
                                        };
                                        readonly avg_time_from_start: {
                                            readonly type: "integer";
                                            readonly description: "time to convert from first step.";
                                        };
                                        readonly event: {
                                            readonly type: "string";
                                            readonly description: "The name of the event";
                                        };
                                        readonly step_label: {
                                            readonly type: "string";
                                            readonly description: "same as event OR custom event name";
                                        };
                                        readonly custom_event: {
                                            readonly type: "boolean";
                                            readonly description: "`true` if the event is a custom event, otherwise key is not present";
                                        };
                                        readonly custom_event_id: {
                                            readonly type: "integer";
                                            readonly description: "Only present if the event is a custom event.";
                                        };
                                    };
                                };
                            };
                            readonly analysis: {
                                readonly type: "object";
                                readonly properties: {
                                    readonly completion: {
                                        readonly type: "integer";
                                        readonly description: "Count in final step";
                                    };
                                    readonly starting_amount: {
                                        readonly type: "integer";
                                        readonly description: "Count in first step";
                                    };
                                    readonly steps: {
                                        readonly type: "integer";
                                        readonly description: "Number of steps";
                                    };
                                    readonly worst: {
                                        readonly type: "integer";
                                        readonly description: "Step with highest drop off";
                                    };
                                };
                            };
                        };
                    };
                };
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
declare const InsightsQuery: {
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
                readonly bookmark_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The ID of your Insights report can be found from the url: `https://mixpanel.com/project/<YOUR_PROJECT_ID>/view/<YOUR_WORKSPACE_ID>/app/boards#id=12345&editor-card-id=%22report-<YOUR_BOOKMARK_ID>%22`";
                };
            };
            readonly required: readonly ["project_id", "bookmark_id"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "object";
            readonly properties: {
                readonly computed_at: {
                    readonly type: "string";
                };
                readonly date_range: {
                    readonly type: "object";
                    readonly properties: {
                        readonly from_date: {
                            readonly type: "string";
                        };
                        readonly to_date: {
                            readonly type: "string";
                        };
                    };
                };
                readonly headers: {
                    readonly type: "array";
                    readonly description: "Explanation of what the nested keys mean in `series`.";
                    readonly items: {
                        readonly type: "string";
                    };
                };
                readonly series: {
                    readonly type: "object";
                    readonly description: "Maps event name of event to an object with dates as keys and number of instances as values. For example:\n\n```json\n{\n  'Viewed page': {\n    '2020-08-17T00:00:00-07:00': 7832,\n    '2020-08-24T00:00:00-07:00': 6234,\n  }\n}\n```\n";
                    readonly additionalProperties: true;
                };
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
declare const ListRecentEvents: {
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
                readonly event: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The event or events that you wish to get data for, encoded as a JSON array. Example format: \"[\"play song\", \"log in\", \"add playlist\"]\".";
                };
                readonly type: {
                    readonly type: "string";
                    readonly enum: readonly ["general", "unique", "average"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The analysis type you would like to get data for - such as general, unique, or average events. Valid values: \"general\", \"unique\", or \"average\".";
                };
                readonly unit: {
                    readonly type: "string";
                    readonly enum: readonly ["minute", "hour", "day", "week", "month"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "This can be \"minute\", \"hour\", \"day\", \"week\", or \"month\". It determines the level of granularity of the data you get back. Note that you cannot get hourly uniques.";
                };
                readonly interval: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The number of \"units\" to return data for - minutes, hours, days, weeks, or months. 1 will return data for the current unit (minute, hour, day, week or month). 2 will return the current and previous units, and so on. Specify either interval or from_date and to_date.";
                };
                readonly from_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to begin querying from. This date is inclusive.";
                };
                readonly to_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to query to. This date is inclusive.";
                };
                readonly format: {
                    readonly type: "string";
                    readonly enum: readonly ["json", "csv"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The data return format, such as JSON or CSV. Options: \"json\" (default), \"csv\".";
                };
            };
            readonly required: readonly ["project_id", "event", "type", "unit", "from_date", "to_date"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "object";
            readonly properties: {
                readonly data: {
                    readonly type: "object";
                    readonly properties: {
                        readonly series: {
                            readonly type: "array";
                            readonly items: {
                                readonly type: "string";
                                readonly description: "All dates included in `values`";
                            };
                        };
                        readonly values: {
                            readonly type: "object";
                            readonly additionalProperties: {
                                readonly type: "object";
                                readonly description: "A mapping of the date of each unit to the number of events. (ex. {\"2010-05-30\": 6})";
                                readonly additionalProperties: true;
                            };
                            readonly description: "Keys are the names of events";
                        };
                    };
                };
                readonly legend_size: {
                    readonly type: "integer";
                    readonly description: "The number of events defined in `values`";
                };
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
declare const QueryEventProperties: {
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
                readonly event: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The event that you wish to get data for. Note: this is a single event name, not an array.";
                };
                readonly name: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The name of the property you would like to get data for.";
                };
                readonly values: {
                    readonly type: "array";
                    readonly items: {
                        readonly type: "string";
                    };
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The specific property values that you would like to get data for, encoded as a JSON array. Example: If you have a property \"gender\" you may have values \"male\", \"female\" and \"unknown\". If you just want data for female and unknown users, you can include a values property that looks like \"[\"female\", \"unknown\"]\".";
                };
                readonly type: {
                    readonly type: "string";
                    readonly enum: readonly ["general", "unique", "average"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The analysis type you would like to get data for - such as general, unique, or average events. Valid values: \"general\", \"unique\", or \"average\".";
                };
                readonly unit: {
                    readonly type: "string";
                    readonly enum: readonly ["minute", "hour", "day", "week", "month"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "This can be \"minute\", \"hour\", \"day\", \"week\", or \"month\". It determines the level of granularity of the data you get back. Note that you cannot get hourly uniques.";
                };
                readonly interval: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The number of \"units\" to return data for - minutes, hours, days, weeks, or months. 1 will return data for the current unit (minute, hour, day, week or month). 2 will return the current and previous units, and so on. Specify either interval or from_date and to_date.";
                };
                readonly from_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to begin querying from. This date is inclusive.";
                };
                readonly to_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to query to. This date is inclusive.";
                };
                readonly format: {
                    readonly type: "string";
                    readonly enum: readonly ["json", "csv"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The data return format, such as JSON or CSV. Options: \"json\" (default), \"csv\".";
                };
                readonly limit: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The maximum number of values to return. Defaults to 255.";
                };
            };
            readonly required: readonly ["project_id", "event", "name", "type", "unit", "from_date", "to_date"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "object";
            readonly properties: {
                readonly data: {
                    readonly type: "object";
                    readonly properties: {
                        readonly series: {
                            readonly type: "array";
                            readonly items: {
                                readonly type: "string";
                                readonly description: "All dates we have data for in the response.";
                            };
                        };
                        readonly values: {
                            readonly type: "object";
                            readonly additionalProperties: true;
                        };
                    };
                };
                readonly legend_size: {
                    readonly type: "integer";
                };
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
declare const QueryEventsTopProperties: {
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
                readonly event: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The event that you wish to get data for. Note: this is a single event name, not an array.";
                };
                readonly limit: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The maximum number of properties to return. Defaults to 10.";
                };
            };
            readonly required: readonly ["project_id", "event"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "object";
            readonly description: "The keys are the name of the properties";
            readonly additionalProperties: {
                readonly type: "object";
                readonly properties: {
                    readonly count: {
                        readonly type: "integer";
                        readonly description: "The number of events with that property";
                    };
                };
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
declare const QueryEventsTopPropertyValues: {
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
                readonly event: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The event that you wish to get data for. Note: this is a single event name, not an array.";
                };
                readonly name: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The name of the property you would like to get data for.";
                };
                readonly limit: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The maximum number of values to return. Defaults to 255.";
                };
            };
            readonly required: readonly ["project_id", "event", "name"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "array";
            readonly description: "Property values for the specified event property";
            readonly items: {
                readonly type: "string";
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
declare const QueryJql: {
    readonly formData: {
        readonly required: readonly ["script"];
        readonly properties: {
            readonly script: {
                readonly type: "string";
                readonly default: "function main(){\n  return Events(params)\n    .groupBy(\n      [\"name\"],\n      mixpanel.reducer.count()\n    )\n}\n";
                readonly description: "The script to run.";
                readonly examples: readonly ["function main(){\n  return Events(params)\n    .groupBy(\n      [\"name\"],\n      mixpanel.reducer.count()\n    )\n}\n"];
            };
            readonly params: {
                readonly type: "string";
                readonly format: "blob";
                readonly default: "{\n  \"scriptParam\": \"paramValue\"\n}\n";
                readonly description: "A JSON-encoded object that will be made available to the script as the params global variable.";
                readonly examples: readonly ["{\n  \"from_date\": 2016-01-01T00:00:00.000Z,\n  \"to_date\": 2016-01-07T00:00:00.000Z\n}\n"];
            };
        };
        readonly type: "object";
        readonly $schema: "http://json-schema.org/draft-04/schema#";
    };
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
            };
            readonly required: readonly ["project_id"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "array";
            readonly items: {
                readonly type: "object";
                readonly additionalProperties: true;
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
declare const QueryMonthsTopEventNames: {
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
                readonly type: {
                    readonly type: "string";
                    readonly enum: readonly ["general", "unique", "average"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The analysis type you would like to get data for - such as general, unique, or average events. Valid values: \"general\", \"unique\", or \"average\".";
                };
                readonly limit: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The maximum number of values to return. Defaults to 255.";
                };
            };
            readonly required: readonly ["project_id", "type"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "array";
            readonly description: "List of names in descending alphabetical order.";
            readonly items: {
                readonly type: "string";
                readonly description: "Event name";
                readonly examples: readonly ["Viewed page"];
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
declare const QueryTopEvents: {
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
                readonly type: {
                    readonly type: "string";
                    readonly enum: readonly ["general", "unique", "average"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The analysis type you would like to get data for - such as general, unique, or average events. Valid values: \"general\", \"unique\", or \"average\".";
                };
                readonly limit: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The maximum number of events to return. Defaults to 100.";
                };
            };
            readonly required: readonly ["project_id", "type"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "object";
            readonly properties: {
                readonly events: {
                    readonly type: "array";
                    readonly items: {
                        readonly type: "object";
                        readonly properties: {
                            readonly amount: {
                                readonly type: "integer";
                                readonly description: "Number of events";
                            };
                            readonly event: {
                                readonly type: "string";
                                readonly description: "The name of the event";
                            };
                            readonly percent_change: {
                                readonly type: "number";
                                readonly format: "float";
                                readonly description: "The percent change from yesterday";
                                readonly minimum: -3.402823669209385e+38;
                                readonly maximum: 3.402823669209385e+38;
                            };
                        };
                    };
                };
                readonly type: {
                    readonly type: "string";
                };
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
declare const RetentionFrequencyQuery: {
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
                readonly from_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to begin querying from. This date is inclusive.";
                };
                readonly to_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to query to. This date is inclusive.";
                };
                readonly unit: {
                    readonly type: "string";
                    readonly enum: readonly ["day", "week", "month"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The overall time period to return frequency of actions for can be \"day\", \"week\", or \"month\".";
                };
                readonly addiction_unit: {
                    readonly type: "string";
                    readonly enum: readonly ["hour", "day"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The granularity to return frequency of actions at can be \"hour\" or \"day\".";
                };
                readonly event: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The event to generate returning counts for.";
                };
                readonly where: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "An expression to filter the returning events by. See the [expressions section](ref:segmentation-expressions) above.";
                };
                readonly on: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The property expression to segment the second event on. See the [expressions section](ref:segmentation-expressions) above.";
                };
                readonly limit: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Return the top limit segmentation values. This parameter does nothing if \"on\" is not specified.";
                };
            };
            readonly required: readonly ["project_id", "from_date", "to_date", "unit", "addiction_unit"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "object";
            readonly properties: {
                readonly data: {
                    readonly type: "object";
                    readonly additionalProperties: {
                        readonly type: "array";
                        readonly items: {
                            readonly type: "integer";
                        };
                    };
                };
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
declare const RetentionQuery: {
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
                readonly from_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to begin querying from. This date is inclusive.";
                };
                readonly to_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to query to. This date is inclusive.";
                };
                readonly retention_type: {
                    readonly type: "string";
                    readonly enum: readonly ["birth", "compounded"];
                    readonly examples: readonly ["birth"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Must be either \"birth\" or \"compounded\". Defaults to \"birth\". The “birth” retention type corresponds to first time retention. The “compounded” retention type corresponds to recurring retention. See the [Types of Retention](https://help.mixpanel.com/hc/en-us/articles/360001370146) article for more information.";
                };
                readonly born_event: {
                    readonly type: "string";
                    readonly examples: readonly ["Added to cart"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The first event a user must do to be counted in a birth retention cohort. Required when retention_type is \"birth\"; ignored otherwise.";
                };
                readonly event: {
                    readonly type: "string";
                    readonly examples: readonly ["Viewed report"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The event to generate returning counts for. Applies to both birth and compounded retention. If not specified, we look across all events.";
                };
                readonly born_where: {
                    readonly type: "string";
                    readonly examples: readonly ["properties[\"$os\"]==\"Linux\""];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "An expression to filter born_events by. See the [expressions section](ref:segmentation-expressions) above.";
                };
                readonly where: {
                    readonly type: "string";
                    readonly examples: readonly ["properties[\"$os\"]==\"Linux\""];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "An expression to filter born_events by. See the [expressions section](ref:segmentation-expressions) above.";
                };
                readonly interval: {
                    readonly type: "integer";
                    readonly examples: readonly [1];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The number of units (can be specified in either days, weeks, or months) that you want per individual bucketed interval. May not be greater than 90 days if days is the specified unit. The default value is 1.";
                };
                readonly interval_count: {
                    readonly type: "integer";
                    readonly examples: readonly [1];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The number of individual buckets, or intervals, that are returned; defaults to 1. Note that we include a \"0th\" interval for events that take place less than one interval after the initial event.";
                };
                readonly unit: {
                    readonly type: "string";
                    readonly enum: readonly ["day", "week", "month"];
                    readonly examples: readonly ["day"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The interval unit. It can be \"day\", \"week\", or \"month\". Default is \"day\".";
                };
                readonly unbounded_retention: {
                    readonly type: "boolean";
                    readonly default: false;
                    readonly examples: readonly [false];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "A counting method for retention queries where retention values accumulate from right to left, i.e. day N is equal to users who retained on day N and any day after. The default value of false does not perform this accumulation. [Learn more about Counting Method](https://help.mixpanel.com/hc/en-us/articles/360045484191).";
                };
                readonly on: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The property expression to segment the second event on. See the [expressions section](ref:segmentation-expressions) above.";
                };
                readonly limit: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Return the top limit segmentation values. This parameter does nothing if \"on\" is not specified.";
                };
            };
            readonly required: readonly ["project_id", "from_date", "to_date"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "object";
            readonly additionalProperties: {
                readonly type: "object";
                readonly properties: {
                    readonly counts: {
                        readonly type: "array";
                        readonly items: {
                            readonly type: "integer";
                        };
                    };
                    readonly first: {
                        readonly type: "integer";
                    };
                };
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
declare const SegmentationNumericQuery: {
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
                readonly event: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The event that you wish to get data for. Note: this is a single event name, not an array.";
                };
                readonly from_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to begin querying from. This date is inclusive.";
                };
                readonly to_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to query to. This date is inclusive.";
                };
                readonly on: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The property expression to segment the event on. This expression must be a numeric property. See the [expressions section](ref:segmentation-expressions) below.";
                };
                readonly unit: {
                    readonly type: "string";
                    readonly enum: readonly ["hour", "day"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "This can be \"hour\" or \"day\". This determines the buckets into which the property values that you segment on are placed. The default value is \"day\".";
                };
                readonly where: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "An expression to filter events by. See the [expression to segment](ref:segmentation-expressions) below.";
                };
                readonly type: {
                    readonly type: "string";
                    readonly enum: readonly ["general", "unique", "average"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "This can be \"hour\" or \"day\". This determines the buckets into which the property values that you segment on are placed. The default value is \"day\".";
                };
            };
            readonly required: readonly ["project_id", "event", "from_date", "to_date", "on"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "object";
            readonly properties: {
                readonly data: {
                    readonly type: "object";
                    readonly properties: {
                        readonly series: {
                            readonly type: "array";
                            readonly items: {
                                readonly type: "string";
                                readonly description: "All dates we have data for in the response.";
                            };
                        };
                        readonly values: {
                            readonly type: "object";
                            readonly additionalProperties: {
                                readonly type: "object";
                                readonly description: "The range of the bucket";
                                readonly additionalProperties: {
                                    readonly type: "integer";
                                    readonly description: "A mapping of the date of each unit to the number of specified events that took place. (ex. {\"2010-05-30\": 6})";
                                };
                            };
                        };
                    };
                };
                readonly legend_size: {
                    readonly type: "integer";
                    readonly description: "List of all dates.";
                };
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
declare const SegmentationQuery: {
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
                readonly event: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The event that you wish to get data for. Note: this is a single event name, not an array.";
                };
                readonly from_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to begin querying from. This date is inclusive.";
                };
                readonly to_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to query to. This date is inclusive.";
                };
                readonly on: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The property expression to segment the event on. See the [expression to segment](ref:segmentation-expressions) below.";
                };
                readonly unit: {
                    readonly type: "string";
                    readonly enum: readonly ["minute", "hour", "day", "month"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "This can be \"minute\", \"hour\", \"day\", or \"month\". This determines the buckets into which the property values that you segment on are placed. The default value is \"day\".";
                };
                readonly interval: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Optional parameter in lieu of 'unit' when 'type' is not 'general'. Determines the number of days your results are bucketed into can be used with or without 'from_date' and 'to_date' parameters.";
                };
                readonly where: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "An expression to filter events by. See the [expression to segment](ref:segmentation-expressions) below.";
                };
                readonly limit: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Return the top property values. Defaults to 60. Maximum value 10,000. This parameter does nothing if \"on\" is not specified.";
                };
                readonly type: {
                    readonly type: "string";
                    readonly enum: readonly ["general", "unique", "average"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "This can be \"general\", \"unique\", or \"average\". If this is set to \"unique\", we return the unique count of events or property values. If set to \"general\", we return the total, including repeats. If set to \"average\", we return the average count. The default value is \"general\".";
                };
                readonly format: {
                    readonly type: "string";
                    readonly enum: readonly ["csv"];
                    readonly description: "Can be set to \"csv\".";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                };
            };
            readonly required: readonly ["project_id", "event", "from_date", "to_date"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "object";
            readonly properties: {
                readonly data: {
                    readonly type: "object";
                    readonly properties: {
                        readonly series: {
                            readonly type: "array";
                            readonly items: {
                                readonly type: "string";
                                readonly description: "All dates we have data for in the response.";
                            };
                        };
                        readonly values: {
                            readonly type: "object";
                            readonly additionalProperties: true;
                        };
                    };
                };
                readonly legend_size: {
                    readonly type: "integer";
                    readonly description: "List of all dates.";
                };
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
declare const SegmentationQueryAverage: {
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
                readonly event: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The event that you wish to get data for. Note: this is a single event name, not an array.";
                };
                readonly from_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to begin querying from. This date is inclusive.";
                };
                readonly to_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to query to. This date is inclusive.";
                };
                readonly on: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The expression to sum per unit time. The result of the expression should be a numeric value. If the expression is not numeric, a value of 0.0 is assumed. See the [expressions section](ref:segmentation-expressions) below.";
                };
                readonly unit: {
                    readonly type: "string";
                    readonly enum: readonly ["hour", "day"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "This can be \"hour\" or \"day\". This determines the buckets into which the property values that you segment on are placed. The default value is \"day\".";
                };
                readonly where: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "An expression to filter events by. See the [expression to segment](ref:segmentation-expressions) below.";
                };
            };
            readonly required: readonly ["project_id", "event", "from_date", "to_date", "on"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "object";
            readonly properties: {
                readonly results: {
                    readonly type: "object";
                    readonly additionalProperties: {
                        readonly type: "number";
                        readonly format: "float";
                        readonly minimum: -3.402823669209385e+38;
                        readonly maximum: 3.402823669209385e+38;
                    };
                };
                readonly status: {
                    readonly type: "string";
                };
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
declare const SegmentationSumQuery: {
    readonly metadata: {
        readonly allOf: readonly [{
            readonly type: "object";
            readonly properties: {
                readonly project_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "Required if using service account to authenticate request.";
                };
                readonly workspace_id: {
                    readonly type: "integer";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The id of the workspace if applicable.";
                };
                readonly event: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The event that you wish to get data for. Note: this is a single event name, not an array.";
                };
                readonly from_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to begin querying from. This date is inclusive.";
                };
                readonly to_date: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The date in yyyy-mm-dd format to query to. This date is inclusive.";
                };
                readonly on: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "The expression to sum per unit time. The result of the expression should be a numeric value. If the expression is not numeric, a value of 0.0 is assumed. See the [expressions section](ref:segmentation-expressions) below.";
                };
                readonly unit: {
                    readonly type: "string";
                    readonly enum: readonly ["hour", "day"];
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "This can be \"hour\" or \"day\". This determines the buckets into which the property values that you segment on are placed. The default value is \"day\".";
                };
                readonly where: {
                    readonly type: "string";
                    readonly $schema: "http://json-schema.org/draft-04/schema#";
                    readonly description: "An expression to filter events by. See the [expression to segment](ref:segmentation-expressions) below.";
                };
            };
            readonly required: readonly ["project_id", "event", "from_date", "to_date", "on"];
        }];
    };
    readonly response: {
        readonly "200": {
            readonly type: "object";
            readonly properties: {
                readonly status: {
                    readonly type: "string";
                };
                readonly computed_at: {
                    readonly type: "string";
                };
                readonly results: {
                    readonly type: "object";
                    readonly additionalProperties: {
                        readonly type: "integer";
                    };
                };
            };
            readonly $schema: "http://json-schema.org/draft-04/schema#";
        };
    };
};
export { ActivityStreamQuery, CohortsList, EngageQuery, FunnelsListSaved, FunnelsQuery, InsightsQuery, ListRecentEvents, QueryEventProperties, QueryEventsTopProperties, QueryEventsTopPropertyValues, QueryJql, QueryMonthsTopEventNames, QueryTopEvents, RetentionFrequencyQuery, RetentionQuery, SegmentationNumericQuery, SegmentationQuery, SegmentationQueryAverage, SegmentationSumQuery };

```
Page 1/3FirstPrevNextLast