TypeScript MCP Analytics installation
@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. 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 |
You need:
- Node.js 20.20+ or 22.22+
@modelcontextprotocol/sdk1.26.0+ (v1) or@modelcontextprotocol/server2.0.0+ (v2)posthog-node6- A PostHog project token
Using a dispatcher with no MCP SDK server object? See Custom dispatchers.
The wizard installs the package and adds instrument() for you. To install by hand, follow the steps below.
- 1
Install the packages
RequiredTerminal@posthog/mcpuses yourposthog-nodeclient to send events. You own that client's lifecycle.@posthog/mcpre-exportsPostHog, so one import covers both.posthog-nodeis still a peer dependency, so install it too. - 2
Wrap your server
RequiredCall
instrument(server, posthog)once, before the server accepts requests. Pass theMcpServeror the low-levelServer. The SDK also instruments tools that you register later.instrument()labels the whole client: every event it sends reports$libposthog-node-mcp. If your app also captures its own events, give MCP analytics its ownPostHogclient.instrument()returns an analytics handle for custom events. A second call on the same server logs a warning and returns a working handle. - 3
Send queued events on shutdown
Requiredposthog-nodesends events in batches. Callposthog.shutdown()when the process stops:TypeScriptThe MCP spec tells stdio clients to close
stdinfirst and sendSIGTERMonly if the server doesn't exit in time, so theSIGTERMhandler may never run. On a stdio server, also shut down whenstdinends:TypeScriptIn serverless and edge functions,
SIGTERMmay not run. Callawait posthog.flush()at the end of each invocation, orctx.waitUntil(posthog.flush())where the platform supports it. - 4
Check your first events
RequiredConnect an agent to your server and call a tool. Then open the activity feed and filter for
event = $mcp_tool_call. See the event reference for every property.
Frameworks
Next.js and Vercel (mcp-handler)
mcp-handler builds a new McpServer for every request and passes it to your setup callback. Call instrument() there, then wrap the route in withMcpSessionHeader. withMcpSessionHeader needs @posthog/mcp 1.5.0 or later.
This is mcp-handler 2.x. On 1.x, mount the route at app/api/[transport]/route.ts and pass {}, { basePath: "/api" } after the setup callback.
instrument() can run before or after you register tools. The identify callback is optional. Drop it, and withMcpAuth, if your server has no auth.
On 2025-11-25, the client sends its name and version only at initialize, and every later request reaches a new server. mcp-handler streams the initialize response, so instrument() can't add the session token to it. withMcpSessionHeader adds the token at the route instead. The client replays it, so its calls share one $session_id and keep $mcp_client_name and $mcp_client_version.
2026-07-28 has no initialize and no session header. withMcpSessionHeader passes those requests through unchanged. To group a client's calls on that revision:
- Keep conversation IDs on (the default). Calls group when the agent echoes the handle.
- Return a
distinctIdfromidentify, such as the authenticated user's ID. This groups calls by user, not by session.
Flush at the end of each invocation, as in step 3.
NestJS (@rekog/mcp-nest)
@rekog/mcp-nest creates the server through McpModule.forRoot(...). Add instrumentMutator to its serverMutator hook:
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, call instrument() yourself:
Read request headers on both SDK majors
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:
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, the SDK carries the session and client name in a token on the Mcp-Session-Id header, so any pod reads the same values. On 2026-07-28, use conversation IDs.
The SDK can only send the token in JSON mode. Set enableJsonResponse: true on a fresh transport per request:
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), wrap a fetch-style route in withMcpSessionHeader, as in Next.js and Vercel. On a Node response, set the header yourself before the response headers go out:
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:
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. 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 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 across requests. |
identify | – | (request, extra) => UserIdentity \| null, or a static UserIdentity. Maps a request to one of your users. |
reportMissing | false | Add the get_more_tools tool for missing capabilities. |
missingCapabilityToolName | "get_more_tools" | Renames the reportMissing tool. |
enableExceptionAutocapture | true | Emit a $exception event for each failed tool call. |
sendInitializeEvent | true | Emit $mcp_initialize for each handshake. Turning it off empties the users and sessions tiles on the default dashboard. |
sendToolsListEvent | true | Emit $mcp_tools_list for each tools/list. |
beforeSend | – | (event) => event \| null. Change or drop each event before it's sent. See Privacy. |
eventProperties | – | (request, extra) => Record<string, unknown>. Adds properties to every event. |
eventOptions | – | (request, extra) => Record<string, unknown> \| null. Sets event options on every auto-captured 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. |
logger | no-op | (message) => void. A stdio-safe sink for SDK warnings. |
context, captureModel, and enableConversationId each add an argument to every tool: context, llm_model, and conversation_id. The model sees them when it lists your tools, so they use part of its context. Set an option to false to remove its argument.
Event options
eventOptions sets event options, such as cookieless_mode or process_person_profile, on MCP events. It needs @posthog/mcp 1.3.0 or later. Set it on instrument() for every auto-captured event, or per call on analytics.capture() and the PostHogMCP capture methods:
On posthog-node 5, eventOptions supports only process_person_profile, cookieless_mode, disable_skew_correction, and product_tour_id, and drops other keys.
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, and missingCapabilityToolName:
Call the capture methods from your dispatcher. They build the same $mcp_* events as instrument(), with the same redaction and size limits:
Pass errorType to captureToolCall to set $mcp_error_type to your own label, such as validation.
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.getToolInputProperties(args, inputSchema, { inputAliases })returns$mcp_input_keys, plus$mcp_input_aliases_usedwhen you passinputAliases, for the original arguments. Pass the result inproperties.
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.
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. |
The instrument() hooks (identify, intentFallback, eventProperties, eventOptions) don't run on this path. Pass identity, and any eventOptions, on each call. On a stateless server, pass originalTool to prepareToolCall. On 2026-07-28, don't send $mcp_initialize.





