PostHog MCP server for AI agents

Live

OAUTH 2.1

PRODUCT ANALYTICS

Analytics

Every event, funnel, and feature flag your product team tracks lives in PostHog. PostHog MCP gives your agent authenticated access to product analytics scoped to the user who authorized it.

  • Acts as the user: Access and write actions stay tied to the PostHog MCP account that authorized the agent.
  • Credentials stay vaulted: AES-256, resolved at request time, never in LLM context.
  • Scoped before every call: Permissions enforced. 90-day audit trail.
PostHog MCP
agent · Acme Q3
Run
What is the 7-day activation funnel completion rate for users who signed up this week?
S
posthogmcp_exec
88ms
Product analytics agent
7-day activation funnel: 1,240 signed up, 847 completed onboarding (68%), 612 reached first value moment (49%), 388 activated (31%). Drop-off largest at step 2 — onboarding form.
Sources: signups this week, activation funnel
posthogmcpmcp
1 query
18:29
Message Claude...

Tools your product analytics agent reaches for on PostHog MCP, scoped per user.

CALL ANY TOOL
Query events with HogQL, list insights and dashboards, check feature flag rollout, browse persons and cohorts.
posthogmcp_exec
Exec
### Using the `posthog` tool PostHog makes your product self-driving: it reads your data and ships changes with you, never without you. Spans analytics, experiments, flags, replay, and more. Pass CLI-style commands in the `command` parameter for all PostHog interactions. **Requirements** 1. Find unknown tools with `search` or `tools`. 2. Run `info <tool_name>` once if its schema is not in context. Reuse it unless the tool changes or a schema error occurs. Never guess a schema or run `info` before every call. **Commands (in order):** ```text # 1. Find unknown tools posthog:exec({ "command": "search <regex>" }) posthog:exec({ "command": "tools" }) # fallback: list all # 2. Inspect once if the schema is missing posthog:exec({ "command": "info <tool_name>" }) # 3. Drill into complex fields, REQUIRED for any field with a `hint` posthog:exec({ "command": "schema <tool_name> <field_path>" }) # 4. Call; reuse the schema posthog:exec({ "command": "call <tool_name> <json_input>" }) posthog:exec({ "command": "call --json <tool_name> <json_input>" }) ``` **Schema drill-down:** - `info` returns the full schema if it fits the token budget; otherwise it auto-summarizes (names, types, required, enums, defaults) and attaches `hint` entries pointing to `schema <tool> <path>` for complex fields. - `schema <tool>` (no path) returns the summarized top-level schema. - `schema <tool> <path>` resolves a dot path, descending through: - object `properties` (e.g. `query.source`) - array `items`, numeric segments step into items (`events.0.properties`), or jump to a property on the item type (`events.id`) - `anyOf`/`oneOf`, numeric segment picks a variant by index, or a property name matches any object variant defining it - Oversized sub-schemas are also summarized with a `note` to drill further. - Unknown paths return an error listing available child paths. **Not supported:** - `search` matches tool metadata only, not input schemas. - No pattern-based field projection, drill one path at a time.
Parameters
Name
Type
Required
Description
command
string
Required
CLI-style command string. Supported commands: ```text help [command], list commands or show usage for one command tools, list available tool names search <words or regex_pattern>, find tools by name, title, or description info [--json] <tool_name>, show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output. schema <tool_name> [field_path], drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns) call [--json] [--confirm] <tool_name> [json_input], call a tool with JSON input (--json returns JSON instead of optimized output in supported tools. Informational responses remain tagged and escaped in both MCP and the agent CLI. --confirm is required by the CLI for destructive tools.) ``` **One command per request.** `exec` has no batch syntax. A request that stacks several commands on separate lines is rejected before any of them run. To run several commands, send several `exec` calls. You can issue them in parallel. **Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ "command": "info insights-list" })` then `posthog:exec({ "command": "call insights-list {}" })`. If the bare name isn't found, fall back to `search <pattern>`, it may have been renamed. **SKILLS FIRST: HARD REQUIREMENT** Skills are the authoritative, instance-versioned docs for PostHog behavior: warning thresholds, scoring and visibility rules, query patterns, system-table schemas. Public docs, web search, and the PostHog GitHub repo may not match this instance, never clone, grep, or web-search PostHog internals for facts a skill can serve. For non-trivial PostHog/team work, first run `learn -s "<task keywords>"`, even if unasked. Run it alone: never batch or parallelize it with schema, info, search, or call. Wait, load matches, then continue. Trivial means repeating a lookup you already made this session; any question about a PostHog feature's behavior or data is not trivial. Load exact qualified names; never guess. Follow `SKILL.md`; fetch references on demand. If no match, continue. Advertised topics load separately. Syntax: `learn [skills|-s "<up to 8 keywords>"|-d <name...>|(posthog|project):<skill> [path...] [-s "<up to 8 keywords>"|--lines <start>:<end>]]` <example> User: At what exposure share does the experiment bias warning fire? Assistant: [Runs only `learn -s "experiment bias warning"`; waits. Loads `posthog:diagnosing-experiment-health`, reads `references/bias-and-skew.md`, answers from it, no web search, no source clone.] </example> #### Metric discovery (semantic layer) Catalog-first is decided by request shape, not by whether the noun sounds like a KPI: a count, sum, or amount of X per day/hour/week/month/year, a rate or percentage of X, an average/percentile/latency of X, a cost per X, or a conversion between two events, plus their rankings, breakdowns, comparisons, synonyms, derived forms, and definition questions. X is anything the product records: sessions, 404s, tickets, tool calls, revenue. Label derivations noncanonical in `context`, and say plainly in the answer that the number is a one-off, not a saved definition. One-off exploration and debugging aggregates stay schema-first. The first call for that shape is `metric-list`; `read-data-schema`, `info query-*`, and `search <noun>` are not substitutes. It outranks 'Retrieving data', typed domain tools, and any skill's query recipe. Read every page. `exec search` finds tools, not catalog rows. **SCHEMA DRILL-DOWN RULE, HARD REQUIREMENT** The `info` command may return the full schema (for simple tools) or a top-level summary with drill-down hints (for complex tools). Look for `hint` fields in the response. If `info` returned a summary (fields have `hint` values), call `schema <tool_name> <field_name>` for each field you need to populate BEFORE constructing that field's value in a `call` command. If `schema` also returns a summary (because the field is too large), drill deeper using dot-notation: `schema <tool> <field>.<subfield>`. **NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first. For query tools, you will typically need: **For multiple tools:** Run `info` for ALL tools first, then make your `call` commands. **Data discovery:** After the metric check, before any analytical `call` that touches collected data (`query-*`, `execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via `call read-data-schema`. Applies to canonical-looking names like `$pageview` too, they vary per team. If the event isn't in the schema, tell the user instead of querying a guessed name. Always run `info read-data-schema` first, the recipes below are common cases, not the full schema. **CORRECT usage pattern:** <example> User: How many weekly active users do we have? Assistant: A weekly count is a governed shape, so the catalog comes first. [Runs posthog:exec({ "command": "call metric-list {\"limit\": 100}" })] Assistant: No approved metric covers weekly active users, so I fall through to the query tools and confirm the schema. [Runs posthog:exec({ "command": "search query-trends" }) and posthog:exec({ "command": "search read-data" }) in parallel] Assistant: Let me check the tool descriptions and schemas. [Runs posthog:exec({ "command": "info query-trends" }) and posthog:exec({ "command": "info read-data-schema" }) in parallel] Assistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events. [Runs posthog:exec({ "command": "schema query-trends series" }) and posthog:exec({ "command": "call read-data-schema {\"query\": {\"kind\": \"events\"}}" }) in parallel] Assistant: Now I know the exact series structure and available events. Let me construct the query. [Runs posthog:exec({ "command": "call query-trends {...}" })] </example> <example> User: Create a dashboard for our key revenue metrics Assistant: I'll need dashboard and query tools. Let me search for them. [Runs posthog:exec({ "command": "search dashboard" }) and posthog:exec({ "command": "search execute-sql" }) in parallel] Assistant: Let me check the schemas for the tools I'll need. [Runs posthog:exec({ "command": "info dashboard-create" }) and posthog:exec({ "command": "info execute-sql" }) in parallel] Assistant: Now I have both schemas. Let me start by searching for existing revenue insights. [Makes call commands with correct parameters] </example> **INCORRECT usage patterns, NEVER do this:** <bad-example> User: Show me our feature flags Assistant: [Directly calls posthog:exec({ "command": "call feature-flag-get-all {}" }) with guessed parameters] WRONG: Run `info feature-flag-get-all` once when its schema is missing. </bad-example> <bad-example> User: Query our events Assistant: [Calls three tools in parallel without any `info` calls first] WRONG: Run `info` once for each missing schema. </bad-example> <bad-example> User: Show me a trends chart of signups Assistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure] WRONG, info returned a summary with hint: "DO NOT GUESS, run `schema query-trends series` before populating this field". You MUST follow the hint and run `schema` before constructing the series field. </bad-example> <bad-example> User: query pageviews for the last 7 days Assistant: [Runs `info query-trends`, then `call query-trends` with `event: "$pageview"` from the prompt] WRONG, skipped `call read-data-schema {"query": {"kind": "events"}}`. Never query an event name taken or inferred from the prompt, canonical-looking (`$pageview`) or guessed (`downloaded_file`) names still need per-team confirmation. </bad-example> **Handling errors:** ### Basic functionality PostHog makes the user's product self-driving: it reads their product data and ships changes with them, never without them, read freely, but make changes only with the user's direction. You work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user. Collected data (used for analytics): events (recorded from SDKs, always associated with persons and sometimes groups); persons and groups (captured individuals or groups of individuals); sessions; properties and property values (key-value metadata for segmenting events, actions, persons, groups, etc.); session recordings (captured web/mobile interactions). Created data (the user's business activity in PostHog): actions (unify multiple events or filter conditions into one); insights; data warehouse (connected sources and custom views); SQL queries (ClickHouse SQL over collected data and the warehouse schema); surveys (questionnaires, e.g. NPS); dashboards; cohorts (person groups for segmentation); feature flags (rollout control); experiments (A/B tests); notebooks; error tracking issues; logs (with severity, service, and trace information); workflows (triggers, actions, conditions); activity logs (who changed what, when, and how). IMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks. If you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project. ### Tool search **Always prefer `search` over `tools`**, `tools` returns every tool and wastes tokens. Use `search <query>` to find what you need. `search` understands two kinds of query: Quotes are ignored. A regex that matches no tool falls back to ranking by its words, so a guessed name such as "project-update" still returns the nearest tools. **Good queries:** **Avoid queries that are too broad** (match dozens of tools): `search data`, `search get list create`, they match almost everything. Only fall back to `tools` if you have no idea which domain to search, or if `search` returns no results. PostHog tools have lowercase kebab-case naming. Tools are organized by category: Typical action names: list/retrieve/get/create/update/delete/query. Example tool names: execute-sql, experiment-create, feature-flag-get-all. ### Retrieving data Choose the query method from the requested result and calculation rules, after any metric-routing rules above. Reuse a matching approved metric or saved query when it defines the requested measure. SQL discovery can inform the events, properties, and filters for a later typed query; typed tools cannot accept SQL result rows as input. Reassess the method when the task changes, regardless of the previous tool call. Save supported dashboard analyses as native query nodes rather than equivalent `HogQLQuery` nodes. Both methods support visualizations; a chart request or missing inline UI does not justify switching to SQL. Read the selected tool's description and schema when they are not already in context. You do not need to inspect every alternative before using SQL. #### Searching for existing entities "find / which / do we have / what's our X chart" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks. This routing is for finding **saved artifacts** (a chart, dashboard, cohort, flag). "What data / tables / events do we have available?" is a schema question instead, answer it from `system.information_schema.tables` (and `read-data-schema` for events), not by searching `system.insights`. Required order on every run, no shortcuts, schema first, every run: 1. Confirm the table's columns with an `execute-sql` against `system.information_schema.columns`, e.g. `SELECT column_name, data_type, description FROM system.information_schema.columns WHERE table_name = 'system.insights'`. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute, query the schema. 2. `execute-sql` against `system.*`, uses only columns confirmed in step 1. 3. `<entity>-get` (e.g. `insight-get`, `dashboard-get`), verifies the entity shape; do NOT re-`execute-sql` by ID. <bad-example> User: rename / find / list … (any `system.*` question) Assistant: [Calls `execute-sql` against `system.insights` without first confirming its columns via `system.information_schema.columns`, OR checks the schema partway through, only after several `execute-sql` calls thrashed] WRONG, the rule is "schema first, every run, no shortcuts." Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against a `system.*` entity table MUST be preceded by an `execute-sql` against `system.information_schema.columns` for that table in the same run. Skipping or postponing the schema check is a hard violation. </bad-example> #### Available insight query tools #### Choosing the right query tool Bare "retention" and "customers" are catalog terms that may have several approved definitions. Consult the catalog and clarify materially different matches instead of routing directly to an insight query. For tasks that need these native analyses: Each `query-*` tool's own description carries its full feature set, use cases, and schema documentation, read it (e.g. `info query-trends`) before constructing the query. #### Read the query guidance Before selecting a query method, read the `querying-posthog-data` skill once if it is installed. Follow its query-selection guidance and relevant examples. It is a built-in PostHog skill, not a team skill: do not fetch it with `skill-get`. If it is not installed, use the available tool descriptions. #### Schema-first workflow After the metric-discovery check, verify the data schema before constructing any insight query. Canonical-looking events (`$pageview`, `$identify`, `$autocapture`, …) still need confirmation, they can be absent, renamed, or filtered per team. Every `read-data-schema` call takes one `query` object, so send the whole payload under `query`. 1. **Discover events** - `{"query": {"kind": "events"}}` to find events matching the user's intent. 2. **Discover properties** - `{"query": {"kind": "event_properties", "event_name": "<event>"}}` for an event, or `{"query": {"kind": "entity_properties", "entity": "<entity>"}}` for a person, session, or group type (use the group type name for a group). 3. **Verify property values** - `{"query": {"kind": "event_property_values", "event_name": "<event>", "property_name": "<property>"}}` when the value must match (e.g., "US" vs "United States"). 4. **Then construct the query** using the selected method. For SQL table schemas, also follow the `execute-sql` schema-discovery guidance. If the required events or properties don't exist, tell the user instead of running an empty query. #### Insight query workflow After schema verification, construct a minimal query with the selected tool. Include only the filters, breakdowns, and settings required for the answer. Execute the query and analyze the result. Save an insight or add it to a dashboard when the user requests it. For complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment. #### Catalog trust signals Before writing SQL, check the catalog's trust layer: ### Where an analysis lands When work produces something worth keeping, pick the artifact before you start building it, say which one you're creating and why, and switch if the user asks for the other. **Notebook** (`search notebooks-` for the tools), the default for an analysis with a narrative: a question investigated step by step, where the reader needs the reasoning, the intermediate steps, and the caveats, not just the final number. Deep dives, one-off investigations, "why did X change", segmentation and cohort studies, data validation, anything whose answer is an argument rather than a metric. Notebooks interleave prose with query and analysis cells, so the method stays next to the result and the reader can re-run it. **Dashboard** (`dashboard-create` plus `dashboard-widgets-batch-add`), for a set of metrics someone will check repeatedly over time: monitoring, weekly or monthly tracking, team and exec overviews, launch and health boards. Reach for a dashboard when the deliverable is tiles that auto-refresh and still make sense next month, not a story with a conclusion. **Saved insight**, a single chart answering one question, standalone or as a building block for either of the above. Default to a notebook when the request reads as "look into", "understand", "figure out why", or "is X true", a dashboard answers those with a wall of tiles and no conclusion. Default to a dashboard when it reads as "track", "monitor", "keep an eye on", or "report every week". If a deep dive also turns up a few metrics worth watching, write the notebook and save just those as insights; don't demote the investigation into a dashboard. ### Explaining a chart When the person gives you a saved trends insight, by link or short ID, and asks why it changed or asks you to explain it, load the `posthog:investigate-metric` skill and follow it. Its answer is the chart explanation from `explain-chart` in the conversation, not a notebook: for that question, this replaces the notebook default above. Write a notebook as well only when the person asks for one to keep. ### SQL in an analysis When the deliverable is a notebook, build the analysis in it as you go, not after. Create the notebook first with a title and the question, then add each query that a reported number depends on as a SQL cell (`notebooks-add-cell` with `cell_type: 'sql'`). A finished run returns the columns and a row preview, while a run that is still going returns only its status: wait for the result, and read it before you write the prose that interprets it. Use `execute-sql` only for throwaway checks the notebook does not rely on, like confirming a table's columns. ### Python in an analysis When an analysis needs Python, dataframe manipulation, statistics, clustering, forecasting, plotting, anything SQL can't express, run it in a notebook Python cell (`notebooks-add-cell` with `cell_type: 'python'`), not in a runtime the user can't see. The point is transparency: the code, its output, and its errors sit in the document next to the result, and the user can read, edit, and re-run them. A number produced in a hidden interpreter is one they have to take on faith. Do this by default, without being asked, whenever the Python is part of the analysis being delivered. Create a notebook for it if none exists yet. Python cells read upstream cells' dataframes by name, so the usual shape is: SQL cell pulls the data → Python cell analyzes it → markdown cell says what it means. The sandbox has pandas, numpy, scipy, scikit-learn, and matplotlib. The exception is throwaway scratch work that isn't part of the deliverable, like a quick sanity check on a figure. If a computation is load-bearing for a conclusion you report, it belongs in a cell. To refresh a notebook somebody already wrote, use `notebooks-run` rather than re-running the cells one at a time. It runs every SQL and Python cell in document order and can set the notebook's variables in the same call, so a report for a new time window is one call. ### Active environment Call `project-get` without an ID to read the active project: its name, id, organization, timezone, person-on-events mode, test account filter default, and enabled products. Call it before you rely on one of these, for example the timezone for a date range. To work in another project or organization, call `switch-project` or `switch-organization`. `projects-get` and `organizations-get` resolve a name to the id they take. Do not search the tool list for this. For the project's group types, run `execute-sql` on `system.group_type_mappings`. ### URL patterns PostHog app links must be full URLs (origin + path), bare paths aren't clickable in MCP clients like Cursor or Claude Desktop. Use Markdown with descriptive anchor text, e.g. `[Cohorts](https://us.posthog.com/project/1/cohorts)`. Never include `/-/`. Choose the link source in this order: 1. If a tool result has a `*url` field (e.g. `_posthogUrl`), surface it verbatim, never rewrite or strip it. 2. Only when you actually want to link a specific entity (or the user asks for a link) and it has no `_posthogUrl`, call `generate-app-url` and surface the `url` verbatim, don't hand-write slugs or retype IDs into paths, both are easy to get wrong. Don't fetch a link just because a result has an ID. 3. Only for genuinely static pages not in the `generate-app-url` catalog (some settings pages), take the origin from a PostHog URL you already have (any `_posthogUrl`, or a `generate-app-url` result). Then build the link (don't double-prefix): ### Sharing feedback on PostHog The `agent-feedback` tool is a direct channel to the PostHog team for feedback about **anything PostHog**, a product or feature you (or the user) hit a rough edge with, this MCP server itself, the docs, or a capability that's missing. Use it whenever you or the user run into something worth telling the PostHog team, on any surface. Set `feedback_type` to route it: **All sentiments are welcome**, set `sentiment` to `positive`, `neutral`, `negative`, or `mixed`. Unlike a bug tracker, praise and feature requests are useful signal too, not just problems. Good triggers: a confusing or broken product experience, a papercut that slowed the task down, a missing capability you had to work around, a feature request, an unhelpful error, or something that worked really well and is worth reinforcing. Keep it short and actionable: a one-sentence `summary`, then the detail fields (`friction_points`, `suggested_improvement`, `details`) as clear, concise bullet points, quoting the exact product surface, tool name, parameter, or error text where you can. Include a concrete `suggested_improvement` whenever you can name one, for negative or mixed feedback that's the most valuable part. Use `task_completed: false` when you couldn't finish the user's request. Do not include user PII or sensitive query content in any field. The user can also ask you to send feedback directly, e.g. "make a PostHog feedback for this, it's broken." When they do, capture their point faithfully and submit it. Submitting feedback is **not** a way to end your turn or skip work. It's a side report to the PostHog team, call it when warranted, then keep going and finish the user's task with the other tools. ### Examples #### Creating an insight with segmentation <example> User: How many users have chatted with the AI assistant from the US? Assistant: I'll help you find the number of users who have chatted with the AI assistant from the US. 1. Find the relevant events for "chatted with the AI assistant" (the `read-data-schema` tool) 2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool) 3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool) 4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool) 5. Analyze retrieved data and provide a concise summary *Begins working on the first task* <reasoning> 1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query. 2. The user query requests additional segmentation by country. 3. Property values might not match what the user expects (e.g., "US" vs "United States"), so retrieving sample values is important. 4. Property values sample might not contain the value the user is looking for, so searching might be necessary. </reasoning> </example> #### Investigating a metric change <example> User: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count. Assistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps. 1. Check the governed catalog for an approved onboarding conversion metric (the `metric-list` tool); run it with `data-catalog-metric-run` if one matches, otherwise continue 2. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool) 3. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool) 4. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool) 5. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool) 6. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool) 7. Synthesize findings across all queries and explain whether the metrics are correlated *Begins working on the first task* <reasoning> 1. A conversion rate is a governed shape, so the catalog is checked before any query. 2. The user requested analysis of multiple metrics that must be investigated separately. 2. Multiple queries are needed to understand each trend independently. 3. Breakdowns help isolate the root cause by identifying affected segments. 4. A funnel connects the two metrics to check for a direct relationship. </reasoning> </example> #### Building a dashboard <example> User: Generate a revenue dashboard. Assistant: I'll help you create a revenue dashboard. Let me plan the steps. 1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool) 2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights`, check `execute-sql` for SQL guidance) 3. Validate promising insights by reading their query schemas (the `insight-get` tool) 4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool) 5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool) 6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool) 7. Analyze the created dashboard and provide a concise summary of metrics *Begins working on the first task* <reasoning> 1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete. 2. Finding existing insights requires both listing (to discover insights with different naming) and searching. 3. Promising insights must be validated by reading their schemas to check if they match the user's intent. 4. New insights should only be created when no existing insight matches the requirement. </reasoning> </example>
context
string
Required
Explain in 15-25 words, in third person, why this tool is called and how it supports the user's goal. For analytics only. You MUST describe only the abstract purpose of the tool call. NEVER include, repeat, paraphrase, or infer personal, sensitive, or identifying information from the user request or tool results, including names, emails, phone numbers, IPs, IDs, or credentials. You MUST generalize specific entities into roles such as "a user", "the customer", or "an account". Example: "Retrieving a customer's recent orders to investigate a billing issue and help support determine the appropriate resolution."
llm_model
string
Required
The exact model identifier you (the assistant) are running as, taken from your system prompt or environment (e.g. "claude-opus-4-8", "gpt-5.2"). Used for analytics only. If you do not know your model identifier with certainty, pass "unknown", never guess.
conversation_id
string
Optional
Pass the exact conversation_id from the server's previous response, unchanged. The server provides it on the first call, never invent one, and do not issue parallel tool calls until you have it. Keep passing the same conversation_id for the rest of the conversation, including after later user messages or on a different task; do not reset it when the user starts a new request.
Build your Agent
Drop the toolkit in, point it at the user, and your product analytics agent can use PostHog MCP from the first run.
Python · LlamaIndex
import { ScalekitClient } from "@scalekit-sdk/node";
import { DynamicStructuredTool } from "@langchain/core/tools";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
import { z } from "zod";

