PostHog MCP package
Please see the main PostHog docs.
SDK usage examples and code snippets live in the official documentation so they stay up to date.
Documentation
Versioning
From 1.0.0, @posthog/mcp follows semver for its API and for the events it sends. A minor or patch release doesn't rename or remove a $mcp_* event or property, change its type, or change which requests send an event, so saved insights keep working across upgrades. It may add events and properties, and redact more of a captured value. The rules come from the MCP analytics spec, section "Event schema stability".
Stateless & multi-pod servers
On stateless deployments the SDK mints the Mcp-Session-Id response header at initialize
as a token carrying the session id and client name/version. Clients replay the header on
every request, so any pod keeps $session_id and $mcp_client_name/$mcp_client_version
stable with no server-side store.
The SDK publishes no standalone $identify event. The identify callback runs on every request,
on any pod, and stamps distinct_id and $set onto each event it sends.
Streamable HTTP: set enableJsonResponse: true
The token is minted onto the Mcp-Session-Id response header from inside the initialize
handler, so it only reaches the client when the transport builds the response after the
handler runs — i.e. JSON mode. In SSE (streaming) mode StreamableHTTPServerTransport
flushes the response headers before the handler runs, so the minted header never lands and
behavior silently falls back to a session-per-request. This is a property of the transport, so
it applies to every Streamable-HTTP host — set enableJsonResponse: true (and use a fresh
transport per request):
1// @modelcontextprotocol/sdk
2new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true })
3
4// Cloudflare agents / createMcpHandler (SSE is the default)
5createMcpHandler(server, { enableJsonResponse: true })
6
7// @rekog/mcp-nest
8McpModule.forRoot({ streamableHttp: { enableJsonResponse: true } })
If you must stream (SSE)
Set the header yourself at the HTTP layer with the exported encodeSessionId (read clientInfo
from the initialize body) — the SDK decodes it either way:
1import { MCP_SESSION_HEADER, encodeSessionId, newSessionId } from '@posthog/mcp'
2
3// after parsing the POST body, before flushing headers:
4if (body?.method === 'initialize' && !req.headers[MCP_SESSION_HEADER]) {
5 res.setHeader(
6 MCP_SESSION_HEADER,
7 encodeSessionId({
8 sessionId: newSessionId(),
9 clientName: body.params?.clientInfo?.name,
10 clientVersion: body.params?.clientInfo?.version,
11 })
12 )
13}
Details: docs/ARCHITECTURE.md §4.
MCP TypeScript SDK v2
instrument() works on both SDK majors — @modelcontextprotocol/sdk v1 and
@modelcontextprotocol/{core,server,client} v2 — and on both the high-level McpServer and the
low-level Server. Shapes are detected at runtime, so neither major is a dependency here.
Sessions and client identity on a v2 server
Protocol revision is a property of each request, not of the server: a v2 server serves both
2025-11-25 and 2026-07-28 traffic, and the SDK is instrumented once for both.
-
On
2026-07-28there is noinitializeand no session header — the revision removed protocol-level sessions, and this SDK will not mint one. Session correlation therefore comes fromenableConversationId, which is on by default. Without it every request is its own$session_id. Theget_more_toolsandsend_feedbackvirtual tools also use this handle, including calls handled by a fresh server instance. -
On
2025-11-25, the session id and the client's name and version are exchanged once atinitialize. If your server builds a freshMcpServerper HTTP request — whichcreateMcpHandlerdoes by default — the instance serving a latertools/callnever saw that handshake. The SDK bridges it by minting theMcp-Session-Idtoken described above, which the client replays on every request.That token only reaches the client if the transport builds response headers after the handler runs.
@rekog/mcp-nestwithenableJsonResponse: truedoes;createMcpHandler's legacy leg does not, and there is no setting we can reach from inside the server. On that leg, expect$mcp_client_nameand$mcp_client_versionto be absent for2025-11-25traffic — the protocol version still arrives, because clients send it on theMCP-Protocol-Versionheader of every request. A fetch-style handler can mint the token outside the server instead: wrap it inwithMcpSessionHeader, as in the Vercelmcp-handlersetup below.
Vercel mcp-handler
mcp-handler builds a fresh McpServer for every request
and passes it to your callback, so call instrument() there. Wrap the handler in
withMcpSessionHeader to keep one session per client on the 2025-11-25 protocol: mcp-handler
streams the initialize response, so the session token has to be added outside the server.
1// app/api/[transport]/route.ts
2import { createMcpHandler, withMcpAuth } from 'mcp-handler'
3import { PostHog, instrument, withMcpSessionHeader } from '@posthog/mcp'
4import { z } from 'zod'
5import { verifyToken } from './auth' // your token check, returning mcp-handler's AuthInfo
6
7const posthog = new PostHog(process.env.POSTHOG_API_KEY!, { host: 'https://us.i.posthog.com' })
8
9const handler = createMcpHandler((server) => {
10 instrument(server, posthog, {
11 // withMcpAuth puts the verified token on extra.http.authInfo
12 identify: async (_request, extra) => {
13 const auth = (extra?.http as { authInfo?: { clientId: string } } | undefined)?.authInfo
14 return auth ? { distinctId: auth.clientId } : null
15 },
16 })
17 server.registerTool('echo', { inputSchema: z.object({ text: z.string() }) }, async ({ text }) => ({
18 content: [{ type: 'text', text }],
19 }))
20})
21
22// Auth outermost and required, so a request without a valid token is rejected before anything reads its body.
23const route = withMcpAuth(withMcpSessionHeader(handler), verifyToken, { required: true })
24export { route as GET, route as POST }
instrument() may come before or after the tools are registered. Every request instruments a new
server, which is the same per-request cost the SDK v2 createMcpHandler already has.
FastMCP
FastMCP builds a new server for every session, or for every
request when stateless, inside the framework. Hand instrumentFastMCP the fastmcp module before
you start the server, and every one of those servers is instrumented:
1import * as fastmcp from 'fastmcp'
2import { PostHog, getRequestHeaders, instrumentFastMCP } from '@posthog/mcp'
3
4const posthog = new PostHog(process.env.POSTHOG_API_KEY!, { host: 'https://us.i.posthog.com' })
5
6instrumentFastMCP(fastmcp, posthog, {
7 identify: async (_request, extra) => {
8 const token = String(getRequestHeaders(extra)?.authorization ?? '').replace(/^Bearer\s+/i, '')
9 return token ? { distinctId: userIdForToken(token) } : null
10 },
11})
12
13const server = new fastmcp.FastMCP({ name: 'my-server', version: '1.0.0' })
14// server.addTool(...)
15await server.start({
16 transportType: 'httpStream',
17 httpStream: { port: 8080, stateless: true, enableJsonResponse: true },
18})
- Stateless servers need
enableJsonResponse: trueto keep one session per client, for the reason given in Streamable HTTP. - FastMCP's HTTP layer does not pass request headers to the server, so
instrumentFastMCPputs the headers of the HTTP request back onextra.requestInfo.headersfor your callbacks. - FastMCP rewrites a thrown error to
Tool '<name>' execution failed: <message>, and that is the$mcp_error_messageyou see. - It hooks the module, so it covers every FastMCP server in the process with the same options.
Reading request headers in a callback
If your identify, intentFallback, eventProperties or beforeSend reads HTTP headers, it has
to change. The two majors put the request in different places and in different shapes: v1 attaches
a plain object at extra.requestInfo.headers, v2 attaches the WHATWG Request at extra.http.req,
whose headers only answers to .get(). A v1-shaped read returns undefined on v2 — an
identify() written that way returns null and every event goes anonymous.
The SDK hands your callback whatever the MCP SDK handed it, unchanged; it does not fake a v1
shape on v2, because a partially synthesised requestInfo is a more convincing lie than an absent
one. Read headers through the exported helper instead, which handles both majors, lowercases keys,
and duck-types Headers so it also works on edge runtimes:
1import { getRequestHeaders } from '@posthog/mcp'
2
3identify: async (request, extra) => {
4 const auth = getRequestHeaders(extra)?.['authorization'] // v1 and v2
5 // ...
6}
What $mcp_intent records, and how to turn it off
context defaults to on: the SDK adds a context parameter to every tool it advertises, asks
the agent to say why it is calling, and records the answer as $mcp_intent. It is stripped before
your tool runs wherever the SDK can confirm the parameter is its own.
On a server that builds a fresh instance per HTTP request — createMcpHandler, or @rekog/mcp-nest
in its stateless mode — that confirmation is not available: ownership is learned while serving
tools/list, and the instance handling a tools/call never served one. There the SDK records the
argument but does not strip it, because deleting an argument your tool declared would cost you
the call, while an extra key usually costs nothing.
What matters is instance lifetime, not statelessness. A server that is stateless at the transport
(sessionIdGenerator: undefined) but keeps one long-lived server object learns ownership from the
first tools/list and keeps it, so none of the above applies to it.
An extra key is not free for a tool that validates strictly (a .strict() Zod object, or
additionalProperties: false enforced by the handler): it rejects the call. A low-level server that
can look up its own tools can resolve ownership without a listing. Return the tool's input schema
as registered, before PostHog preparation, and the SDK strips the arguments it owns on every
instance. It never strips a parameter that the returned schema declares. Returning undefined
keeps the behavior above.
1instrument(server, posthog, {
2 resolveOriginalTool: (toolName) => {
3 const tool = myToolRegistry.get(toolName)
4 return tool ? { inputSchema: tool.inputSchema } : undefined
5 },
6})
The consequence worth knowing: if your own tool declares a parameter named context and the SDK
cannot tell that it is yours, its value is recorded as $mcp_intent. It never leaves your project,
and it is capped at 2048 characters. Two ways out, both one line:
1instrument(server, posthog, { context: false }) // no injection, no capture
2
3instrument(server, posthog, {
4 // keep it, drop the property
5 beforeSend: (event) => {
6 delete event.properties.$mcp_intent
7 return event
8 },
9})
intentFallback is the third option: supply the intent yourself when the agent did not send one.
Whatever the agent narrates, the SDK redacts structured personal identifiers — email addresses, phone
numbers, IPv4/IPv6 addresses, Luhn-valid card numbers, and US SSNs — from $mcp_intent before it is
sent. This is always on and needs no configuration. It is best-effort for those well-defined shapes,
not for free-form personal data such as names or postal addresses, which a regex cannot catch without
over-redacting ordinary prose. It also applies only to $mcp_intent: structured tool arguments and
results are left as-is, because the same shapes are often legitimate data there. If you need a stronger
guarantee, context: false and the beforeSend hook above remain the ways to drop the field entirely.
Defaults and opt-outs
On fresh low-level instances, tools with an outputSchema deliver new handles through content only. Clients that consume only structuredContent will not echo those handles, so correlation is not guaranteed for that combination. Unknown ownership can also cause a prompt-back block to be appended for a schema that discovery would not extend; disable enableConversationId if that contract is unsuitable.
A valid echoed conversation handle takes precedence over transport sessions. A request that already carries a transport session or a PostHog session token does not mint a new handle or append a prompt-back block. Requests carrying neither use the conversation fallback.
Some MCP clients name the conversation in each tool call's params._meta: ChatGPT's
openai/session, Codex's sessionId, and VS Code's vscode.conversationId. The SDK reads each key
only from a request whose User-Agent or client name identifies that client, and derives
$session_id from it ahead of any conversation handle or transport session. ChatGPT sends its id on
every call, so its tools/list has no conversation_id argument and its results get no handle, even
with enableConversationId on. Each event records which source grouped it in $mcp_session_source:
client_metadata, conversation, transport, or generated.
Intent, model capture, conversation correlation, exception capture, and $mcp_initialize are
enabled by default. Missing-capability reporting and feedback collection remain disabled.
1instrument(server, posthog, { captureModel: false, enableConversationId: false })
Model capture adds an optional llm_model argument to compatible tool schemas. Strict-schema
clients see the new field. Set captureModel: false to leave schemas untouched. Conversation correlation adds an optional
conversation_id argument and returns a handle in eligible tool results. Clients must echo that
handle to group later calls; calls without it mint new handles. Set enableConversationId: false
to retain transport-based session grouping and unchanged response content. Custom PostHogMCP
dispatchers also enable model capture and conversation correlation by default.
The reasoning behind these defaults is in ADR-0013.
Set sendInitializeEvent: false to stop sending $mcp_initialize. Many clients reconnect before
every few tool calls, so this event can outnumber $mcp_tool_call. Nothing else changes in what
the SDK sends: tool calls keep their sessions and client identity. In PostHog, MCP onboarding and
the users and sessions tiles of the default MCP dashboard read $mcp_initialize. They show no data
while the option is off.
1instrument(server, posthog, { sendInitializeEvent: false })
Set sendToolsListEvent: false to stop sending $mcp_tools_list. Nothing else changes: tools keep
their injected arguments, and the virtual tools stay listed.
Identifying the deployed server build
MCP advertises a server version, but it does not define an exact build identifier. Pass an immutable
Git commit SHA, release ID, or container digest once during setup. The SDK adds it to every MCP event
as $mcp_server_build.
1instrument(server, posthog, { serverBuild: process.env.GIT_SHA })
2
3const customDispatcherClient = new PostHogMCP(process.env.POSTHOG_PROJECT_TOKEN, {
4 serverBuild: process.env.GIT_SHA,
5})
Omit serverBuild when the deployment does not provide a reliable value.
PostHogMCP also adds the build to custom events from its inherited capture() and captureImmediate() methods.
Per-event options (eventOptions)
eventOptions sets posthog-node per-event options, such as process_person_profile, on MCP events.
Give instrument() a callback for every auto-captured event, or pass eventOptions per call to
analytics.capture() and to the PostHogMCP capture methods. The callback runs only for
auto-captured events, since analytics.capture() has no request to pass it. A failed call's
$exception event gets the same options.
1const analytics = instrument(server, posthog, {
2 // Process persons for anonymous sessions too
3 eventOptions: (request, extra) => ({ process_person_profile: true }),
4})
5
6await analytics.capture({ event: 'report_exported', eventOptions: { process_person_profile: false } })
7
8posthogMCP.captureToolCall({
9 toolName: 'search_docs',
10 sessionId,
11 eventOptions: { process_person_profile: true },
12})
Events from a session with no resolved identity are personless by default: they carry the
process_person_profile: false option. An explicit process_person_profile in eventOptions wins
over that default.
beforeSend receives the options as event.options and can change them. The SDK sends what it
returns. On posthog-node 6.x.x, the client's own beforeSend sees them too. posthog-node 5.x.x has no
per-event options, so the SDK sends the known options the way that version reads them and drops
other keys. PostHogMCP.capture() is posthog-node's own capture(), so it takes posthog-node's
options field instead of eventOptions.
What $mcp_llm_model records, and when it stays empty
captureModel is on by default. The SDK records the best model id visible to the
server as $mcp_llm_model. Recognized client metadata wins with source client_metadata. Otherwise,
the SDK injects an optional llm_model parameter and records the answer with source self_reported.
MCP does not standardize or attest model identity. Client metadata and self-report are both
unverified. Use the value to spot degradation across models, never for billing or access control.
Missing, blank, and unknown values are recorded as nothing.
The recognized metadata path is Codex's x-codex-turn-metadata.model field inside request _meta.
Other clients keep using self-report until they expose a stable model field.
Like context, self-report follows the ownership rule of ADR-0011: reading llm_model fails
open where the SDK cannot tell who declared it, stripping it requires proof that the SDK did:
instrument(server)on a high-levelMcpServerresolves ownership for your registered tools per request from the live tool registry, so those work even on a fresh instance.- The
get_more_toolsvirtual tool works on any instance and on either server type: the SDK writes that descriptor itself, so what it declares is known without a listing. - Instrumenting a low-level
Serverlearns ownership while servingtools/list. A fresh instance that never served one —createMcpHandler, or@rekog/mcp-nestin its stateless mode — has no answer, so it recordsllm_modelas the self-reported model and strips nothing, unlessresolveOriginalToolsupplies the tool's schema (see$mcp_intentabove). Return the schema as yourtools/listadvertises it: ownership follows the same rule as a served listing, and a listing served on the instance wins. A Zod schema is read the way the MCP SDK advertises it, so a union, record or refined object lists as an empty object, gains the injected fields and has them stripped; a host that lists its own JSON Schema (ananyOf, say) returns that schema. A tool that declares its ownllm_modelon such an instance is therefore recorded under$mcp_llm_modeluntil a listing says otherwise;captureModel: falseor dropping the property inbeforeSendare the escapes. The SDK never replays your listing handler on the call path to find out.
As with context, what matters is instance lifetime rather than statelessness: a transport-stateless
server (sessionIdGenerator: undefined) that keeps one long-lived server object learns ownership
from the first tools/list and keeps it.
For a custom dispatcher, PostHogMCP enables model capture and conversation correlation by default.
prepareToolList() injects the analytics fields and records ownership by tool name.
prepareToolCall() removes SDK-owned arguments and resolves the conversation and session.
prepareToolResult() returns the result to send and the final values to capture. Pass the original
tool descriptor on each call so this also works when tools/list and tools/call reach different
server replicas:
1const posthog = new PostHogMCP(process.env.POSTHOG_PROJECT_TOKEN)
2
3const tools = posthog.prepareToolList(serverTools)
4const originalTool = serverTools.find((tool) => tool.name === toolName)
5const preparedCall = posthog.prepareToolCall(toolName, rawArgs, {
6 originalTool,
7 requestMeta: request.params?._meta,
8 sessionId: transportSessionId,
9})
10const toolResult = await dispatch(toolName, preparedCall.args)
11const preparedResult = posthog.prepareToolResult(toolResult, preparedCall)
12
13posthog.captureToolCall({
14 toolName,
15 llmModel: preparedCall.llmModel,
16 llmModelSource: preparedCall.llmModelSource,
17 sessionId: preparedResult.sessionId,
18 conversationId: preparedResult.conversationId,
19 isError: false,
20})
21
22return preparedResult.result
A persistent single-process dispatcher can omit originalTool after it has prepared its tool list.
Pass requestMeta whenever the request supplies _meta, and headers (plus clientInfo from a
handshake bound to the request, if you hold one) so the SDK can recognize the client; this enables
recognized client metadata and client conversation ids without changing the arguments sent to the
tool. Pass the same headers to prepareToolList. Pass an existing transport or request session as
sessionId. A client conversation id or a valid echoed conversation handle takes precedence. Otherwise, the existing session
prevents a new handle from being minted. Set enableConversationId: false on PostHogMCP to keep
the previous custom-dispatcher behavior.
Collecting agent feedback (send_feedback)
collectFeedback is off by default. Turn it on and the SDK advertises a send_feedback virtual
tool: an honest, general feedback channel from the agent to your team. The tool description lists
a capability the agent needed that no tool provides first, and also invites reports about a tool
that failed or misled the agent, and praise. Every call emits one $mcp_feedback event — never a
$mcp_tool_call — with $mcp_feedback_type, $mcp_feedback_summary, and the other
$mcp_feedback_* properties; the summary and details double as $mcp_intent. The agent receives an
acknowledgement that says exactly what happened: the report was recorded, no tools were added.
1instrument(server, posthog, {
2 collectFeedback: {
3 // All fields optional; `collectFeedback: true` uses the defaults.
4 toolName: 'send_feedback',
5 extraProperties: {
6 product_area: { type: 'string', description: 'The product or feature the feedback is about.' },
7 },
8 extraRequired: ['product_area'],
9 onFeedback: async (report) => {
10 await myFeedbackBackend.record(report) // report.extras.product_area, report.raw, ...
11 return 'Thanks - your feedback reached the team.' // replaces the default acknowledgement
12 },
13 },
14})
Host-declared extraProperties are merged into the advertised schema and captured as
$mcp_feedback_<key> (sanitized and bounded like every captured value). Arguments the agent invents
beyond the schema are never captured — they reach onFeedback via report.raw only. A key that
collides with a core field fails at configuration time. Free-text fields go through the same PII
redaction as $mcp_intent.
onFeedback's returned string replaces the acknowledgement and is captured as $mcp_response
through the generic sanitize pipeline only — it does not get the structured-PII redaction applied to
$mcp_feedback_summary/details, so don't echo the agent's raw report text back in it.
On the custom-dispatcher path, configure the tool on the PostHogMCP constructor and route reports
yourself (onFeedback does not apply there):
1const posthog = new PostHogMCP(process.env.POSTHOG_PROJECT_TOKEN, {
2 collectFeedback: { toolName: 'send_feedback' },
3})
4
5// tools/list handler
6return { tools: posthog.prepareToolList(myTools, { collectFeedback: true }) }
7
8// tools/call dispatcher
9const originalTool = myTools.find((tool) => tool.name === name)
10const preparedCall = posthog.prepareToolCall(name, rawArgs, { originalTool })
11if (preparedCall.isFeedback) {
12 await myFeedbackBackend.record(preparedCall.feedbackReport!)
13 const preparedResult = posthog.prepareToolResult(sendFeedbackResult(), preparedCall)
14 posthog.captureFeedback({
15 report: preparedCall.feedbackReport!,
16 sessionId: preparedResult.sessionId,
17 conversationId: preparedResult.conversationId,
18 ...identity,
19 })
20 return preparedResult.result
21}
originalTool must come from the application's tool list before prepareToolList() adds PostHog's
virtual tools. This lets a real application tool with the configured feedback name win, including
when tools/list and tools/call reach different server replicas.
send_feedback covers what reportMissing covers — a capability gap is
feedback_type: "missing_capability" — so new integrations should enable only collectFeedback.
reportMissing and its $mcp_missing_capability event stay unchanged for existing users; enabling
both advertises both tools. Like get_more_tools, a real tool that already uses the configured name
wins: the SDK warns, skips injection, and delegates calls to the real handler.
On a paginated catalogue (a tools/list response with a nextCursor), instrument() injects
its virtual tools (send_feedback and get_more_tools) on the first page only — the page every
client reads, including clients that never follow nextCursor — so a compliant client's
concatenated list carries each once. "First page" means a tools/list request with no cursor; an
empty string is a valid cursor, so cursor: "" is a continuation page. Hosts using
prepareToolList() directly own this rule themselves: pass reportMissing: true and
collectFeedback: true only for the first page.
Name collisions are detected on the first page only. A real tool named send_feedback (or
get_more_tools) on the first page wins: the SDK warns, skips injection, and forwards its calls. A
real tool that only appears on a later page is not detected up front — the SDK's virtual tool is
injected and intercepts calls to the name, so the real tool is shadowed and a concatenated listing
carries the name twice. The SDK logs a warning when a client fetches the colliding page, but the fix
is yours: rename the SDK's tools with collectFeedback: { toolName: "..." } and the
missingCapabilityToolName option.
If you switched to instrument(server.server)
Before v2 support landed, the compatibility gate rejected high-level v2 servers, and the usual
workaround was to instrument the underlying low-level server. instrument(server) now works, so
you can go back to the documented call.
Whether the workaround costs you anything depends on your stack: instrumenting the low-level server
skips the high-level tool registry, so tool descriptions and callback-level wrapping come only from
what is advertised over tools/list. If your framework never calls registerTool() — @rekog/mcp-nest
does not — the registry is empty and the two calls behave the same.
Library identity ($lib)
instrument() and PostHogMCP label the whole posthog-node client: every event it captures afterwards reports $lib posthog-node-mcp and $lib_version set to the @posthog/mcp version, not only the $mcp_* events. So:
- Give MCP analytics its own
PostHogclient if your app also captures other events. - With posthog-node 6.x.x, events the client captured before
instrument()keepposthog-node, except an exception it was still building. With posthog-node 5.x.x, an event captured just beforeinstrument()can get the MCP label too. - With posthog-node 6.x.x, a
$libyou set on an event, in a context or withregister()wins over the label. Set$lib_versiontoo, or the event is sent without one. - To find MCP traffic, filter on
$mcp_*events or$mcp_source = 'posthog_mcp_analytics'rather than$lib.
Developing locally
To test local changes in a consumer app (e.g. a dummy MCP server), symlink both
@posthog/mcp and its posthog-node peer from this monorepo into the app — run from the
app's directory:
1mkdir -p node_modules/@posthog # in case the app has no other @posthog/-scoped deps yet
2ln -s /absolute/path/to/posthog-js/packages/mcp node_modules/@posthog/mcp
3ln -s /absolute/path/to/posthog-js/packages/node node_modules/posthog-node
Then keep a watch build running and restart the app after each change:
1cd /absolute/path/to/posthog-js/packages/mcp && pnpm dev # rebuilds dist/ on save
2
3# in the app (e.g. dummy mcp), after each rebuild:
4npm start # Node caches dist/ at startup, so restart to pick it up
npm installin the app replaces both symlinks with published copies — re-create them if you run it.
Run tests
1cd packages/mcp && pnpm test:unit