> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt # TypeScript MCP Analytics installation Canonical URL: https://posthog.com/docs/mcp-analytics/installation/typescript > **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.posthog.com` instead of `https://app.posthog.com` (app host for links). ## On this page - [Install the packages](#install-the-packages) - [Wrap your server](#wrap-your-server) - [Send queued events on shutdown](#send-queued-events-on-shutdown) - [Check your first events](#check-your-first-events) - [Frameworks](#frameworks) - [Read request headers on both SDK majors](#read-request-headers-on-both-sdk-majors) - [Stateless and multi-pod servers](#stateless-and-multi-pod-servers) - [Configuration](#configuration) - [Custom dispatchers](#custom-dispatchers) **Beta SDK** `@posthog/mcp` is in beta (pre-1.0). Minor `0.x` releases may contain breaking API changes until `v1`. Pin a version during the beta. `@posthog/mcp` instruments servers built on the official [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk). It supports both SDK majors: | Your imports | MCP SDK major | Protocol revisions it serves | | --- | --- | --- | | `@modelcontextprotocol/sdk` | v1 | `2025-11-25` and earlier | | `@modelcontextprotocol/core`, `/server`, `/client` | v2 | `2025-11-25` and `2026-07-28` | The minimum versions are `@modelcontextprotocol/sdk` 1.26.0 for v1 and `@modelcontextprotocol/server` 2.0.0 for v2. You need Node.js 20.20+ or 22.22+, `posthog-node` 5, and a PostHog [project token](https://posthog.com/docs/feature-flags/installation.md#where-to-find-your-project-api-key). Using a dispatcher with no MCP SDK server object? See [Custom dispatchers](#custom-dispatchers). `npx @posthog/wizard mcp-analytics` The [wizard](https://posthog.com/blog/envoy-wizard-llm-agent.md) installs the package and adds `instrument()` for you. To install by hand, follow the steps below. 1. 1 ## Install the packages Required ```bash npm install @posthog/mcp@1 posthog-node@5 ``` `@posthog/mcp` uses your [`posthog-node`](https://posthog.com/docs/libraries/node.md) client to send events. You own that client's lifecycle. `@posthog/mcp` re-exports `PostHog`, so one import covers both. `posthog-node` is still a peer dependency, so install it too. 2. 2 ## Wrap your server Required Call `instrument(server, posthog)` once, before the server accepts requests. Pass the `McpServer` or the low-level `Server`. The SDK also instruments tools that you register later. ### SDK-v1 ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" import { PostHog, instrument } from "@posthog/mcp" const server = new McpServer({ name: "my-mcp-server", version: "1.0.0" }) const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN, { host: "https://us.i.posthog.com", // or https://eu.i.posthog.com }) const analytics = instrument(server, posthog) server.tool("search_events", { /* ... */ }, async (args) => { // your handler runs untouched }) ``` ### SDK-v2 ```typescript import { McpServer } from "@modelcontextprotocol/server" import { PostHog, instrument } from "@posthog/mcp" const server = new McpServer({ name: "my-mcp-server", version: "1.0.0" }) const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN, { host: "https://us.i.posthog.com", // or https://eu.i.posthog.com }) const analytics = instrument(server, posthog) server.registerTool("search_events", { /* ... */ }, async (args) => { // your handler runs untouched }) ``` `instrument()` returns an analytics handle for [custom events](https://posthog.com/docs/mcp-analytics/custom-events.md). A second call on the same server does nothing new. It logs a warning through the `logger` from the first call and returns a working handle. 3. 3 ## Send queued events on shutdown Required `posthog-node` sends events in batches. Call `posthog.shutdown()` when the process stops: ```typescript process.on("SIGTERM", async () => { await posthog.shutdown() process.exit(0) }) ``` In serverless and edge functions, `SIGTERM` may not run. Call `await posthog.flush()` at the end of each invocation, or `ctx.waitUntil(posthog.flush())` where the platform supports it. 4. 4 ## Check your first events Required Connect an agent to your server and call a tool. Then open the [activity feed](https://app.posthog.com/activity/explore) and filter for `event = $mcp_tool_call`. See [the event reference](https://posthog.com/docs/mcp-analytics/events.md) for every property. ## Frameworks ### Next.js and Vercel (`mcp-handler`) [`mcp-handler`](https://github.com/vercel/mcp-handler) gives you an `McpServer` in its setup callback. Call `instrument()` there: ```typescript import { createMcpHandler } from "mcp-handler" import { PostHog, instrument } from "@posthog/mcp" // Create the client once at module scope, not per request. const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN, { host: "https://us.i.posthog.com", }) const handler = createMcpHandler( (server) => { instrument(server, posthog) server.registerTool("roll_dice", { /* ... */ }, async ({ sides }) => { /* ... */ }) }, {}, { basePath: "/api" }, ) export { handler as GET, handler as POST } ``` `mcp-handler` creates a new server for each request and sends no `Mcp-Session-Id` header. Without another signal, each request gets its own `$session_id`. To group a client's calls: - Return a `distinctId` from [`identify`](https://posthog.com/docs/mcp-analytics/identifying-users.md), such as the OAuth subject. This needs no client changes. - Keep [conversation IDs](https://posthog.com/docs/mcp-analytics/conversation-id.md) on (the default). Calls group when the agent echoes the handle. Flush at the end of each invocation, as in [step 3](#send-queued-events-on-shutdown). ### NestJS (`@rekog/mcp-nest`) [`@rekog/mcp-nest`](https://github.com/rekog-labs/MCP-Nest) creates the server through `McpModule.forRoot(...)`. Add `instrumentMutator` to its `serverMutator` hook: ```typescript import { Module } from "@nestjs/common" import { McpModule } from "@rekog/mcp-nest" import { PostHog, instrumentMutator } from "@posthog/mcp" const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN, { host: "https://us.i.posthog.com", }) @Module({ imports: [ McpModule.forRoot({ name: "my-mcp-server", version: "1.0.0", serverMutator: instrumentMutator(posthog), }), ], }) export class AppModule {} ``` `instrumentMutator(posthog)` calls `instrument()` and returns the server, not the analytics handle. It also captures tools that mcp-nest registers later. If you need the handle for [custom events](https://posthog.com/docs/mcp-analytics/custom-events.md), call `instrument()` yourself: ```typescript serverMutator: (server) => { const analytics = instrument(server, posthog) return server } ``` ## Read request headers on both SDK majors **This fails silently** MCP SDK v1 stores headers at `extra.requestInfo.headers`. v2 stores a WHATWG `Request` at `extra.http.req`. Reading the v1 location on v2 returns `undefined`, so `identify()` can return `null` and send anonymous events without an error. Use `getRequestHeaders(extra)` in `identify`, `intentFallback`, and `eventProperties`. It works on both majors and returns lowercase keys: ```typescript import { instrument, getRequestHeaders } from "@posthog/mcp" instrument(server, posthog, { identify: async (request, extra) => { const token = getRequestHeaders(extra)?.["authorization"] return token ? { distinctId: await resolveUserId(token) } : null }, }) ``` ## Stateless and multi-pod servers A stateless server creates a new instance for each request, often on a different pod. Without correlation, each request gets its own `$session_id`, and events after `initialize` lose the client name and version. On `2025-11-25` traffic, the SDK fixes this without a shared store or sticky routing. At `initialize`, it puts a token with the session ID and client metadata in the `Mcp-Session-Id` response header. Clients send the header back, so any pod reads the same values. The `2026-07-28` revision has no `initialize`, so use [conversation IDs](https://posthog.com/docs/mcp-analytics/conversation-id.md) there. The SDK can only send the token in JSON mode. Set `enableJsonResponse: true` on a fresh transport per request: ```typescript new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, // stateless enableJsonResponse: true, // lets the SDK set the session header }) ``` With `@rekog/mcp-nest`, set `streamableHttp: { statelessMode: true, enableJsonResponse: true }` on the module. The legacy path in `createMcpHandler` can't send the token, so `$mcp_client_name` and `$mcp_client_version` are absent there. If you must stream (SSE), set the header yourself before the response headers go out: ```typescript import { MCP_SESSION_HEADER, encodeSessionId, newSessionId } from "@posthog/mcp" if (body?.method === "initialize" && !req.headers[MCP_SESSION_HEADER]) { res.setHeader( MCP_SESSION_HEADER, encodeSessionId({ sessionId: newSessionId(), clientName: body.params?.clientInfo?.name, clientVersion: body.params?.clientInfo?.version, }) ) } ``` ### Resolve tool arguments on fresh low-level servers A fresh low-level `Server` has not served `tools/list`, so it does not know which `context` and `llm_model` arguments the SDK added. A strict input schema can reject these arguments before the tool runs. Use `resolveOriginalTool` to return each tool's original input schema from your registry. The callback must return the schema from before PostHog adds its arguments: ```typescript instrument(server, posthog, { resolveOriginalTool: (toolName) => { const tool = toolsByName.get(toolName) return tool ? { inputSchema: tool.inputSchema } : undefined }, }) ``` The SDK strips only arguments that it added. It reads a Zod schema as the MCP SDK advertises it. If your server advertises a custom JSON Schema, return that schema instead. ## Configuration `instrument(server, posthog, options?)` takes these options: | Option | Default | What it does | | --- | --- | --- | | `context` | `true` | Add a `context` argument to capture [agent intent](https://posthog.com/docs/mcp-analytics/intent.md). Pass `{ description }` to change its prompt. | | `intentFallback` | – | `(request, extra) => string \| null`. Supplies intent when the agent sends no `context`. | | `captureModel` | `true` | Capture the [calling model](https://posthog.com/docs/mcp-analytics/events.md#model-capture) from client metadata or an `llm_model` argument. Pass `{ description }` to change the argument's prompt. | | `enableConversationId` | `true` | Add a `conversation_id` argument to [group calls](https://posthog.com/docs/mcp-analytics/conversation-id.md) across requests. | | `identify` | – | `(request, extra) => UserIdentity \| null`, or a static `UserIdentity`. Maps a request to [one of your users](https://posthog.com/docs/mcp-analytics/identifying-users.md). | | `reportMissing` | `false` | Add the `get_more_tools` tool for [missing capabilities](https://posthog.com/docs/mcp-analytics/missing-capability.md). | | `missingCapabilityToolName` | `"get_more_tools"` | Renames the `reportMissing` tool. | | `collectFeedback` | `false` | Add the `send_feedback` tool, which emits [`$mcp_feedback`](https://posthog.com/docs/mcp-analytics/events.md#feedback-properties). It reports missing capabilities too, but the MCP Analytics views read only `reportMissing` reports. Pass `{ toolName, description, extraProperties, onFeedback }` to customize it. | | `enableExceptionAutocapture` | `true` | Emit a `$exception` event for each failed tool call. | | `sendInitializeEvent` | `true` | Emit `$mcp_initialize` for each `initialize` handshake. Set to `false` to stop it. Other events keep their sessions and client names. MCP onboarding and the default dashboard's users and sessions tiles then show no data. | | `sendToolsListEvent` | `true` | Emit `$mcp_tools_list` for each `tools/list`. Set to `false` to stop it. Tools keep their injected arguments. | | `beforeSend` | – | `(event) => event \| null`. Change or drop each event before it's sent. See [Privacy](https://posthog.com/docs/mcp-analytics/privacy.md). | | `eventProperties` | – | `(request, extra) => Record`. Adds [properties](https://posthog.com/docs/mcp-analytics/custom-events.md) to every event. | | `serverBuild` | – | An immutable build ID, such as a Git SHA, sent as `$mcp_server_build`. 1 to 256 characters. | | `shouldRecordInputKey` | declared names | Decides which argument names `$mcp_input_keys` records. Other names become one `[redacted]` entry. | | `resolveInputAliases` | – | `(toolName) => aliases`. Lists alternative argument names, recorded as `$mcp_input_aliases_used`. | | `resolveOriginalTool` | – | `(toolName) => { inputSchema } \| undefined`. Resolves input ownership on a fresh low-level server. See [Resolve tool arguments on fresh low-level servers](#resolve-tool-arguments-on-fresh-low-level-servers). | | `logger` | no-op | `(message) => void`. A stdio-safe sink for SDK warnings. | ## Custom dispatchers `instrument()` needs an MCP SDK server object. A Hono, Express, Cloudflare Workers, or edge handler that implements the protocol itself has none. Use `PostHogMCP` instead. It extends the `posthog-node` client and takes its constructor arguments, plus `serverBuild`, `captureModel`, `enableConversationId`, `missingCapabilityToolName`, and `collectFeedback`: ```typescript import { PostHogMCP, getMoreToolsResult } from "@posthog/mcp" const posthog = new PostHogMCP(process.env.POSTHOG_PROJECT_TOKEN, { host: "https://us.i.posthog.com", }) ``` Call the capture methods from your dispatcher. They build the same `$mcp_*` events as `instrument()`, with the same redaction and size limits: ```typescript // When you answer tools/list: const tools = posthog.prepareToolList(myTools, { reportMissing: true }) // When you answer tools/call, before the tool runs: const prepared = posthog.prepareToolCall(name, request.params.arguments) if (prepared.isMissingCapability) { posthog.captureMissingCapability({ context: prepared.intent, distinctId: user.id }) return getMoreToolsResult() } const start = Date.now() const result = await runTool(name, prepared.args) // Adds the conversation handle to the result, and returns the session to capture: const final = posthog.prepareToolResult(result, prepared) posthog.captureToolCall({ toolName: name, intent: prepared.intent, intentSource: prepared.intentSource, llmModel: prepared.llmModel, llmModelSource: prepared.llmModelSource, parameters: prepared.args, response: final.result, durationMs: Date.now() - start, isError: false, sessionId: final.sessionId, conversationId: final.conversationId, distinctId: user.id, protocolVersion: requestProtocolVersion, groups: { organization: user.orgId }, }) return final.result // Only on a 2025-11-25 initialize handshake: posthog.captureInitialize({ clientName: "claude-code", clientVersion: "1.2.3", protocolVersion: "2025-11-25", distinctId: user.id, }) ``` Pass `errorType` to `captureToolCall` to set `$mcp_error_type` to your own label, such as `validation` or `rate_limited`. Other capture methods cover the rest of the protocol: - `captureToolsList({ toolNames })` sends `$mcp_tools_list`. Without it, a dispatcher server has no listing events, so you can't find tools that are advertised but never called. - `captureFeedback({ report })` sends `$mcp_feedback`. Call it when `prepared.isFeedback` is true, with `report` set to `prepared.feedbackReport`. Return `sendFeedbackResult()` to the agent. To advertise the tool, set `collectFeedback` on the constructor and pass `collectFeedback: true` to `prepareToolList`. - `getToolInputProperties(args, inputSchema, { inputAliases })` returns `$mcp_input_keys`, plus `$mcp_input_aliases_used` when you pass `inputAliases`, for the original arguments. Pass the result in `properties`. These methods queue events and never throw, so analytics can't break your tool. Flush at the end of each invocation, as in [step 3](#send-queued-events-on-shutdown). Every capture method takes these fields: | Field | Becomes | Notes | | --- | --- | --- | | `distinctId` | `distinct_id` | Turns on person processing. Omit it for anonymous traffic. | | `sessionId` | `$session_id` | Omitted when you don't pass one. Keep it to 128 characters or fewer. | | `protocolVersion` | `$mcp_protocol_version` | Pass the revision of each request. | | `clientUserAgent` | `$mcp_client_user_agent` | The raw `User-Agent` header on HTTP transports. | | `vendorClient` | `$mcp_vendor_client` | A vendor client header, such as `x-anthropic-client`. | | `groups` | `$groups` | `{ groupType: groupKey }`. | | `setProperties` | `$set` | Person properties, such as name or plan. | | `properties` | event properties | Extra properties, added as they are. | | `timestamp` | event time | Defaults to the time of the call. | The `instrument()` hooks (`identify`, `intentFallback`, `eventProperties`) don't run on this path. Pass identity on each call. `prepareToolCall` and `prepareToolResult` handle intent, model capture, and conversation IDs. On a stateless server, pass the original tool as the `originalTool` option of `prepareToolCall`, so a process that didn't serve `tools/list` still knows which arguments it added. On `2026-07-28`, don't send `$mcp_initialize`, because that revision has no handshake.