const sk = new ScalekitClient(envUrl, clientId, clientSecret);

const { tools } = await sk.tools.listScopedTools("user_123", {
filter: { connectionNames: ["posthogmcp"], toolNames: ["posthogmcp_exec", "posthogmcp_exec", "posthogmcp_exec"] },
pageSize: 100,
});

const lcTools = tools.map((t) => new DynamicStructuredTool({
name: t.tool.definition.name,
description: t.tool.definition.description,
schema: z.object({}).passthrough(),
func: async (args) => {
const { data } = await sk.tools.executeTool({
toolName: t.tool.definition.name,
identifier: "user_123",
params: args,
});
return JSON.stringify(data);
},
}));

const agent = createReactAgent({ llm, tools: lcTools });
import { ScalekitClient } from "@scalekit-sdk/node";
import OpenAI from "openai";

const sk = new ScalekitClient(envUrl, clientId, clientSecret);
const openai = new OpenAI();

const { tools } = await sk.tools.listScopedTools("user_123", {
filter: { connectionNames: ["posthogmcp"], toolNames: ["posthogmcp_exec", "posthogmcp_exec", "posthogmcp_exec"] },
pageSize: 100,
});

const llmTools = tools.map((t) => ({
type: "function",
function: {
name: t.tool.definition.name,
description: t.tool.definition.description,
parameters: t.tool.definition.input_schema,
},
}));

