
PostHog MCP Server
io.github.PostHog由 GitHub 帳號 PostHog 發布v1.0.1更新於 Oct 26, 2026
Official PostHog MCP Server for product analytics, feature flags, experiments, and more.
概覽
PostHog 官方 MCP 伺服器,讓助理查詢產品分析資料、管理功能旗標與實驗,並檢視工作階段重播、錯誤與問卷。
- 可以做什麼
- 查詢分析資料,執行 SQL、趨勢與漏斗查詢,讀取洞察與儀表板
- 建立與檢視功能旗標、實驗及其變體
- 檢視工作階段重播、錯誤追蹤問題、問卷、同群使用者與人員
- 瀏覽事件、資料結構、資料倉儲來源、日誌與 LLM 分析
- 切換目前組織或專案,並搜尋 PostHog 文件
- 可依功能群組或確切工具名稱限制開放的工具
- 適用情境
- 適合已在用 PostHog、希望助理依自有分析資料回答產品問題、建立或調整功能旗標與 A/B 測試,或追查錯誤與重播時使用,不必離開聊天用戶端。
- 執行需求
- 遠端端點 mcp.posthog.com,透過 Streamable HTTP 存取,Accept 標頭需同時包含 JSON 與事件串流。驗證使用 OAuth 或 PostHog 個人 API 金鑰,以 Bearer 權杖放在 Authorization 標頭中,金鑰需以 MCP Server 預設建立。歐盟使用者應改用歐盟端點。
安裝
在 SourceWeft 中
- 開啟 儀表板中的 PostHog MCP Server,將其新增到工作區。
- 連接 所需的 憑證。它們會被私密儲存,絕不會在公開頁面上展示。
- 為需要使用其工具的對話啟用該服務。
Web executable,透過 Streamable HTTP。 遠端服務在工作區中設定後即可從網頁執行環境執行。
交給代理程式安裝
把這段提示詞貼上到 Claude Code、Codex、Cursor 等代理程式,或 SourceWeft 對話中。代理程式會讀取該伺服器的安裝指南,先向你展示發布者、端點和登入方式,經你同意後再把它新增到你的客戶端。金鑰不會寫進任何命令。
閱讀 https://sourceweft.com/mcp/io.github.PostHog%2Fmcp/install.md,並按其中說明把這個 MCP 伺服器接入我的客戶端。修改任何設定之前,先告訴我它的發布者、端點和登入方式,等我確認。不要把 API 金鑰寫進命令或我會提交的檔案;問我金鑰應從哪裡取得。其他 MCP 客戶端
把它新增到你客戶端的 mcpServers 設定中。 客戶端會在首次連接時完成 OAuth 登入。
{
"mcpServers": {
"posthog": {
"type": "http",
"url": "https://mcp.posthog.com/mcp"
}
}
}README
PostHog MCP
The official MCP server for PostHog. PostHog makes your product self-driving — it reads your data and ships changes with you, never without you — and this server gives MCP clients (Claude, Cursor, VS Code, Zed, and more) that full surface: analytics and SQL, dashboards, experiments, feature flags, surveys, session replay, error tracking, and more.
Documentation: https://posthog.com/docs/model-context-protocol
Use the MCP Server
Quick install
You can install the MCP server automatically into Cursor, Claude, Claude Code, VS Code and Zed by running the following command:
Manual install
-
Obtain a personal API key using the MCP Server preset.
-
Add the MCP configuration to your desktop client (e.g. Cursor, Windsurf, Claude Desktop) and add your personal API key
Minimal Node client (Streamable HTTP)
If you want to call MCP from Node (outside an IDE), use the Model Context Protocol SDK’s Streamable HTTP transport.
- Auth: Use a personal PostHog API key and pass it as a Bearer token in
Authorization. - Accept header: Clients must include
Accept: application/json, text/event-stream. - Lifecycle: MCP requires
initializethen a clientnotifications/initialized; the SDK performs this duringconnect().
Why these headers & steps?
- Streamable HTTP requires the
Acceptheader to include both JSON and SSE. - After
initialize, the client must sendnotifications/initialized; the SDK does this for you inconnect().
See also the main PostHog MCP docs for available tools and setup flows: https://posthog.com/docs/model-context-protocol
Example Prompts
Below are detailed examples showing realistic prompts and expected outputs:
Example 1: Feature flag management
Prompt: "Create a feature flag called 'new-checkout-flow' that's enabled for 20% of users, and show me the configuration"
What happens:
- The
create-feature-flagtool creates the flag with a 20% rollout - Returns the flag configuration including the key, rollout percentage, and targeting rules
Expected output:
Example 2: Analytics query
Prompt: "How many unique users signed up in the last 7 days, broken down by day?"
What happens:
- The
query-trendstool executes a trends query filtering for$signupevents - Returns daily counts with unique user aggregation
Expected output:
Example 3: A/B test creation and monitoring
Prompt: "Create an A/B test for our pricing page that measures conversion to the checkout page"
What happens:
- The
experiment-createtool creates an experiment with control/test variants - Sets up a funnel metric: pricing page view → checkout page view
- Creates an associated feature flag for variant assignment
Expected output:
Example 4: Error investigation
Prompt: "What are the top 5 errors in my project this week and how many users are affected?"
What happens:
- The
query-error-tracking-issues-listtool fetches error groups sorted by occurrence count - Returns error details including affected user counts
Expected output:
Quick prompts
For simpler queries, you can use shorter prompts:
- "What feature flags do I have active?"
- "Show me my LLM costs this week"
- "List my dashboards"
- "What events are being tracked?"
Feature Filtering
You can limit which tools are available by adding query parameters to the MCP URL. If no features are specified, all tools are available. When features are specified, only tools matching those features are exposed.
Available features:
Note: Hyphens and underscores are treated as equivalent in feature names (e.g.,
error-trackinganderror_trackingboth work).
To view which tools are available per feature, see our documentation or check schema/tool-definitions-all.json.
Learning and skills in cli mode
Claude web and desktop silently drop exec when its serialized inputSchema reaches 16,384 characters.
In cli mode, the exec tool keeps the guidance needed for routine calls in its schema.
The compact tool-domain index stays inline in the command schema so Claude can discover relevant tools before making a call.
Optional, task-specific guidance is served through the same tool:
learnlists the available built-in guides and, when enabled, the PostHog/project skill discovery syntax.learn analyticsloads detailed analytics guidance and examples.learn visualizationsloads rendering guidance when visualizations are available.learn urlsloads the PostHog app link formatting rules (kept inline for other clients; served as a guide on Claude web and desktop to protect the schema budget).learn feedbackloads feedback guidance when feedback is available.learn skillslists qualified names from the published PostHog bundle (posthog:) and the current project's Skills store (project:).learn -s "<up to 8 keywords>"searches both sources in names, descriptions, Markdown bodies, and bundled file paths. Longer keywords take priority when a query contains more than eight. Results from both sources are merged into one relevance order.learn -d <source>:<skill> [...]prints the one-line description of each named skill without reading its body (up to 20 per call). Unknown names are reported inline without failing the batch.learn posthog:<skill> [path]orlearn project:<skill> [path]reads a skill or one of its bundled files.learn <source>:<skill> <path> [path...]reads several bundled files, andlearn <source>:<skill> [<source>:<skill>...]reads several skills, in one call (up to 10 targets).learn <source>:<skill> <path> -s "<up to 8 keywords>"searches within one Markdown file.learn <source>:<skill> <path> --lines <start>:<end>reads an inclusive line range.
Built-in guides are specific to Claude web and desktop. Skill discovery is independently available to every cli-mode client when the mcp-exec-skills feature flag is enabled. Other clients, including Claude Code, receive only the skill commands and do not receive Claude's built-in guides. If the flag is missing, disabled, or cannot be evaluated, skill commands are omitted from the schema and rejected at runtime.
When skill discovery is enabled, the inline prompt tells every non-plugin cli client, including Claude web and desktop, to search with learn -s "<task keywords>" before non-trivial PostHog work, load matches by exact qualified name, and follow the loaded SKILL.md before choosing tools. Trivial lookups and unrelated conversation skip this workflow.
Skill use is advisory: a product call is never rejected for skipping learn, so every client behaves the same whether or not it holds an MCP session id.
The skill bundle is shared through Redis: each pod loads it once at startup, parses it into memory, and serves every learn command from that parsed catalog.
A background timer polls a small version key in Redis; only when the version changes does a pod read the archive bytes again.
One pod at a time refreshes the archive from its source when the shared copy is older than ten minutes, using a conditional request so an unchanged release costs a 304.
The cached bytes are kept for thirty days and re-extended on every refresh, so a source outage serves the last good archive.
No learn, initialize, or discover request reads the archive from Redis.
By default it is loaded from https://github.com/PostHog/posthog/releases/download/agent-skills-latest/skills.zip.
Set POSTHOG_MCP_SKILLS_URL to use another archive during local development.
Custom archive URLs use separate Redis cache namespaces so a local bundle cannot read or overwrite the published bundle's cache entry.
Project skills are read directly from the request-authenticated project and are not cached by the MCP server.
Only latest, active, uncategorized skills are exposed through learn; category-specific skills such as scouts stay on their own surfaces.
Project full-text search is bounded to 10 skills, two short snippets per skill, and a five-second database timeout.
Individual learn responses stay below 44,000 characters; large references return a heading outline for follow-up search or line reads.
The fixed command syntax stays in the tool schema, while skill names and bodies are loaded only when requested.
consumer=plugin and consumer=posthog-code omit learn because both surfaces already supply their own bundled skill context, regardless of the feature flag.
Other clients keep the full inline command reference.
Tool filtering
In CLI mode, tools and exclude_tools also apply to namespaced connected tools. A features filter excludes connected tools unless tools explicitly names them. Exclusions take precedence over explicit selections.
For finer-grained control you can allowlist specific tools by name using the tools query parameter. Only the exact tool names listed will be exposed, regardless of their feature category.
When features and tools are both provided they are combined as a union — a tool is included if it matches a feature category or is in the tools list. This lets you select a feature group and add a handful of individual tools on top:
The example above exposes all flag tools plus dashboard-get.
Server mode (tools vs cli)
The MCP server can register either every PostHog tool individually (tools mode) or wrap them all behind a single exec CLI-like tool (cli mode).
cli is the default for all clients.
When the caller does not pin a mode, the server only auto-selects tools mode for a short allow-list of clients that are better served by the full per-tool roster — currently Cursor (matched by its self-reported client name or its Cursor/… User-Agent).
Every OpenAI surface (ChatGPT, Codex, Agent Builder, Responses API) gets the cli default. OpenAI's openai-mcp client caches the roster it captures for a published plugin and serves that snapshot to every user of the plugin, so the mode a plugin listing should run in is pinned on the URL submitted to OpenAI rather than inferred from a User-Agent label.
You can pin the choice yourself with either a query parameter or a header. Only tools and cli are accepted:
The header wins when both the header and the query parameter are set. An explicit value always wins over the client auto-detection; any other value is ignored and the auto-detection takes over.
The cli-mode command surface is documented publicly on posthog.com/docs/model-context-protocol/tools, which embeds schema/exec-command-reference.md at build time.
That fragment is generated from the templates in src/templates/sections/ by scripts/generate-exec-docs.ts (part of hogli build:openapi); edit the templates, not the fragment.
Consumer attribution
Wrapping apps and AI-tool plugins that install or proxy the PostHog MCP can self-identify so usage can be attributed to the install path (e.g. plugin-installed vs. manually-pasted URL). The wrapped MCP client (Claude Code, Cursor, …) is already captured separately via the MCP clientInfo handshake — this signal is only for the wrapping context.
The header wins when both the header and the query parameter are set. Reserved values: plugin (AI-tool plugin installs), posthog-code (PostHog Desktop Tasks sandbox), slack (Slack integration).
Data processing
The MCP server runs in PostHog's US and EU Kubernetes clusters and stores session state in the region you connect to. A stateless Cloudflare Worker in front of it only authenticates requests and routes them to your cloud region; it does not store any sensitive data.
Using self-hosted instances
If you're using a self-hosted instance of PostHog, you can specify a custom base URL by setting the POSTHOG_API_BASE_URL environment variable when running the MCP server locally or on your own infrastructure, e.g. POSTHOG_API_BASE_URL=https://posthog.example.com
Development
To run the MCP server (Hono on Node) locally, run the following command:
Or use bin/start-mcp-server from the repo root, which also bootstraps .env and sets Redis/port defaults.
Then replace https://mcp.posthog.com/mcp with http://localhost:8787/mcp in the MCP configuration.
The server defaults to port 8787, reads config from .env (see .env.example), and expects a local Redis on port 6379 for session state; production deployments must set REDIS_URL to a TLS-encrypted rediss:// endpoint.
Startup waits up to 45 seconds for Redis to become ready, including connection retries. If Redis stops reconnecting or the deadline expires, the process exits without starting the HTTP server.
Session cache
Each MCP transport session keeps its own active organization and project, including connections without a project_id or organization_id pin. An unpinned session starts from the user's active organization and project, within the credential's allowed scope. Later website changes and switches in other MCP sessions do not change that selection. switch-project and switch-organization update only the calling session; switching to another organization clears the previous project.
switch-project requires a positive integer projectId. It also accepts project_id and new_project_id as aliases. If several are supplied, projectId takes precedence, followed by project_id.
Clients without an MCP session ID use the SDK's conversation_id instead. Echo the handle returned by the first tool call on subsequent calls. A switch without a carried session or conversation handle returns an error and a new handle; retry with that handle to apply the switch. Conversation state is bound to the credential and stored separately from transport sessions. Calls without either identity start from the connection's pin or default selection. If your client cannot retain conversation handles, pin the project or organization in the connection URL.
Legacy JSON-RPC batches restore each call's conversation handle independently. The wrapper's sessionId query parameter is an analytics hint and does not replace a conversation handle; wrapper-only calls still receive a new handle from the SDK.
Session defaults are stored once, separately from explicit selections. A delayed lookup can resolve context for its own request without overwriting a completed switch.
If default project discovery fails, later requests retry within the session's original organization. The first successful project discovery wins, and explicit switches still take precedence. An organization switch retains a selected project when the destination's team list confirms that it belongs there, even if the credential cannot read project metadata.
A session's client context lives in one mcp:s:<id>:c key with a 24-hour idle expiry, refreshed on every request in the session.
Concurrent requests merge their fields through a Lua compare-and-merge, so a field first seen mid-session is never lost to an overlapping write.
Monitor mcp_session_cache_operations_total for read_error and write_error.
Both are non-blocking: a failed read serves whatever context the current request carries, so attribution degrades rather than the call failing.
Each also logs a warning prefixed [McpSessionRedisStore], so a Redis failure on this path is greppable in logs and not only visible on the metrics counter.
Edge-proxy worker (Cloudflare)
In production, a thin Cloudflare Worker sits in front of the Hono deployments as a stateless edge router: it serves the OAuth metadata endpoints, validates tokens, resolves the caller's cloud region, and proxies /mcp traffic to mcp.us.posthog.com / mcp.eu.posthog.com.
It does not serve the MCP protocol itself - see ARCHITECTURE.md.
To run just the worker locally:
Developing with local resources
To develop with warm loading for MCP resources (workflows, prompts, examples):
- Start the context-mill dev server:
cd ../context-mill && npm run dev - Start the MCP server with local resources:
pnpm run dev:local-resources(runsbin/start-mcp-serverwithPOSTHOG_MCP_LOCAL_SKILLS_URLpointed at context-mill)
Changes in the examples repo will be reflected on the next request.
Project Structure
src/- The MCP server: Hono app (src/hono/), tool handlers (src/tools/), prompt templates (src/templates/)definitions/- Hand-authored YAML tool definitions (per-product YAML lives atproducts/<product>/mcp/in the monorepo)schema/- Generated schema files, includingtool-definitions-all.json(the full tool catalog)
Development Commands
pnpm run dev- Start the MCP development serverpnpm run dev:proxy- Start the edge-proxy worker (wrangler)pnpm run lint/pnpm run format:check- Verify linting and formatting without changing filespnpm run lint:fix- Apply safe lint fixes without suggestion fixespnpm run format- Format code with Oxfmt onlypnpm run fix- Apply safe lint fixes, always format code, and report failures from either tool
Adding New Tools
Most tools are generated from products/<product>/mcp/tools.yaml.
Follow the implementing MCP tools skill and the handbook guide for that flow.
Use src/tools/README.md only for hand-written tools.
Environment variables
Copy .env.example to .env in the root and adjust the values as needed.
Configuring the Model Context Protocol Inspector
During development you can directly inspect the MCP tool call results using the MCP Inspector.
You can run it using the following command:
Alternatively, you can use the following configuration in the MCP Inspector:
Use transport type STDIO.
Command:
Arguments:
Developing against Claude Desktop
Claude Desktop is one of the easiest ways to test MCP Apps - while PostHog Desktop doesn't support it. You can configure access Settings > Developer and then edit claude_desktop_config.json with the following:
Privacy & Support
- Privacy Policy: https://posthog.com/privacy
- Terms of Service: https://posthog.com/terms
- Support: https://posthog.com/questions or email [email protected]
- GitHub Issues: https://github.com/PostHog/posthog/issues
Data handling
The MCP server acts as a proxy to your PostHog instance. It does not store your analytics data - all queries are executed against your PostHog project and results are returned directly to your AI client. Session state (active project/organization) is cached temporarily, keyed by your API key hash.
For EU users, use the mcp-eu.posthog.com endpoint to ensure OAuth flows route to the EU PostHog instance.
來源:services/mcp/README.md,提交 9fe8361
工具
0版本歷史
1- v1.0.1最新Sep 16, 2026
評分
已滿足適用檢查項的 75%
該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。
- 近 30 天內可連通必需25 分
- 已宣告認證方式必需10 分
- 已列出工具15 分
請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。
- 描述必需15 分
- 圖示10 分
- 文件15 分
- 授權條款10 分
請在儲存庫或註冊中心條目中宣告授權條款。