TypeScript MCP Analytics installation

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. It supports both SDK majors:

Your importsMCP SDK majorProtocol revisions it serves
@modelcontextprotocol/sdkv12025-11-25 and earlier
@modelcontextprotocol/core, /server, /clientv22025-11-25 and 2026-07-28

You need:

  • Node.js 20.20+ or 22.22+
  • @modelcontextprotocol/sdk 1.26.0+ (v1) or @modelcontextprotocol/server 2.0.0+ (v2)
  • posthog-node 6
  • A PostHog project token

Using a dispatcher with no MCP SDK server object? See Custom dispatchers.

Learn more

The wizard installs the package and adds instrument() for you. To install by hand, follow the steps below.

  1. Install the packages

    Required
    Terminal
    npm install @posthog/mcp@1 posthog-node@6

    @posthog/mcp uses your posthog-node 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. 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.

    instrument() labels the whole client: every event it sends reports $lib posthog-node-mcp. If your app also captures its own events, give MCP analytics its own PostHog client.

    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
    })

    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

    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)
    })

    The MCP spec tells stdio clients to close stdin first and send SIGTERM only if the server doesn't exit in time, so the SIGTERM handler may never run. On a stdio server, also shut down when stdin ends:

    TypeScript
    process.stdin.on("end", 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. Check your first events

    Required

    Connect 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.

TypeScript
// app/api/mcp/route.ts
import { createMcpHandler, withMcpAuth } from "mcp-handler"
import { PostHog, instrument, withMcpSessionHeader } from "@posthog/mcp"
import { z } from "zod"
import { verifyToken } from "./auth" // your token check, returning mcp-handler's AuthInfo
// 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, {
// withMcpAuth puts the verified token on extra.authInfo (mcp-handler 1.x) or extra.http.authInfo (2.x)
identify: async (_request, extra) => {
type Auth = { authInfo?: { clientId: string } }
const auth = (extra as Auth | undefined)?.authInfo ?? (extra?.http as Auth | undefined)?.authInfo
return auth ? { distinctId: auth.clientId } : null
},
})
server.registerTool("echo", { inputSchema: z.object({ text: z.string() }) }, async ({ text }) => ({
content: [{ type: "text", text }],
}))
})
// Auth goes outermost and is required, so a request without a valid token is rejected before anything reads its body.
const route = withMcpAuth(withMcpSessionHeader(handler), verifyToken, { required: true })
export { route as GET, route as POST }

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 distinctId from identify, 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:

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, 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, 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:

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), 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:

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
},
})

If your server advertises a custom JSON Schema, return that schema instead.

Configuration

instrument(server, posthog, options?) takes these options:

OptionDefaultWhat it does
contexttrueAdd 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.
captureModeltrueCapture the calling model from client metadata or an llm_model argument. Pass { description } to change the argument's prompt.
enableConversationIdtrueAdd 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.
reportMissingfalseAdd the get_more_tools tool for missing capabilities.
missingCapabilityToolName"get_more_tools"Renames the reportMissing tool.
enableExceptionAutocapturetrueEmit a $exception event for each failed tool call.
sendInitializeEventtrueEmit $mcp_initialize for each handshake. Turning it off empties the users and sessions tiles on the default dashboard.
sendToolsListEventtrueEmit $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.
shouldRecordInputKeydeclared namesDecides 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.
loggerno-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:

TypeScript
const analytics = instrument(server, posthog, {
eventOptions: (request, extra) => ({ cookieless_mode: true }),
})
await analytics.capture({ event: "report_exported", eventOptions: { cookieless_mode: true } })
// On a custom dispatcher, where posthog is a PostHogMCP client:
posthog.captureToolCall({ toolName: "search_docs", sessionId, eventOptions: { cookieless_mode: true } })

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:

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) {
const reply = posthog.prepareToolResult(getMoreToolsResult(), prepared)
posthog.captureMissingCapability({
context: prepared.intent,
sessionId: reply.sessionId,
conversationId: reply.conversationId,
distinctId: user.id,
})
return reply.result
}
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.

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_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.

Every capture method takes these fields:

FieldBecomesNotes
distinctIddistinct_idTurns on person processing. Omit it for anonymous traffic.
sessionId$session_idOmitted when you don't pass one. Keep it to 128 characters or fewer.
protocolVersion$mcp_protocol_versionPass the revision of each request.
clientUserAgent$mcp_client_user_agentThe raw User-Agent header on HTTP transports.
vendorClient$mcp_vendor_clientA vendor client header, such as x-anthropic-client.
groups$groups{ groupType: groupKey }.
setProperties$setPerson properties, such as name or plan.
propertiesevent propertiesExtra 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.

Still have questions?

Was this page useful?