const resp = await openai.responses.create({
model: "gpt-4o", input: prompt, tools: llmTools,
});
import { ScalekitClient } from "@scalekit-sdk/node";
import Anthropic from "@anthropic-ai/sdk";

const sk = new ScalekitClient(envUrl, clientId, clientSecret);
const anthropic = new Anthropic();

const { tools } = await sk.tools.listScopedTools("user_123", {
filter: { connectionNames: ["posthogmcp"], toolNames: ["posthogmcp_exec", "posthogmcp_exec", "posthogmcp_exec"] },
pageSize: 100,
});

const llmTools = tools.map((t) => ({
name: t.tool.definition.name,
description: t.tool.definition.description,
input_schema: t.tool.definition.input_schema,
}));

const msg = await anthropic.messages.create({
model: "claude-sonnet-4-6", max_tokens: 1024,
tools: llmTools,
messages: [{ role: "user", content: prompt }],
});
import { Agent } from "@google/adk/agents";
import {
MCPToolset, StreamableHTTPConnectionParams,
} from "@google/adk/tools/mcp";

const toolset = new MCPToolset({
connectionParams: new StreamableHTTPConnectionParams({
url: "https://mcp.scalekit.com/posthogmcp",
headers: { Authorization: `Bearer ${userScopedToken}` },
}),
});

