Contents

@posthog/mcp — Architecture

This document describes the internals of the @posthog/mcp SDK and the exact PostHog event/property contract it emits.

It documents the current state only. The reasoning behind architectural decisions — what problem forced them, what was rejected, what trade-offs were accepted — lives in docs/adr/; the filenames are the index. When this document says "see ADR-NNNN", that's where the why is. Not every change gets an ADR: ADR-0001 has the conventions and the bar for what counts as architecturally significant.

TL;DR

  • instrument(server, posthog, options?) wraps an MCP server, intercepts request handlers, and pushes structured events through a small in-memory pipeline into PostHog via the host's posthog-node client (posthog.capture()). It returns an McpAnalytics handle.
  • Every SDK-owned PostHog event name is $-prefixed ($mcp_tool_call, $mcp_initialize, …) per the PostHog naming convention. (Custom events you emit via analytics.capture() keep your own verbatim name — they're customer events, not SDK-owned.)
  • Every PostHog property key is also $-prefixed ($mcp_tool_name, $mcp_intent, $mcp_duration_ms, …) so MCP keys never collide with PostHog autocapture, web analytics, or other product events.
  • $session_id ties one MCP connection to one PostHog session. distinct_id falls back through identified user → session id → "anonymous".
  • Tool calls additionally emit a sibling $exception event whenever a tool errors (unless enableExceptionAutocapture: false).

Resource bodies are not captured; a resource listing is, because names, uris, and uri templates are discovery metadata rather than content. A fragment is split at its first ? and each side is read as credential-named fields when it holds an = and as text otherwise, so both an OAuth #access_token=… fragment and a single-page-app #/callback?token=… are covered. Captured URLs redact usernames, passwords, and credential-named query and fragment parameters, including signed URL credentials — a key is credential-named when any -/_/.///;-delimited segment of it is (private_token, X-Amz-Signature, subscription-key, /token, download;token), which over-redacts a benign sort_key by design. A URL nested inside a retained parameter value is sanitized one level deep; a value that still carries a URL past that level is dropped whole rather than trusted. When a URL appears inside prose, the trailing punctuation the match absorbs is restored — unless the URL's last query field was itself redacted, in which case the punctuation goes with it, since it may be the credential's own tail. An address is recognized with or without an authority, so an MCP resource URI such as resource:guide?token=… is covered alongside https://…. URLs longer than 8,192 characters or with more than 128 query fields are redacted entirely to bound parsing work. The length bound applies only to an address that carries an authority; a long authority-less match — typically a data URI — is sanitized like any other and kept intact when it holds nothing to redact. This also applies when a failed read repeats the URL in its error message. Other query parameters can still contain application-specific sensitive data. Requests and responses keep their original addresses. Use beforeSend to remove any additional application-specific sensitive data.


1. Wire-up

The public surface in src/index.ts:

  • instrument(server, posthog, options?) — installs the SDK on an MCP server. The posthog-node client is a required positional 2nd argument; options is the optional 3rd argument. Returns an McpAnalytics handle (exposing .capture()). Idempotent per server (re-calling logs and returns early).
  • analytics.capture({ event, properties }) — a method on the McpAnalytics handle returned by instrument() that emits a custom event onto the same pipeline. event is required and sent verbatim (a custom event is a customer event, so it is not $-prefixed). Returns a promise that resolves once the event has been processed, so callers can await it.

The host application supplies its own posthog-node client as the positional posthog argument (same pattern as @posthog/ai) and owns its lifecycle — there is no SDK-managed client to flush or shut down. Internally, instrument() wraps that client in an McpEventSink (src/extensions/sink.ts, not exported) that runs the pipeline and calls posthog.capture().

instrument() does five things (src/index.ts):

  1. Validate server is either a low-level Server or a high-level McpServer, and unwrap the latter to get the underlying Server. Both MCP TypeScript SDK majors are supported, and which one you have is never read — capabilities are detected by object shape in src/extensions/detect.ts (ADR-0005).
  2. Wrap the user-provided posthog client in an McpEventSink.
  3. Build per-server tracking state (session id, identity cache, callbacks, the sink) stored in a module-level WeakMap.
  4. Replace the tools/list, tools/call, resources/list, resources/templates/list, resources/read, and initialize handlers on the underlying Server instance with wrappers, and (for McpServer) install a Proxy on _registeredTools so any tool registered after instrument() is also wrapped.
  5. Optionally register the get_more_tools virtual tool when options.reportMissing: true, and the send_feedback virtual tool when options.collectFeedback is set.

Two thin adapters exist for the two MCP server shapes, each wrapping the shared captureToolCall() lifecycle in src/extensions/instrumentation.ts:

Server type File Entry
Low-level Server (raw protocol SDK) src/extensions/instrument-lowlevel.ts instrumentLowLevelServer()
High-level McpServer (typed wrapper) src/extensions/instrument-highlevel.ts instrumentHighLevelServer()

Both converge on the same internal McpEvent shape (src/types.ts) and funnel through captureToolCall in src/extensions/instrumentation.ts, which owns the shared tool-call lifecycle and the same publish pipeline.

2. Request lifecycle (tool call, high-level path)

client → MCP server → tools/call wrapper (instrument-highlevel.ts) → captureToolCall (instrumentation.ts)
  ├─ prepareToolCallEvent         ← build McpEvent, resolve session
  ├─ handleIdentify               ← resolves identity (§4)
  ├─ applyResolvedMetadata        ← runs eventProperties and eventOptions callbacks
  ├─ resolveToolCallIntent        ← context arg OR intentFallback callback
  ├─ execute(request, extra)      ← run the wrapped tool handler
  ├─ attach result, duration, error
  └─ captureEvent(server, event)  → McpEventSink.capture()

The wrapper strips SDK-injected context and conversation_id arguments from params.arguments before validation and tool execution. Fields already declared by the tool's own schema are preserved.

3. Event pipeline

The pipeline lives in an exported processMcpEvent() function in src/extensions/sink.ts that both McpEventSink.capture() and the test harness call, so it's the single source of truth for the transform. Once an McpEvent reaches it, it runs through:

  1. Sanitization — sanitizeEvent (src/extensions/sanitization.ts):
    • type: "image" | "audio" content blocks → replaced with a text stub.
    • type: "resource" blocks with .blob → replaced.
    • Long base64-looking strings (≥10KB) → "[binary data redacted...]".
    • Keys matching SENSITIVE_KEY_PATTERN (authorization, cookie, password, token, secret, api_key, private_key, …) → value replaced with "[redacted]".
    • PostHog API-key patterns (ph[a-z]_...) in string values → "[redacted]".
  2. Truncation — truncateEvent (src/extensions/truncation.ts): per-field caps, recursive normalization (max depth 10, max breadth 100, max string 32KB), and a 100KB total event budget with progressive falloff.
  3. Build PostHog events — buildPostHogCaptureEvents (src/extensions/posthog-events.ts) fans one internal event out to up to 2 PostHog events:
    • Always: the main $mcp_* capture event.
    • If event.isError && event.error (and enableExceptionAutocapture !== false): a sibling $exception event.
    • Each payload gets its own copy of the event's per-event options, plus the anonymous process_person_profile: false default (see §4).
  4. beforeSend: each fully-built PostHog payload ({ event, distinct_id, properties, options }) is passed through options.beforeSend(event) (sync or async) right before dispatch, so it runs once per emitted event, including the $exception sibling. Returning the (possibly mutated) payload sends it. Returning a nullish value drops it. A throw drops that event (and is logged). This is the seam for customer redaction or property and option tweaks. The SDK sends the options the hook returns.
  5. Dispatch: each surviving event is handed to the user's posthog-node client via posthog.capture(). On posthog-node 6.x.x, detected by registerOptions, the payload's options are passed as the event's options. posthog-node 5.x.x has no per-event options, so the SDK sends each known option the way that version reads it and drops unknown keys. Batching, retries, and flushing are owned by that client. The host calls posthog.shutdown() to drain. The SDK installs no process-signal handlers and owns no client lifecycle.

Tool input field names

Automatic tool-call events include $mcp_input_keys on success and failure. The SDK reads the original arguments before validation can remove unknown fields. It records up to 20 top-level field names, sorted, without their values. By default, only names declared by the server's input schema remain visible. Unknown names and names longer than 64 characters are replaced by one [redacted] entry, the same marker the SDK uses for other hidden data. Declared names come first, so [redacted] appears only when the 20-name limit leaves space.

The shouldRecordInputKey(key, { declared }) option replaces the default rule, for automatic capture and as the helper's third argument. Return true to record a name; any other result, or a throw, records [redacted]. The 64-character limit, the 20-name limit, and declared-names-first ordering still apply. Use it when your server can accept that a caller-chosen name reaches analytics, for example to see misspelled parameter names:

 1instrument(server, posthog, {
 2  shouldRecordInputKey: (key, { declared }) => declared || /^[A-Za-z0-9_.-]+$/.test(key),
 3})

SDK argument names (context, llm_model, and conversation_id) are omitted unless the application schema declares them. Non-object arguments do not produce this property.

High-level servers use the registered tool's schema. Low-level servers use schemas from prior tools/list responses on the same server instance. Before a listing, or when a schema cannot be inspected, every name is hidden behind [redacted] by default. Alias names from resolveInputAliases remain visible because the server owns and declares them. The helper supports top-level JSON Schema properties, Zod raw shapes, and Zod object schemas, including objects wrapped by refinements, transforms, preprocessors, pipes, and optional, nullable, default, catch, or readonly wrappers. A pipe reports the names of its input schema. It does not resolve JSON Schema references or inspect fields inside unions.

Servers with declared input aliases can provide them to automatic instrumentation. For example, this server accepts city or place instead of location for one tool. It also accepts orderId or id instead of order_id for another tool:

 1import { instrument, type InputAliasMap } from '@posthog/mcp'
 2
 3const inputAliasesByTool: Record<string, InputAliasMap> = {
 4  'weather-current': {
 5    location: ['city', 'place'],
 6  },
 7  'order-get': {
 8    order_id: ['orderId', 'id'],
 9  },
10}
11
12instrument(server, posthog, {
13  resolveInputAliases: (toolName) => inputAliasesByTool[toolName],
14})

The resolver returns canonical name to aliases in the order the server tries them. The server must already accept and normalize these aliases. The SDK uses the map only for telemetry and does not change the tool arguments.

For this tool call:

 1{
 2  "name": "weather-current",
 3  "arguments": {
 4    "city": "Berlin"
 5  }
 6}

The SDK adds these properties to the $mcp_tool_call event:

 1{
 2  "$mcp_input_keys": ["city"],
 3  "$mcp_input_aliases_used": ["city:location"]
 4}

Custom dispatchers use the same helper through the existing properties argument:

 1import { getToolInputProperties, PostHogMCP } from '@posthog/mcp'
 2
 3const posthog = new PostHogMCP(process.env.POSTHOG_PROJECT_TOKEN)
 4await posthog.register({ $mcp_server_build: 'example-build' })
 5
 6const properties = getToolInputProperties(rawArguments, originalTool.inputSchema)
 7posthog.captureToolCall({ toolName, isError: false, properties })

Compute these properties before argument normalization, and include them in both success and error events. Pass a schema owned by the server, never one supplied by the caller. Custom command formats must extract the actual tool arguments and schema before calling the helper. A server that accepts alternative field names passes its own alias map as inputAliases, canonical name to aliases in the order the server tries them:

 1const properties = getToolInputProperties(rawArguments, originalTool.inputSchema, {
 2  inputAliases: { id: ['experimentId', 'experiment_id'] },
 3})
 4// { experimentId: 30 } → $mcp_input_keys: ['experimentId'], $mcp_input_aliases_used: ['experimentId:id']

Alias names count as declared, so they stay visible in $mcp_input_keys. $mcp_input_aliases_used records alias:canonical for each canonical name the call did not send, using the first of its aliases that the call did send. It is omitted when no alias was needed, and it holds at most 20 entries. Do not report alias use through server-specific $mcp_* properties. The SDK does not normalize arguments; the map only describes what the server's own normalizer does.

The helper adds no request values to the event. Existing parameter and response capture remains unchanged. Use beforeSend to remove $mcp_input_keys when needed. The underlying PostHog client also exposes beforeSend in Node 6 (before_send in Node 5). No session store or additional network request is required.

4. Session & identity

Shared event properties

Use the underlying PostHog client's register() method for values that apply to every event from that client. PostHogMCP inherits this method from posthog-node, and instrument() sends events through the supplied client.

 1await posthog.register({
 2  $mcp_server_build: 'example-build',
 3  environment: 'production',
 4})

Register these values during startup, before the server accepts requests. The build identifier describes the host server release, independently of the analytics SDK version. The server supplies it from its deployment configuration; the SDK does not read Git or environment variables for it.

Registered properties apply to MCP events sent through posthog.capture(), including tool calls and their exception events, and to ordinary capture() events from the client. Do not depend on them for inherited identify(), groupIdentify(), or alias() events, or for minimized $feature_flag_called events. An event's own properties take precedence over registered properties. The underlying client's beforeSend hook (before_send in Node 5) receives the merged properties. The MCP-specific beforeSend hook runs earlier and does not receive registered properties or registered options. Use a separate client when servers need different shared properties. Keep user and request data on individual events, because a shared client can serve concurrent requests.

Session resolution

  • Session ID format: ses_<uuidv7> (src/extensions/ids.ts). Uses uuidv7 from @posthog/core.
  • Session resolution (resolveSession, src/extensions/session.ts) — five sources, first match wins. The winning source is stamped as $mcp_session_source (client_metadata, conversation, transport, generated):
    1. Client conversation id (tool calls only): a recognized client's own id in params._meta, per the table in src/extensions/client-conversation.ts — ChatGPT's openai/session, Codex's sessionId, VS Code's vscode.conversationId. A row's key is read only from a request whose User-Agent or client name recognizes that client. Hash <key>:<id> (deriveSessionIdFromClientConversation). Wins over a handle the agent echoes, sets no $mcp_conversation_id, and is never persisted to shared state. See ADR-0014.
    2. Conversation handle (an agent-carried conversation_id tool argument, enableConversationId: true): hash it (deriveSessionIdFromConversation) — the 2026-07-28 anchor. Never persisted to shared state. See ADR-0004.
    3. Session token (the replayed mcp-session-id request header): use the session id inside it and save the token's client name/version for events. See "Session tokens" below.
    4. Transport session id (extra.sessionId, stateful servers): hash it (deriveSessionIdFromMCPSession) so the same MCP session maps to the same PostHog session across restarts.
    5. Memory: keep the current id. Only generated sessions roll over, after 30 minutes of inactivity; conversation/token/MCP sessions live as long as the client replays them.
  • Session tokens — stateless / multi-pod continuity on MCP 2025-11-25 (src/extensions/session-token.ts, ADR-0003):
    • At initialize, when neither the client nor the transport supplied a session id, mintStatelessSessionOnInitialize sets the Mcp-Session-Id response header to base64url(JSON) with shortened keys (sid = session id, cn/cv = client name/version, pv = protocol version). Any pod decodes the replayed header — no store, no sticky routing, no client changes. The token is unsigned and re-minted after the handler runs so it carries the negotiated protocol version, not the requested one.
    • JSON-mode constraint: the auto-mint reaches the wire only with enableJsonResponse: true (headers are built after handlers run). SSE flushes headers first, so SSE servers set the header themselves with the exported encodeSessionId; the SDK still decodes it. Stateless mode also needs the SDK's usual fresh-transport-per-request pattern.
    • Degradation: clients that don't replay the header fall back to the pre-token behavior — a generated session per request.
  • MCP 2026-07-28 (stateless revision): the revision removes initialize and the Mcp-Session-Id header, so the token machinery is legacy-only there. The session anchor is the agent-carried conversation_id (source 1 above), and client name/version + protocol version travel in every request's params._meta (src/extensions/client-identity.ts), stamped per-event so concurrent requests can't cross-attribute. $mcp_initialize is no longer a universal session anchor — anchor analysis on the first $mcp_tool_call. Era detection (suppressing the header for these clients) is an open follow-up. See ADR-0004.
  • Handle-free clients: a client whose row sends an id on every call (ChatGPT) gets no conversation_id argument in its tools/list and is minted no handle. Codex and VS Code keep the handle as a fallback for calls that carry no valid id.
  • Custom dispatchers: PostHogMCP uses the same order. prepareToolCall reads the client conversation id from requestMeta, recognizing the client from headers and clientInfo, then validates or mints the conversation handle, then falls back to the carried sessionId. prepareToolList takes headers to leave conversation_id out for a handle-free client. prepareToolResult adds a newly minted handle to compatible results. If no result channel can deliver a new handle, capture keeps the derived session id but omits $mcp_conversation_id.
  • distinct_id (posthog-events.ts): identifyActorGivenId || sessionId || "anonymous". Pre-identify events are session-scoped; once options.identify() returns a user, subsequent events attribute to that user. The SDK does not merge the earlier session-scoped events into that person.
  • Person processing: events for sessions with no resolved identity carry the process_person_profile: false option, so anonymous MCP sessions don't each mint a throwaway person profile (the distinct id is just the session id). As a per-event option it beats a registered or context process_person_profile option on the client. Once an identity is resolved, the SDK sets no default, so $set lands on a real person.
  • The user's choice wins: an explicit process_person_profile in eventOptions (per call or from the callback), or one beforeSend sets, replaces the anonymous default. The default applies only when the user chose no value. This package deliberately lets the host opt anonymous sessions into person processing.
  • No $identify event (handleIdentify, src/extensions/internal.ts): options.identify() is resolved on every request and merged into an IdentityCache (bounded LRU, max 1000 entries) keyed by session id and per-server. The result stamps distinct_id/$set onto each event. The SDK publishes no standalone $identify: it would carry no $anon_distinct_id, so ingestion would merge no person.
  • Groups ($groups): if options.identify() returns a groups?: Record<string, string> field (groupType → groupKey), it is stamped onto every event for that session as $groups. Callers never hand-write the $groups dollar-key themselves — they just return groups from identify.
  • Person properties ($set): the properties object returned from options.identify() is written verbatim to $set (same as posthog-node's identify({ distinctId, properties })). Put name/email/etc in there.

5. Event catalog

All events are emitted by buildPostHogCaptureEvents. The main event name is computed by looking up the internal MCPAnalyticsEventType in BUILT_IN_EVENT_NAME_BY_TYPE.

PostHog event When Notable extras
$mcp_tool_call Every tool invocation $mcp_tool_name, $mcp_tool_description, $mcp_tool_category, $mcp_parameters, $mcp_response, $mcp_duration_ms, $mcp_is_error, optionally $mcp_intent / $mcp_intent_source, $mcp_llm_model / $mcp_llm_model_source
$mcp_unknown_tool A tools/call names a tool the server never registered, and the call is rejected Not a tool call, so no $mcp_tool_call or $exception. $mcp_tool_name (the requested name, sanitized as free text). A disabled tool, a server whose own dispatcher bypasses the MCP SDK's tool registry (such as @rekog/mcp-nest), or a low-level server with no resolveOriginalTool and a dispatcher, records a failed $mcp_tool_call instead. A call naming no tool emits nothing
$mcp_tools_list Client lists tools $mcp_listed_tool_names (array of tool names advertised); useful for "did this client discover us?" and "which advertised tools never get called?". With instrument(), $mcp_response keeps only the envelope (nextCursor, ttlMs, …), never the tool descriptors
$mcp_initialize Client/server handshake $mcp_client_name, $mcp_client_version, $mcp_server_name, $mcp_server_version, $mcp_protocol_version (negotiated MCP spec version — for tracking spec-revision adoption)
$mcp_missing_capability Agent calls the get_more_tools virtual tool A capability gap, not a tool invocation. The context arg is captured as $mcp_intent with $mcp_intent_source = "context_parameter"
$mcp_feedback Agent calls the send_feedback virtual tool A feedback report, not a tool invocation. $mcp_feedback_type (missing_capability | issue | praise | other), $mcp_feedback_summary and the other $mcp_feedback_* fields, declared extras as $mcp_feedback_<key>, and the summary/details as $mcp_intent
$mcp_resources_list Client lists resources or resource templates $mcp_parameters (request.method separates resources/list from resources/templates/list), $mcp_response (the listing metadata — names, uris, uri templates, mime types, next cursor), $mcp_duration_ms, $mcp_is_error
$mcp_resource_read Resource fetched $mcp_resource_name, $mcp_parameters, $mcp_duration_ms, $mcp_is_error; resource bodies are never captured
$mcp_prompts_list Client lists prompts —
$mcp_prompt_get Prompt fetched $mcp_resource_name (= prompt name)
(your event name) analytics.capture({ event, properties }) A customer event sent under the verbatim event name (not $-prefixed). Carries $session_id, distinct_id, server/client metadata, plus whatever you pass in properties
$exception Sibling to any errored event (unless enableExceptionAutocapture: false) $exception_list, $exception_level (standard @posthog/core error-tracking shape)

6. Property catalog

All wire keys live in PostHogMCPAnalyticsProperty (src/extensions/constants.ts).

Core properties (present on most $mcp_* events)

Constant Wire key Type Source
SessionId $session_id string event.sessionId (ses_…)
Source $mcp_source string Hardcoded "posthog_mcp_analytics"
ResourceName $mcp_resource_name string Tool / resource / prompt name
ToolName $mcp_tool_name string Same as ResourceName, but only on $mcp_tool_call
ToolDescription $mcp_tool_description string Tool's current description at call time. Cached from tools/list and (for McpServer) seeded from _registeredTools. Only on $mcp_tool_call and the paired $exception event
ToolCategory $mcp_tool_category string Product category declared on the tool's _meta.category. Cached from tools/list and (for McpServer) seeded from _registeredTools; captureToolCall takes it as category. Only on $mcp_tool_call and the paired $exception event
ListedToolNames $mcp_listed_tool_names string[] Names of tools advertised in a tools/list response. Only on $mcp_tools_list events.
DurationMs $mcp_duration_ms number (ms) Wall-clock duration
IsError $mcp_is_error boolean Set from tool result or thrown exception
ServerName $mcp_server_name string server._serverInfo.name
ServerVersion $mcp_server_version string server._serverInfo.version
ClientName $mcp_client_name string server.getClientVersion().name
ClientVersion $mcp_client_version string server.getClientVersion().version
ClientUserAgent $mcp_client_user_agent string Raw user-agent request header, read off extra.requestInfo.headers per request (HTTP transports only — absent on stdio/in-memory). The only signal that separates a vendor's surfaces: Anthropic reports clientInfo.name = "claude-code" from its CLI, Agent SDK, VS Code extension and desktop app alike, and only the User-Agent parenthetical (claude-code/2.1.0 (cli) vs (sdk-ts) vs (claude-vscode)) tells them apart. Captured verbatim and capped at 256 chars — the SDK classifies nothing, product labels are resolved at query time. PostHogMCP callers pass it as clientUserAgent
VendorClient $mcp_vendor_client string Raw x-anthropic-client request header (HTTP transports only) — a second, independent surface signal alongside $mcp_client_user_agent, also captured verbatim. PostHogMCP callers pass it as vendorClient
ProtocolVersion $mcp_protocol_version string Negotiated MCP spec version. Learned at initialize (off the response), then stamped on every event for the session — persisted in sessionInfo and recovered cross-pod from the session token (re-minted to carry the negotiated version). Tracks spec-revision adoption and lets you slice event metrics by spec version
Intent $mcp_intent string context argument when present, else intentFallback() return
IntentSource $mcp_intent_source "context_parameter" | "inferred" Where the intent came from
ConversationId $mcp_conversation_id string Optional; set when enableConversationId: true and the SDK owns the tool's injected conversation_id parameter
LlmModel $mcp_llm_model string Optional; set when captureModel is enabled and a recognized client metadata source or the SDK-owned llm_model parameter provides a value. Client metadata takes precedence. Both sources are unverified, so use this for degradation analytics, never for billing or security. Blank and "unknown" values are dropped
LlmModelSource $mcp_llm_model_source "client_metadata" | "self_reported" How the model id was obtained. client_metadata identifies a recognized vendor metadata field; self_reported identifies the injected argument fallback
Parameters $mcp_parameters object Sanitized MCP request payload (see §3)
Response $mcp_response object Sanitized tool result

Person & group properties

Key On Source
$set.<anything> events with a resolved identity Keys of UserIdentity.properties (e.g. name, email), written to $set verbatim
$groups every event for the session UserIdentity.groups ({ groupType: groupKey })

Callers never hand-write the $groups key.

Event options

Option On Source
process_person_profile events with no resolved identity false
any key every event, $exception included eventOptions
  • process_person_profile is false so anonymous sessions don't mint a person profile each, unless the user chose a value (see §4).
  • Any key comes from eventOptions, from the callback on auto-captured events or per call on the others.

Exception properties ($exception event)

$exception_list + $exception_level (the standard @posthog/core error-tracking shape — each exception carries type, value, mechanism, and a parsed stacktrace.frames), plus $session_id, $mcp_resource_name, $mcp_tool_name and $mcp_tool_description (tool calls only), $mcp_server_*, $mcp_client_*, $mcp_vendor_client.

Customer-defined properties

The eventProperties callback returns key/value pairs that are spread flat at the top level of the PostHog event properties, alongside the $mcp_* keys. They can therefore override built-in $mcp_* keys — intentional, so customers can backfill missing context. Values must be JSON-serializable; the SDK does not validate keys or values beyond truncation.

Customer-defined options

eventOptions sets posthog-node per-event options, such as process_person_profile. The instrument() path takes a per-request callback in MCPAnalyticsOptions. analytics.capture() and every PostHogMCP capture method take a per-call eventOptions field. The callback runs only on the request-handling paths, after any options the event already carries, which win. The options reach every payload of the event, including the $exception sibling. PostHogMCP.capture() is posthog-node's own capture(), so it takes posthog-node's options field instead.

7. Customer extension points (MCPAnalyticsOptions, src/types.ts)

The posthog-node client is not an option — it is the required positional 2nd argument to instrument(server, posthog, options?). You construct and own it (host, project token, batching, lifecycle all configured there). The options below are the optional 3rd argument.

Option Default Use case
logger no-op STDIO-safe log sink for SDK-internal warnings. Receives single string messages.
enableExceptionAutocapture true When false, a failed tool call does not emit the sibling $exception event.
enableConversationId true (ADR-0013) Inject conversation_id into eligible tools that don't already declare it and stamp $mcp_conversation_id on their events.
reportMissing false Register the get_more_tools virtual tool.
collectFeedback false (object form: { toolName, description, extraProperties, extraRequired, onFeedback }) Register the send_feedback virtual tool — an honest general feedback channel with missing capabilities as the priority category. Covers what reportMissing covers, so new integrations should enable only one of the two.
context true (object form: { description }) Inject required context arg into every tool schema.
captureModel true (object form: { description }) Capture a model id from recognized client metadata, with an injected llm_model argument as fallback. Self-report reads fail open where ownership is unresolved and strips fail closed (ADR-0011); client metadata does not depend on tool ownership. Default per ADR-0013.
intentFallback — Consumer-supplied callback returning a $mcp_intent string when the client didn't pass a context argument. SDK does no inference.
identify — Per-request callback returning { distinctId, properties?, groups? } | null — posthog-node's identify shape. properties → $set, groups → $groups.
beforeSend — (event) => event | null | undefined (sync or async), matching posthog-node. Runs on each fully-built payload right before posthog.capture() — once per emitted event, including the $exception sibling. Return nullish (or throw) to drop that event.
eventProperties — Freeform JSON, spread flat.
eventOptions none Per-request callback returning posthog-node per-event options

eventOptions returns options for every auto-captured event, $exception included. beforeSend sees them as the payload's options. An explicit process_person_profile wins over the anonymous default.

8. Useful queries

All queries assume event is the PostHog event name column. Property names use the literal wire keys (with $).

Top tools per server (last 7d)

 1SELECT
 2  properties.$mcp_server_name AS server,
 3  properties.$mcp_tool_name   AS tool,
 4  count() AS calls
 5FROM events
 6WHERE event = '$mcp_tool_call' AND timestamp > now() - INTERVAL 7 DAY
 7GROUP BY server, tool
 8ORDER BY calls DESC
 9LIMIT 50

Error rate per tool

 1SELECT
 2  properties.$mcp_tool_name AS tool,
 3  countIf(properties.$mcp_is_error)        AS errors,
 4  count()                                  AS total,
 5  countIf(properties.$mcp_is_error) / count() AS error_rate
 6FROM events
 7WHERE event = '$mcp_tool_call' AND timestamp > now() - INTERVAL 7 DAY
 8GROUP BY tool
 9ORDER BY total DESC

P95 latency per tool

 1SELECT
 2  properties.$mcp_tool_name AS tool,
 3  quantile(0.95)(toFloat(properties.$mcp_duration_ms)) AS p95_ms
 4FROM events
 5WHERE event = '$mcp_tool_call' AND timestamp > now() - INTERVAL 7 DAY
 6GROUP BY tool
 7ORDER BY p95_ms DESC

Intent samples split by source

 1SELECT
 2  properties.$mcp_intent_source AS source,
 3  properties.$mcp_tool_name     AS tool,
 4  any(properties.$mcp_intent)   AS sample_intent,
 5  count()                       AS calls
 6FROM events
 7WHERE event = '$mcp_tool_call' AND timestamp > now() - INTERVAL 24 HOUR
 8GROUP BY source, tool
 9ORDER BY calls DESC

Advertised tools that never get called

 1WITH listed AS (
 2  SELECT DISTINCT arrayJoin(properties.$mcp_listed_tool_names) AS tool_name
 3  FROM events
 4  WHERE event = '$mcp_tools_list'
 5    AND timestamp > now() - INTERVAL 30 DAY
 6),
 7called AS (
 8  SELECT DISTINCT properties.$mcp_tool_name AS tool_name
 9  FROM events
10  WHERE event = '$mcp_tool_call'
11    AND timestamp > now() - INTERVAL 30 DAY
12)
13SELECT tool_name AS zombie_tool
14FROM listed
15WHERE tool_name NOT IN (SELECT tool_name FROM called)
16ORDER BY tool_name

Active sessions per client

 1SELECT
 2  properties.$mcp_client_name AS client,
 3  uniq(properties.$session_id) AS sessions
 4FROM events
 5WHERE event IN ('$mcp_initialize', '$mcp_tool_call')
 6  AND timestamp > now() - INTERVAL 7 DAY
 7GROUP BY client
 8ORDER BY sessions DESC

9. Migration from the previous standalone @posthog/mcp (0.0.x)

The previous version of this SDK lived in a separate repo and depended on posthog-node. This first monorepo release (0.1.0) is a clean break — there were no production users, so the contract is intentionally rebuilt rather than maintained.

Breaking changes

Concern Old (standalone 0.0.x) New (monorepo 0.1.0)
PostHog client Required posthog-node runtime dep, or BYO via posthogClient BYO posthog-node client via the posthog option (matches @posthog/ai)
posthogClient option Accepted any duck-typed client Renamed to posthog; expects a posthog-node PostHog instance
posthogOptions option Forwarded to posthog-node Removed — configure the posthog-node client you pass in directly
eventTags callback Constrained string map; spread flat on events Removed — fold all metadata into eventProperties
~/posthog-mcp-analytics.log SDK wrote to the user's home directory Removed; pass logger?: (msg: string) => void if you want to capture internal logs
PostHog event names Plain (mcp_tool_call, mcp_custom, posthog_identify, …) SDK events $-prefixed ($mcp_tool_call, …); capture() events keep your verbatim name
POSTHOG_MCP_ANALYTICS_HOST env var Read at instrument() time Removed; pass host directly
Session id source uuidv4 via node:crypto uuidv7 from @posthog/core

Insight migration checklist

  1. event = 'mcp_tool_call' → event = '$mcp_tool_call' (same for every other mcp_* event).
  2. Drop filters on posthog_identify. The SDK no longer sends an identify event; person properties arrive as $set on every event.
  3. Replace properties.$mcp_source = 'posthog_mcp_analytics' filters with event LIKE '$mcp_%' if you want a broader funnel.
  4. Drop any filters on customer tags — fold them into eventProperties.

10. Intent resolution in depth

Intent is the most semantically-loaded property the SDK emits. Lives in src/extensions/intent.ts.

Two sources, one property

$mcp_intent can come from either:

  1. The context argument the LLM/client passed — the SDK-injected JSON-Schema parameter. Tagged $mcp_intent_source = "context_parameter".
  2. The intentFallback callback you supplied — runs only when no context argument is present. Tagged $mcp_intent_source = "inferred".

An explicit SDK-owned context always wins. If the SDK injected context and its value is non-empty, intentFallback is not invoked. A tool's own declared context is not consumed as intent, so the fallback may still run.

Why the fallback exists

The context parameter is advertised as required in JSON Schema but not enforced at the SDK validation layer — a tool call with arguments: {} succeeds and lands in PostHog with $mcp_intent empty (ADR-0002 records why enforcement isn't possible). For clients that ignore the JSON Schema hint — raw cURL, in-house agents, schema-blind crawlers — intentFallback is the only way to keep intent coverage non-zero. For a tightly-controlled internal MCP server with a single well-behaved client, the fallback is dead code.

What the SDK does NOT do

intentFallback is a slot, not a strategy. The SDK:

  • Awaits whatever async function you pass.
  • Trims and null-guards the result.
  • Tags it source: "inferred".
  • Swallows + logs any thrown exception.

The SDK does not: call an LLM, inspect tool arguments, build heuristics, or cache results across calls. If you want any of that, your callback implements it.

  1. Deterministic, per-tool (cheapest, sync, runs on every uncontextualized call):

     1intentFallback: (request) => {
     2  const tool = request.params?.name
     3  const args = request.params?.arguments ?? {}
     4  if (tool === 'search_events') return `Searching events for "${args.query}"`
     5  return tool ? `Invoking ${tool}` : null
     6}
    
  2. Transport metadata (when extra carries user-agent or session info worth surfacing):

     1intentFallback: (request, extra) => {
     2  const ua = extra?.requestInfo?.headers?.['user-agent']
     3  return `${ua ?? 'unknown client'} invoked ${request.params?.name}`
     4}
    
  3. LLM-derived (async, expensive — push back unless the value is high). Sits on the hot path of every uncontextualized tool call.

Known sharp edges

  • reportMissing and collectFeedback determine ownership from the server's raw tools/list handler without relying on a previous client request, so stateless calls can reach the virtual tools across instances. If a real tool already advertises the configured name, the SDK warns, does not inject a duplicate descriptor, and delegates calls to the real handler. If the raw listing is unavailable or fails, calls fail open to the server handler rather than risk intercepting a real tool.
  • A low-level Server learns reserved-argument ownership while serving tools/list, so an instance that never served one strips nothing (ADR-0011). resolveOriginalTool lets the host return the tool's input schema as its listing advertises it on tools/call; ownership follows the same rule as a served listing, a listing already served on the instance wins, and $mcp_input_keys follow the returned schema. A thrown error or undefined falls back to unresolved ownership.
  • The MCP SDK advertises non-object Zod schemas — including refined objects such as z.object({ context, value }).refine(...) — as empty object schemas. Reserved-argument ownership follows that advertised schema on every path, including a Zod schema returned by resolveOriginalTool, so a context declared inside one of these schemas is treated as analytics-owned and stripped before the tool callback. A low-level host that advertises the declared fields returns its listed JSON Schema from the resolver instead.
  • The get_more_tools virtual tool emits its own $mcp_missing_capability event (a capability gap), not a $mcp_tool_call. Its context arg is recorded as $mcp_intent with $mcp_intent_source = "context_parameter". It's defensible — the LLM did type a context string — but worth knowing if you segment by source.
  • The send_feedback virtual tool likewise emits its own $mcp_feedback event, not a $mcp_tool_call. All feedback types land in that one event; $mcp_feedback_type = "missing_capability" is a property filter, not a separate event, so dashboards reading $mcp_missing_capability see only get_more_tools reports (ADR-0012).
  • $mcp_intent_source is currently only present when an intent was captured. Events with neither a context arg nor a fallback result have no $mcp_intent and no $mcp_intent_source. Dashboards filtering on $mcp_intent_source = "inferred" won't see them — that's the desired behavior; just don't expect a synthetic "none" value.

File map quick reference

Concern File
Public API entry src/index.ts
Public types & options src/types.ts
Property/event constants src/extensions/constants.ts
Event serialization to PostHog src/extensions/posthog-events.ts
Internal event types src/extensions/event-types.ts
McpEventSink + processMcpEvent pipeline src/extensions/sink.ts
Per-server captureEvent helper src/extensions/capture.ts
Shared tool-call lifecycle / list / initialize src/extensions/instrumentation.ts
High-level McpServer wrapping (thin adapter over instrumentation) src/extensions/instrument-highlevel.ts
Low-level Server wrapping (thin adapter over instrumentation) src/extensions/instrument-lowlevel.ts
Intent resolution (context arg + fallback) src/extensions/intent.ts
Identity cache + identify dispatch src/extensions/internal.ts
Session id derivation & timeout src/extensions/session.ts, src/extensions/ids.ts
Self-encoded session tokens (Mcp-Session-Id) src/extensions/session-token.ts
Per-request protocol revision + mint gating (ADR-0008/0009) src/extensions/session.ts, src/extensions/client-identity.ts
conversation_id injection + minting src/extensions/conversation-id.ts
_mcp_instructions output-schema mirror src/extensions/output-instructions.ts
Client identity from request _meta (2026-07-28) src/extensions/client-identity.ts
Injected-argument ownership tracking src/extensions/analytics-parameters.ts
get_more_tools virtual tool src/extensions/tools.ts
send_feedback virtual tool src/extensions/feedback.ts
Auto-redaction & binary stubbing src/extensions/sanitization.ts, src/extensions/mcp-payloads.ts
Size / depth / breadth caps src/extensions/truncation.ts
context JSON-Schema injection src/extensions/context-parameters.ts
STDIO-safe logger sink src/extensions/logger.ts
Exception capture & stack-trace parsing src/extensions/exceptions.ts
MCP SDK version compat shims src/extensions/compatibility.ts, src/extensions/mcp-sdk-compat.ts
Structural capability probes (both SDK majors) src/extensions/detect.ts
MCP wire shapes, declared not imported (ADR-0007) src/types.ts
Request headers on either SDK major (getRequestHeaders) src/extensions/request-headers.ts