const agent = new Agent({
name: "agent", model: "gemini-2.0-flash",
tools: await toolset.getTools(),
});
Try these prompts
Paste any prompt into your agent to start using PostHog MCP.
Events & funnels
Copy the prompt
Copied
Activation funnel for signups this week.
Copy the prompt
Copied
Daily active users for the last 30 days.
Copy the prompt
Copied
Top 10 events by volume today.
Copy the prompt
Copied
Query: SELECT event, count() FROM events WHERE timestamp > now() - interval 7 day GROUP BY event.
Feature flags & cohorts
Copy the prompt
Copied
List all active feature flags.
Copy the prompt
Copied
Which flags have rollout below 20%?
Copy the prompt
Copied
List all cohorts and their sizes.
Copy the prompt
Copied
Which users are in cohort [name]?
Insights & reporting
Copy the prompt
Copied
List all saved insights.
Copy the prompt
Copied
Which insight tracks [metric]?
Copy the prompt
Copied
Retention curve for users who signed up last month.
Copy the prompt
Copied
Session recording count by page this week.
SEE HOW AUTH WORKS
Users authorize PostHog MCP once. Their credentials stay vaulted, every call is checked, and every action is logged.
1
Authorize
Your user connects
PostHog MCP
once. We tie it to their identity and the meetings they approved — no shared bot account, no org-wide access
Who:
user ‘A’
when:
Once per user
access:
Limited to user
2
Store
Their
PostHog MCP
token lives in a vault scoped to them. User A's meetings are never reachable by an agent acting for user B, even on the same connection
vault:
encrypted
scope:
per-user
tokens:
auto-refreshed
3
Resolve
When your agent calls a
PostHog MCP
tool, we fetch the right token server-side. It never touches your agent, never appears in the LLM context, never shows up in your logs
speed:
~40ms
check:
before every call
seen by:
nobody
4
Audit
Every
PostHog MCP
tool call is logged — who triggered it, which meeting was fetched, what came back. 90 days of history, tied to the user who authorized it
history:
90 days
export:
SIEM-ready
logged:
every call
Test other agents
Same per-user auth pattern across other product analytics agents and MCP connectors. Working code, live demos, fork what fits.
GTM and RevOps Teams
Revenue forecast commentary
Pulls open pipeline from Salesforce and HubSpot, calculates coverage against quota, flags at-risk stages, posts commentary to Slack, and logs every snapshot to Google Sheets.
GTM and RevOps Teams
Deal intelligence agent
Pulls recent Gong calls, scores deal risk with an LLM, cross-references the record in Attio, and DMs each owner their at-risk deals in Slack. Every read is scoped to that rep's own access.
Engineering Teams
Engineering standup agent
Pulls commits from GitHub and GitLab, tracks issue movement in Jira, and posts a per-engineer standup brief to Slack. Each engineer's activity is read on their own delegated OAuth.
GTM and RevOps Teams
Competitive intelligence briefing agent
Scans Gong calls for competitor mentions, matches each one to its Notion battlecard, and DMs every affected rep a single Slack digest per cycle. Every call runs as the PMM who owns the briefing, never a shared bot.
Test other agents
Same per-user auth pattern across other product analytics agents and MCP connectors. Working code, live demos, fork what fits.
ENGINEERING
Engineering standup agent
Pull commits from GitHub and GitLab, track Jira issue movement, and post a per-engineer standup brief to Slack.
GTM
Revenue forecast agent
Score pipeline coverage against quota across Salesforce and HubSpot, post forecast commentary to Slack, log snapshots to Sheets.
SALES
Deal intelligence agent
Score Gong call risk with an LLM, cross-reference the Attio record, and DM each owner their at-risk deals in Slack.
GTM
Competitive intelligence briefing agent
Scan Gong calls for competitor mentions, match each one to its Notion battlecard, and DM every affected rep a single Slack digest.
Why Scalekit
Secure your agent's access. Connectors ship in minutes
01.
Shared tokens break per-user analytics
A shared token looks fine in a demo. In production every call looks like a service account. Scalekit resolves the real user credential so attribution, audit, and scope stay accurate.
// shared token
 audit → bot_service_account
 user_filter → broken

 // scalekit
 audit → user_abc
 scope → enforced ✓
02.
Authentication is not authorization
03.
Multi-tenancy is architectural
04.
PostHog MCP today. Others tomorrow.
“Our agents act across Salesforce, Gong, Google Drive, and more, on behalf of every customer. Scalekit behind the scenes meant we can keep adding tools without ever rebuilding how credentials or tool calling work.”
Venu Madhav Kattagoni
Head of Engineering / Von
FAQs
Frequently Asked Questions
Does the agent access PostHog MCP as the user or as a shared key?
As the user. Each workspace member authorizes once and Scalekit resolves their credential at request time. Audit logs attribute every action to that user, not a shared service account.
Where is the PostHog OAuth token stored?
In Scalekit's managed AES-256 token vault, namespaced per tenant. Refresh is automatic. Revocation is a single dashboard action. Tokens never appear in prompts, logs, or LLM context.
Can I limit what the agent is allowed to do in PostHog MCP?
Yes. Pass a tool name filter to listScopedTools so the product analytics agent only sees the subset you authorize. Pre-API-call scope checks block out-of-policy actions before the request reaches PostHog MCP.
What happens when a user revokes PostHog MCP access?
The connection is invalidated on the next tool call. Subsequent requests for that user fail closed with a clear error. Other users in the tenant remain unaffected. The event is logged for audit.
Does the agent inherit my PostHog project and org access?
Yes. Access is scoped to the projects the authorizing user can reach in PostHog. The agent can only access data within that project. Cross-project queries require a separate connected account per project.
What other MCP connectors does Scalekit support?
Scalekit runs the PagerDuty MCP server, Datadog MCP server, and Vercel MCP server on the same per-user auth, token vault, and audit trail. Browse 600+ connectors in the MCP connector directory.
How do I build a PostHog agent?
Follow the step-by-step tutorial: Build a Multi-User PostHog Agent with Claude and Scalekit. It covers per-user auth, tool scoping, and working agent code for PostHog.
Start in your coding agent
Up and running in one command
Install the Scalekit skill in your editor of choice. Connector, auth, tools, prompt, all wired up
Claude Code REPL
/plugin marketplace add scalekit-inc/claude-code-authstack
/plugin install agentkit@scalekit-auth-stack
Cursor Code REPL
# ~/.cursor/mcp.json
{
""mcpServers"": {
""posthogmcp"": {
""url"": ""https://mcp.scalekit.com/posthogmcp"",
""headers"": { ""Authorization"": ""Bearer $SCALEKIT_TOKEN"" }
}
}
}
Codex Code REPL
# ~/.codex/config.toml
[mcp_servers.posthogmcp]
url = ""https://mcp.scalekit.com/posthogmcp""
auth_env = ""SCALEKIT_TOKEN""
Copilot Code REPL
# .vscode/mcp.json
{
""servers"": {
""posthogmcp"": {
""url"": ""https://mcp.scalekit.com/posthogmcp"",
""type"": ""http""
}
}
}