@posthog/mcp 0.10.9 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +39 -0
  2. package/dist/extensions/capture.d.ts.map +1 -1
  3. package/dist/extensions/capture.js +2 -0
  4. package/dist/extensions/capture.mjs +2 -0
  5. package/dist/extensions/compatibility.d.ts.map +1 -1
  6. package/dist/extensions/compatibility.js +14 -18
  7. package/dist/extensions/compatibility.mjs +10 -14
  8. package/dist/extensions/constants.d.ts +2 -0
  9. package/dist/extensions/constants.d.ts.map +1 -1
  10. package/dist/extensions/constants.js +3 -1
  11. package/dist/extensions/constants.mjs +3 -1
  12. package/dist/extensions/context-parameters.d.ts.map +1 -1
  13. package/dist/extensions/conversation-id.d.ts +2 -13
  14. package/dist/extensions/conversation-id.d.ts.map +1 -1
  15. package/dist/extensions/detect.d.ts +45 -0
  16. package/dist/extensions/detect.d.ts.map +1 -0
  17. package/dist/extensions/detect.js +90 -0
  18. package/dist/extensions/detect.mjs +35 -0
  19. package/dist/extensions/headers.d.ts +33 -0
  20. package/dist/extensions/headers.d.ts.map +1 -0
  21. package/dist/extensions/headers.js +54 -0
  22. package/dist/extensions/headers.mjs +17 -0
  23. package/dist/extensions/instrument-highlevel.d.ts.map +1 -1
  24. package/dist/extensions/instrument-lowlevel.d.ts.map +1 -1
  25. package/dist/extensions/instrumentation.d.ts +7 -0
  26. package/dist/extensions/instrumentation.d.ts.map +1 -1
  27. package/dist/extensions/instrumentation.js +7 -2
  28. package/dist/extensions/instrumentation.mjs +7 -2
  29. package/dist/extensions/internal.d.ts.map +1 -1
  30. package/dist/extensions/internal.js +2 -0
  31. package/dist/extensions/internal.mjs +2 -0
  32. package/dist/extensions/output-instructions.d.ts +6 -8
  33. package/dist/extensions/output-instructions.d.ts.map +1 -1
  34. package/dist/extensions/posthog-events.js +4 -0
  35. package/dist/extensions/posthog-events.mjs +4 -0
  36. package/dist/extensions/posthog-mcp.d.ts.map +1 -1
  37. package/dist/extensions/posthog-mcp.js +3 -0
  38. package/dist/extensions/posthog-mcp.mjs +3 -0
  39. package/dist/extensions/request-headers.d.ts +36 -0
  40. package/dist/extensions/request-headers.d.ts.map +1 -0
  41. package/dist/extensions/request-headers.js +62 -0
  42. package/dist/extensions/request-headers.mjs +28 -0
  43. package/dist/extensions/session-token.d.ts.map +1 -1
  44. package/dist/extensions/session-token.js +5 -14
  45. package/dist/extensions/session-token.mjs +2 -11
  46. package/dist/extensions/session.d.ts +4 -3
  47. package/dist/extensions/session.d.ts.map +1 -1
  48. package/dist/extensions/session.js +2 -1
  49. package/dist/extensions/session.mjs +2 -1
  50. package/dist/extensions/sink.d.ts +4 -6
  51. package/dist/extensions/sink.d.ts.map +1 -1
  52. package/dist/extensions/tools.d.ts.map +1 -1
  53. package/dist/extensions/transport-identity.d.ts +64 -0
  54. package/dist/extensions/transport-identity.d.ts.map +1 -0
  55. package/dist/extensions/transport-identity.js +64 -0
  56. package/dist/extensions/transport-identity.mjs +21 -0
  57. package/dist/extensions/truncation.d.ts.map +1 -1
  58. package/dist/extensions/truncation.js +2 -0
  59. package/dist/extensions/truncation.mjs +2 -0
  60. package/dist/index.d.ts +2 -1
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +11 -7
  63. package/dist/index.mjs +2 -1
  64. package/dist/types.d.ts +52 -0
  65. package/dist/types.d.ts.map +1 -1
  66. package/dist/version.d.ts +1 -1
  67. package/dist/version.js +1 -1
  68. package/dist/version.mjs +1 -1
  69. package/package.json +2 -2
  70. package/src/extensions/capture.ts +6 -0
  71. package/src/extensions/compatibility.ts +25 -33
  72. package/src/extensions/constants.ts +2 -0
  73. package/src/extensions/context-parameters.ts +3 -11
  74. package/src/extensions/conversation-id.ts +5 -17
  75. package/src/extensions/detect.ts +78 -0
  76. package/src/extensions/headers.ts +52 -0
  77. package/src/extensions/instrument-highlevel.ts +0 -1
  78. package/src/extensions/instrument-lowlevel.ts +0 -1
  79. package/src/extensions/instrumentation.ts +32 -39
  80. package/src/extensions/internal.ts +6 -5
  81. package/src/extensions/output-instructions.ts +6 -8
  82. package/src/extensions/posthog-events.ts +14 -0
  83. package/src/extensions/posthog-mcp.ts +7 -5
  84. package/src/extensions/request-headers.ts +76 -0
  85. package/src/extensions/session-token.ts +3 -15
  86. package/src/extensions/session.ts +23 -36
  87. package/src/extensions/sink.ts +4 -6
  88. package/src/extensions/tools.ts +3 -6
  89. package/src/extensions/transport-identity.ts +100 -0
  90. package/src/extensions/truncation.ts +4 -0
  91. package/src/index.ts +4 -0
  92. package/src/types.ts +51 -0
  93. package/src/version.ts +1 -1
@@ -41,7 +41,6 @@ export function addContextParameterToTool<TTool extends ContextInjectableTool>(
41
41
  contextDescriptionOverride?: string,
42
42
  logger: LoggerFn = log
43
43
  ): TTool {
44
- // Create a shallow copy of the tool to avoid modifying the original
45
44
  const modifiedTool = { ...tool }
46
45
  const toolName = tool.name || 'unknown'
47
46
  const schema = modifiedTool.inputSchema as AnalyticsInjectableJsonSchema | undefined
@@ -55,10 +54,6 @@ export function addContextParameterToTool<TTool extends ContextInjectableTool>(
55
54
  return modifiedTool
56
55
  }
57
56
 
58
- // Note: If additionalProperties is false, we'll need to remove that constraint
59
- // when adding context, otherwise the schema would be invalid. We handle this
60
- // after the deep copy below.
61
-
62
57
  if (!modifiedTool.inputSchema) {
63
58
  modifiedTool.inputSchema = {
64
59
  type: 'object',
@@ -69,29 +64,26 @@ export function addContextParameterToTool<TTool extends ContextInjectableTool>(
69
64
 
70
65
  const contextDescription = contextDescriptionOverride || DEFAULT_CONTEXT_PARAMETER_DESCRIPTION
71
66
 
72
- // Deep copy the inputSchema to avoid mutations
67
+ // Deep copy: the server may reuse or freeze the schema object it handed us.
73
68
  modifiedTool.inputSchema = JSON.parse(JSON.stringify(modifiedTool.inputSchema)) as AnalyticsInjectableJsonSchema
74
69
 
75
70
  const inputSchema = modifiedTool.inputSchema as AnalyticsInjectableJsonSchema
76
71
 
77
- // Ensure properties object exists
78
72
  if (!inputSchema.properties) {
79
73
  inputSchema.properties = {}
80
74
  }
81
75
 
82
- // Handle additionalProperties: false - must remove this constraint since we're adding context
83
- // The MCP SDK adds this constraint when converting Zod schemas to JSON Schema
76
+ // The MCP SDK emits `additionalProperties: false` when converting Zod schemas;
77
+ // left in place it would make the injected `context` key invalid.
84
78
  if (inputSchema.additionalProperties === false) {
85
79
  inputSchema.additionalProperties = undefined
86
80
  }
87
81
 
88
- // Add context property
89
82
  inputSchema.properties.context = {
90
83
  type: 'string',
91
84
  description: contextDescription,
92
85
  }
93
86
 
94
- // Add context to required array
95
87
  if (Array.isArray(inputSchema.required)) {
96
88
  if (!inputSchema.required.includes('context')) {
97
89
  inputSchema.required.push('context')
@@ -102,20 +102,9 @@ export type ConversationIdResolution =
102
102
  * derivation is deterministic so that two pods agree — which also means two
103
103
  * *callers* sending the same string land in the same session. The strings agents
104
104
  * invent are not random (`conv-1`, `1`, `session`), so trusting them verbatim
105
- * would silently merge unrelated conversations, potentially across users.
106
- *
107
- * A compliant agent echoes the uuidv7 we minted and is unaffected. Anything else
108
- * is treated exactly as if the handle were absent: mint, and prompt back. Shape
105
+ * would silently merge unrelated conversations, potentially across users. Shape
109
106
  * rather than a registry of issued ids, because a per-request server has no
110
- * memory of what it minted.
111
- *
112
- * This narrows the problem, it does not prove provenance: a caller supplying a
113
- * well-formed uuidv7 is trusted, so two that pick the *same* one still merge. That
114
- * residue is far smaller than the case it replaces — an agent ignoring the
115
- * parameter description reaches for `conv-1` or `1`, not a conforming uuidv7 — and
116
- * closing it needs a signed handle, i.e. a secret shared by every pod. Worth doing
117
- * if this ever anchors something security-bearing; `$session_id` is an analytics
118
- * grouping key, so it does not today.
107
+ * memory of what it minted. Residual risk and why it's accepted: ADR-0004.
119
108
  */
120
109
  export function resolveConversationId(enabled: boolean, args: unknown): ConversationIdResolution {
121
110
  if (!enabled) {
@@ -123,10 +112,9 @@ export function resolveConversationId(enabled: boolean, args: unknown): Conversa
123
112
  }
124
113
  const supplied = extractConversationId(args)
125
114
  if (supplied && MINTED_CONVERSATION_ID.test(supplied)) {
126
- // Lowercased because the shape test is case-insensitive but the hash behind
127
- // `$session_id` is not. Some hosts normalise uuids to uppercase, and an
128
- // uppercased echo of our own handle would otherwise clear the gate and then
129
- // land in a different session than the call that minted it.
115
+ // Lowercased: the shape test is case-insensitive but the hash behind
116
+ // `$session_id` is not, so an uppercased echo (some hosts normalise uuids)
117
+ // would land in a different session than the call that minted it.
130
118
  return { minted: false, conversationId: supplied.toLowerCase() }
131
119
  }
132
120
  return { minted: true, conversationId: uuidv7() }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Structural feature probes.
3
+ *
4
+ * Every question about the shape of a server object is answered here, by
5
+ * duck-typing the object in front of us — never by reading a package version or
6
+ * a protocol constant. Two reasons this is a rule and not a preference:
7
+ *
8
+ * - The two SDK majors expose the same capability under different names (v1's
9
+ * `.tool()` vs v2's `.registerTool()`), so "which SDK is installed" answers a
10
+ * different question than "can this object register a tool".
11
+ * - A single v2 server serves both protocol eras, request by request, so no
12
+ * module-level constant describes it. v2's exported `LATEST_PROTOCOL_VERSION`
13
+ * is `2025-11-25`.
14
+ *
15
+ * Nothing here imports `@modelcontextprotocol/*`; that boundary is pinned by
16
+ * `sdk-import-boundary.test.ts`.
17
+ */
18
+
19
+ type UnknownRecord = Record<string, unknown>
20
+
21
+ function asRecord(value: unknown): UnknownRecord | undefined {
22
+ return value && typeof value === 'object' ? (value as UnknownRecord) : undefined
23
+ }
24
+
25
+ function hasMethod(value: unknown, key: string): boolean {
26
+ return typeof asRecord(value)?.[key] === 'function'
27
+ }
28
+
29
+ /** A high-level `McpServer` wrapper: it holds the low-level server on `.server`. */
30
+ export function hasNestedLowLevelServer(server: unknown): server is UnknownRecord & { server: UnknownRecord } {
31
+ const record = asRecord(server)
32
+ return !!record && 'server' in record && !!asRecord(record.server)
33
+ }
34
+
35
+ /** No `.server` property, so the object is itself the low-level `Server`. */
36
+ export function isBareServerShape(server: unknown): boolean {
37
+ const record = asRecord(server)
38
+ return !!record && !('server' in record)
39
+ }
40
+
41
+ /** The high-level registry we read tool metadata from and wrap callbacks in. */
42
+ export function hasToolRegistry(server: unknown): boolean {
43
+ return !!asRecord(asRecord(server)?._registeredTools)
44
+ }
45
+
46
+ /**
47
+ * The object can register a tool.
48
+ *
49
+ * v1 offers both `tool()` and `registerTool()`; v2 dropped the deprecated
50
+ * `tool()` and keeps only `registerTool()`. Requiring `tool()` specifically is
51
+ * what made `instrument()` reject every v2 high-level server — and, because
52
+ * `instrument()` swallows compatibility errors, reject it silently.
53
+ */
54
+ export function canRegisterTools(server: unknown): boolean {
55
+ return hasMethod(server, 'registerTool') || hasMethod(server, 'tool')
56
+ }
57
+
58
+ /** Handler registration, which we patch to wrap late registrations. */
59
+ export function canSetRequestHandler(server: unknown): boolean {
60
+ return hasMethod(server, 'setRequestHandler')
61
+ }
62
+
63
+ /** The live handler map we read and write directly. A real `Map` on both majors. */
64
+ export function hasRequestHandlerMap(server: unknown): boolean {
65
+ const handlers = asRecord(server)?._requestHandlers
66
+ return handlers instanceof Map && typeof handlers.get === 'function'
67
+ }
68
+
69
+ /** `getClientVersion()` — still present on v2, and a link in B1's identity chain. */
70
+ export function hasClientVersionAccessor(server: unknown): boolean {
71
+ return hasMethod(server, 'getClientVersion')
72
+ }
73
+
74
+ /** `_serverInfo`, which names the server on every event. */
75
+ export function hasServerInfo(server: unknown): boolean {
76
+ const info = asRecord(asRecord(server)?._serverInfo)
77
+ return !!info && 'name' in info
78
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The single place this package reads an HTTP request header.
3
+ *
4
+ * The MCP SDK hands us `IsomorphicHeaders` — a plain
5
+ * `Record<string, string | string[] | undefined>`, not a `Headers` instance — so
6
+ * values come out by bracket access rather than `.get()`. MCP SDK v2 plans to
7
+ * pass a real `Headers` object instead; funnelling every read through here keeps
8
+ * that migration a one-function change instead of a hunt for bracket lookups.
9
+ */
10
+
11
+ /**
12
+ * Reads one header value out of an `IsomorphicHeaders` bag. `name` must be
13
+ * lower-cased: the HTTP transports build the bag with
14
+ * `Object.fromEntries(req.headers.entries())` and the Fetch spec lower-cases
15
+ * header names. A hand-rolled transport can still hand us mixed-case keys, so a
16
+ * case-insensitive scan backs up the direct lookup.
17
+ *
18
+ * Repeated headers arrive as an array — we take the first entry, since every
19
+ * header we read is single-valued by definition. Returns `undefined` for a
20
+ * missing, non-string, or blank value, and never throws: a malformed header from
21
+ * an untrusted client must not break the request it rode in on.
22
+ */
23
+ export function readHeaderValue(headers: unknown, name: string): string | undefined {
24
+ if (!headers || typeof headers !== 'object') {
25
+ return undefined
26
+ }
27
+ const record = headers as Record<string, unknown>
28
+ let value = record[name]
29
+ if (value === undefined) {
30
+ const key = Object.keys(record).find((k) => k.toLowerCase() === name)
31
+ value = key === undefined ? undefined : record[key]
32
+ }
33
+ return normalizeHeaderString(value)
34
+ }
35
+
36
+ /**
37
+ * Coerces one raw header value into a clean string, or `undefined`.
38
+ *
39
+ * Exported so the custom-dispatcher path can apply the same rules to values a host
40
+ * read off the request itself. Without it the two integration paths emit different
41
+ * properties for the *same* request: a whitespace-only header would survive as a junk
42
+ * value, and a repeated header would reach the wire as an array, because the
43
+ * downstream length cap passes non-strings through untouched.
44
+ */
45
+ export function normalizeHeaderString(value: unknown): string | undefined {
46
+ const first = Array.isArray(value) ? value[0] : value
47
+ if (typeof first !== 'string') {
48
+ return undefined
49
+ }
50
+ const trimmed = first.trim()
51
+ return trimmed.length > 0 ? trimmed : undefined
52
+ }
@@ -280,7 +280,6 @@ export function instrumentHighLevelServer(server: HighLevelMCPServerLike, logger
280
280
  const lowLevelServer = server.server
281
281
  const mcpAnalyticsData = getServerTrackingData(lowLevelServer)
282
282
 
283
- // Patch already existing handlers, and patch setRequestHandler to capture dynamically created handlers.
284
283
  const handlers: Record<string, HandlerPatch> = {
285
284
  initialize: (trackedServer, originalHandler, request, extra) =>
286
285
  handleInitializeRequest(trackedServer, originalHandler, request, extra, logger),
@@ -32,7 +32,6 @@ type MCPRequestExtra = Parameters<MCPRequestHandler>[1]
32
32
  */
33
33
  export function instrumentLowLevelServer(server: MCPServerLike, logger: LoggerFn): void {
34
34
  try {
35
- // Patch already existing handlers, and patch setRequestHandler to capture dynamically created handlers.
36
35
  const hadCallToolHandler = server._requestHandlers.has('tools/call')
37
36
  const traceToolCall: HandlerPatch = (server, originalHandler, request, extra) =>
38
37
  handleToolCallRequest(server, originalHandler, request, extra, logger)
@@ -24,6 +24,7 @@ import {
24
24
  resolveConversationId,
25
25
  } from './conversation-id'
26
26
  import { stampMetaClientInfo } from './client-identity'
27
+ import { stampTransportIdentity } from './transport-identity'
27
28
  import { addInstructionsToOutputSchemas, mirrorInstructionsIntoStructuredContent } from './output-instructions'
28
29
  import { captureEvent } from './capture'
29
30
  import { MCPAnalyticsEventType } from './event-types'
@@ -33,6 +34,7 @@ import { getServerTrackingData, handleIdentify, setServerTrackingData, withIdent
33
34
  import type { LoggerFn } from './logger'
34
35
  import { buildCapturedMcpParameters } from './mcp-payloads'
35
36
  import { readRequestHandlerMethod } from './mcp-sdk-compat'
37
+ import { getRequestHeaders } from './request-headers'
36
38
  import { getSessionId, getSessionInfo, newSessionId } from './session'
37
39
  import { encodeSessionId, readMcpSessionHeader, writeSessionIdToTransport } from './session-token'
38
40
  import { getReportMissingToolDescriptor, resolveMissingCapabilityToolName } from './tools'
@@ -157,22 +159,13 @@ function getActiveAnalyticsParameterOwnership(
157
159
  return {
158
160
  context: !isMissingCapabilityTool && isContextEnabled(data.options.context) && ownership?.context === true,
159
161
  conversationId: data.options.enableConversationId === true && ownership?.conversationId === true,
160
- // Deliberately read off `listed`, never the override. This asks whether
161
- // `tools/list` actually declared `_mcp_instructions`, and only the advertised
162
- // JSON Schema can answer it — an override is built from the live registry,
163
- // which on the high-level path holds Zod.
164
- //
165
- // The cache is per-instance, so this is not merely "before the first
166
- // `tools/list`": an instance that never serves a listing never writes the
167
- // mirror at all. That is the per-request server pattern — `tools/list` lands
168
- // on one instance, `tools/call` on a cold one — where the handle falls back
169
- // to the `content` block and a structuredContent-only client misses it.
170
- //
171
- // Failing closed is deliberate. Writing a key the advertised schema did not
172
- // declare fails the *entire* tool result under `additionalProperties: false`,
173
- // so guessing costs the caller their result, while not guessing costs us one
174
- // delivery channel. The fix is a process-scoped ownership cache, so a listing
175
- // served by any instance answers for the rest — not a per-call guess.
162
+ // Deliberately read off `listed`, never the override: only the advertised
163
+ // JSON Schema can say whether `tools/list` declared `_mcp_instructions` (an
164
+ // override is built from the live registry, which holds Zod on the
165
+ // high-level path). An instance that never served a listing has no answer
166
+ // and fails closed — writing an undeclared key fails the customer's entire
167
+ // tool result under `additionalProperties: false`. See ADR-0004 for the
168
+ // per-request-instance gap this leaves and the planned fix.
176
169
  outputInstructions: data.options.enableConversationId === true && listed?.outputInstructions === true,
177
170
  }
178
171
  }
@@ -237,6 +230,9 @@ async function prepareToolCallEvent(
237
230
  // `_meta` on every request rather than at `initialize`; stamp them onto this
238
231
  // event now so concurrent requests can't cross-attribute it.
239
232
  stampMetaClientInfo(event, request)
233
+ // Which *surface* of the client made this call lives only in the request
234
+ // headers (HTTP transports); `clientInfo` can't tell a vendor's products apart.
235
+ stampTransportIdentity(event, extra)
240
236
 
241
237
  await applyResolvedMetadata(event, data, request, extra)
242
238
  setEventIntent(event, await resolveToolCallIntent(data, request, ownership.context, extra))
@@ -250,19 +246,14 @@ async function prepareToolCallEvent(
250
246
  }
251
247
 
252
248
  /**
253
- * Delivers the conversation session handle back to the agent, over both channels a tool
254
- * result has:
249
+ * Delivers the conversation session handle back to the agent over both channels
250
+ * a tool result has: mirrored into `structuredContent` on every response (for
251
+ * tools whose output schema declares the key), and as a `content` text block on
252
+ * the minting response only. Why two channels and why those cadences: ADR-0004.
255
253
  *
256
- * - `structuredContent`, on *every* response for a tool whose output schema we
257
- * declared the key on. Clients that read structured results never see the text
258
- * block, and re-sending it each time lets an agent that dropped the session handle read
259
- * it back.
260
- * - `content`, as a text block, only on the response that minted the session handle.
261
- * Repeating it every call would put a `[SERVER]:` line in front of the user on
262
- * every single tool result.
263
- *
264
- * If neither channel could carry a session handle we minted, the agent never received it,
265
- * so clear it off the event rather than showing analytics an id nobody has.
254
+ * If neither channel could carry a session handle we minted, the agent never
255
+ * received it, so clear it off the event rather than showing analytics an id
256
+ * nobody has.
266
257
  */
267
258
  function applyConversationInstructions(
268
259
  event: McpEvent | null,
@@ -364,13 +355,7 @@ export type HandlerPatch = (
364
355
  extra: CompatibleRequestHandlerExtra | undefined
365
356
  ) => Promise<unknown>
366
357
 
367
- /**
368
- * Applies the `patches` (keyed by method, e.g. `initialize`, `tools/list`) to the
369
- * handlers already registered, and patches `setRequestHandler` so matching
370
- * handlers registered later are patched too. The latter is what makes adapters
371
- * that register handlers post-construction work — e.g. `@rekog/mcp-nest` hands a
372
- * bare server to instrument() and only then registers its handlers.
373
- */
358
+ /** Pre-patch handlers, kept so `isToolAdvertised` can query the raw listing. */
374
359
  const originalRequestHandlers = new WeakMap<MCPServerLike, Map<string, MCPRequestHandler>>()
375
360
 
376
361
  function rememberOriginalRequestHandler(
@@ -417,8 +402,14 @@ export function registerFallbackRequestHandler(
417
402
  server._requestHandlers.set(handlerName, (request, extra) => patch(server, fallbackHandler, request, extra))
418
403
  }
419
404
 
405
+ /**
406
+ * Applies the `patches` (keyed by method, e.g. `initialize`, `tools/list`) to the
407
+ * handlers already registered, and patches `setRequestHandler` so matching
408
+ * handlers registered later are patched too. The latter is what makes adapters
409
+ * that register handlers post-construction work — e.g. `@rekog/mcp-nest` hands a
410
+ * bare server to instrument() and only then registers its handlers.
411
+ */
420
412
  export function patchRequestHandlers(server: MCPServerLike, patches: Record<string, HandlerPatch>): void {
421
- // Monkey patch existing handlers.
422
413
  for (const [handlerName, patch] of Object.entries(patches)) {
423
414
  const originalHandler = server._requestHandlers.get(handlerName)
424
415
  if (originalHandler) {
@@ -519,6 +510,7 @@ export async function handleListToolsRequest(
519
510
  timestamp: startTime,
520
511
  }
521
512
  stampMetaClientInfo(event, request)
513
+ stampTransportIdentity(event, extra)
522
514
 
523
515
  if (data) {
524
516
  await applyResolvedMetadata(event, data, request, extra)
@@ -683,7 +675,7 @@ export function cacheToolCategories(cache: Map<string, string>, tools: ListTools
683
675
  * client name/version is lost after `initialize`. Fix: mint the
684
676
  * `Mcp-Session-Id` response header as a token carrying both. Clients replay
685
677
  * the header on every request, so any pod recovers them with no server-side
686
- * store (decoded in `getSessionId`).
678
+ * store (decoded in `getSessionId`). See ADR-0003.
687
679
  *
688
680
  * The header only reaches the wire when response headers are built after the
689
681
  * handler runs — StreamableHTTP with `enableJsonResponse: true`. SSE flushes
@@ -697,8 +689,8 @@ function mintStatelessSessionOnInitialize(
697
689
  extra: CompatibleRequestHandlerExtra | undefined
698
690
  ): string | undefined {
699
691
  try {
700
- const headers = extra?.requestInfo?.headers
701
- if (!headers || typeof headers !== 'object') {
692
+ const headers = getRequestHeaders(extra)
693
+ if (!headers) {
702
694
  return undefined // not an HTTP transport (stdio/in-memory) — nothing to mint into
703
695
  }
704
696
  if (readMcpSessionHeader(headers)) {
@@ -830,6 +822,7 @@ export async function handleInitializeRequest(
830
822
  // negotiated protocol version below overrides any `_meta` one); picks up client
831
823
  // info if a client also sends it in `_meta`.
832
824
  stampMetaClientInfo(event, request)
825
+ stampTransportIdentity(event, extra)
833
826
 
834
827
  await applyResolvedMetadata(event, data, request, extra)
835
828
 
@@ -15,6 +15,7 @@ import type {
15
15
  import { MCPAnalyticsEventType } from './event-types'
16
16
  import { captureEvent } from './capture'
17
17
  import { stampMetaClientInfo } from './client-identity'
18
+ import { stampTransportIdentity } from './transport-identity'
18
19
 
19
20
  /**
20
21
  * Bounded LRU cache for session identities, capped at `maxSize` entries so a
@@ -153,6 +154,7 @@ export async function handleIdentify(
153
154
  timestamp: new Date(),
154
155
  }
155
156
  stampMetaClientInfo(identifyEvent, request)
157
+ stampTransportIdentity(identifyEvent, extra)
156
158
 
157
159
  try {
158
160
  const identityResult =
@@ -166,11 +168,10 @@ export async function handleIdentify(
166
168
  // was already announced by whichever pod handled `initialize`, so only the
167
169
  // handshake, or a genuine change a long-lived server observed, publishes
168
170
  // $identify. Every event still carries distinct_id/$set regardless, so
169
- // person properties are never lost. Known gap: if identity is null at
170
- // `initialize` but resolves later on a token session, that first $identify
171
- // is suppressed too, so any pre-identify (anonymous) events aren't aliased
172
- // onto the user. Inherent to statelessness (no pod knows a sibling already
173
- // announced); revisit with the stateless-by-default rework.
171
+ // person properties are never lost. Known accepted gap (ADR-0003): an
172
+ // identity resolving only after `initialize` on a token session gets no
173
+ // standalone $identify, so its pre-identify events aren't aliased onto
174
+ // the user.
174
175
  const changed = previousIdentity !== undefined && !areIdentitiesEqual(previousIdentity, mergedIdentity)
175
176
  const firstSeen = previousIdentity === undefined
176
177
  const announcedAtInitialize =
@@ -3,18 +3,16 @@ import { log } from './logger'
3
3
  import type { AnalyticsInjectableJsonSchema } from './analytics-parameters'
4
4
 
5
5
  /**
6
- * The `conversation_id` session handle reaches the agent as a text block appended to the
7
- * tool result. That block is invisible to any client that reads
8
- * `structuredContent` instead of `content` — which is what clients do whenever a
9
- * tool declares an `outputSchema`. Measured against Claude Code, correlation for
10
- * such tools drops to zero.
11
- *
12
- * The fix is to mirror the session handle into `structuredContent` as well, which this
13
- * module does in two halves that must stay in that order:
6
+ * Mirrors the `conversation_id` session handle into `structuredContent`, in two
7
+ * halves that must stay in that order:
14
8
  *
15
9
  * 1. declare `_mcp_instructions` on the tool's advertised `outputSchema`
16
10
  * 2. write it into the result's `structuredContent`
17
11
  *
12
+ * Needed because clients that read `structuredContent` — which they do whenever
13
+ * a tool declares an `outputSchema` — never see the `content` text block that
14
+ * carries the handle (ADR-0004).
15
+ *
18
16
  * The declaration is what makes the write safe. The MCP client ajv-validates
19
17
  * `structuredContent` against the schema from `tools/list`, and
20
18
  * `zod-to-json-schema` emits `additionalProperties: false` for a plain
@@ -151,6 +151,14 @@ function addCommonEventProperties(event: Event, properties: Record<string, unkno
151
151
  if (event.clientVersion) {
152
152
  properties[PostHogMCPAnalyticsProperty.ClientVersion] = event.clientVersion
153
153
  }
154
+ // HTTP transports only, and only for the request that carried the header —
155
+ // stdio and in-memory servers simply never set these.
156
+ if (event.clientUserAgent) {
157
+ properties[PostHogMCPAnalyticsProperty.ClientUserAgent] = event.clientUserAgent
158
+ }
159
+ if (event.vendorClient) {
160
+ properties[PostHogMCPAnalyticsProperty.VendorClient] = event.vendorClient
161
+ }
154
162
  // Present on every event once negotiated at `initialize` (carried via
155
163
  // sessionInfo / the session token). Absent only before the handshake.
156
164
  if (event.protocolVersion) {
@@ -242,6 +250,12 @@ function buildExceptionEvent(event: Event): PostHogCaptureEvent {
242
250
  if (event.clientVersion) {
243
251
  properties[PostHogMCPAnalyticsProperty.ClientVersion] = event.clientVersion
244
252
  }
253
+ if (event.clientUserAgent) {
254
+ properties[PostHogMCPAnalyticsProperty.ClientUserAgent] = event.clientUserAgent
255
+ }
256
+ if (event.vendorClient) {
257
+ properties[PostHogMCPAnalyticsProperty.VendorClient] = event.vendorClient
258
+ }
245
259
  if (event.protocolVersion) {
246
260
  properties[PostHogMCPAnalyticsProperty.ProtocolVersion] = event.protocolVersion
247
261
  }
@@ -19,6 +19,7 @@ import {
19
19
  } from './context-parameters'
20
20
  import { MCPAnalyticsEventType } from './event-types'
21
21
  import { captureException } from './exceptions'
22
+ import { normalizeHeaderString } from './headers'
22
23
  import { applyMcpLibIdentity } from './lib-identity'
23
24
  import { log } from './logger'
24
25
  import { McpEventSink } from './sink'
@@ -72,10 +73,6 @@ export interface PostHogMCPOptions extends PostHogOptions {
72
73
  * ```
73
74
  */
74
75
  export class PostHogMCP extends PostHog {
75
- // Reuses the shared sink so MCP events flow through the identical
76
- // sanitize/truncate/fan-out pipeline as the `instrument()` path; the sink
77
- // publishes via `this` (the inherited `capture()`), so the client's own
78
- // `beforeSend` and batching apply.
79
76
  readonly #sink = new McpEventSink(this)
80
77
 
81
78
  // The get_more_tools name lives here (not on the per-call options) so that
@@ -85,7 +82,6 @@ export class PostHogMCP extends PostHog {
85
82
  constructor(apiKey: string, options: PostHogMCPOptions = {}) {
86
83
  super(apiKey, options)
87
84
  this.#missingCapabilityToolName = options.missingCapabilityToolName ?? GET_MORE_TOOLS_NAME
88
- // Report `$lib: 'posthog-node-mcp'` instead of the inherited `posthog-node`.
89
85
  applyMcpLibIdentity(this)
90
86
  }
91
87
 
@@ -244,6 +240,12 @@ function baseEvent(eventType: MCPAnalyticsEventType, common: McpCaptureCommon):
244
240
  eventType,
245
241
  sessionId: common.sessionId,
246
242
  protocolVersion: common.protocolVersion,
243
+ // There is no `extra` on this path, so the host reads the request headers and
244
+ // passes them per capture — the SDK has no transport to read them from. Normalized
245
+ // with the same rules `instrument()` applies, so one request yields one set of
246
+ // properties whichever path captured it.
247
+ clientUserAgent: normalizeHeaderString(common.clientUserAgent),
248
+ vendorClient: normalizeHeaderString(common.vendorClient),
247
249
  timestamp: common.timestamp ?? new Date(),
248
250
  properties: common.properties,
249
251
  groups: common.groups,
@@ -0,0 +1,76 @@
1
+ import type { RequestHeaderBag } from '../types'
2
+
3
+ /**
4
+ * Reads the HTTP request headers off the `extra` (v1) / `ctx` (v2) object the
5
+ * MCP SDK hands a request handler, and returns them as a plain object with
6
+ * lowercase keys. Returns `undefined` when the request did not come over HTTP —
7
+ * stdio and in-memory transports carry no headers at all.
8
+ *
9
+ * The two SDK majors put them in different places and in different shapes: v1
10
+ * attaches a plain object at `extra.requestInfo.headers`, while v2 attaches the
11
+ * WHATWG `Request` at `ctx.http.req`, whose `headers` is a `Headers` instance
12
+ * that only answers to `.get()`. A v1-shaped read returns `undefined` on v2,
13
+ * which is why this exists.
14
+ *
15
+ * Normalisation is **by shape, not by source**: a framework is free to hand us a
16
+ * plain object where the SDK hands `Headers`, so both fields are checked for
17
+ * both shapes. `Headers` is duck-typed on `.entries` rather than `instanceof` —
18
+ * workerd and other edge runtimes are a different realm and would fail the
19
+ * identity check on a perfectly good object.
20
+ *
21
+ * Exported from the package for host callbacks. `identify`, `intentFallback`,
22
+ * `eventProperties` and `beforeSend` receive the SDK's `extra` unchanged — we
23
+ * deliberately do not synthesise a v1 shape on v2, because a fabricated
24
+ * `requestInfo` is a convincing partial lie about a shape the SDK removed on
25
+ * purpose. So a host that reads headers reads them through this instead:
26
+ *
27
+ * ```ts
28
+ * import { getRequestHeaders } from '@posthog/mcp'
29
+ *
30
+ * identify: async (request, extra) => {
31
+ * const auth = getRequestHeaders(extra)?.['authorization']
32
+ * // ...
33
+ * }
34
+ * ```
35
+ */
36
+ export function getRequestHeaders(extra: unknown): RequestHeaderBag | undefined {
37
+ if (!extra || typeof extra !== 'object') {
38
+ return undefined
39
+ }
40
+ const record = extra as Record<string, unknown>
41
+ const http = record.http as { req?: { headers?: unknown } } | undefined
42
+ const requestInfo = record.requestInfo as { headers?: unknown } | undefined
43
+ const source = http?.req?.headers ?? requestInfo?.headers
44
+ if (!source || typeof source !== 'object') {
45
+ return undefined
46
+ }
47
+ return toHeaderBag(source)
48
+ }
49
+
50
+ /**
51
+ * Flattens either shape into a lowercase-keyed bag. Never throws: a header read
52
+ * failing must not take a tool call down with it.
53
+ */
54
+ function toHeaderBag(source: object): RequestHeaderBag | undefined {
55
+ try {
56
+ const entries = isHeadersLike(source) ? [...source.entries()] : Object.entries(source)
57
+ const bag: RequestHeaderBag = {}
58
+ for (const [key, value] of entries) {
59
+ if (typeof key !== 'string' || value === undefined || value === null) {
60
+ continue
61
+ }
62
+ if (typeof value === 'string' || Array.isArray(value)) {
63
+ bag[key.toLowerCase()] = value as string | string[]
64
+ }
65
+ }
66
+ return bag
67
+ } catch {
68
+ return undefined
69
+ }
70
+ }
71
+
72
+ /** Duck-typed, never `instanceof` — an edge runtime's `Headers` is another realm's class. */
73
+ function isHeadersLike(source: object): source is { entries(): Iterable<[string, string]> } {
74
+ const candidate = source as { entries?: unknown; get?: unknown }
75
+ return typeof candidate.entries === 'function' && typeof candidate.get === 'function'
76
+ }
@@ -10,6 +10,8 @@
10
10
  * The token is unsigned: it holds only what the client already self-reports.
11
11
  */
12
12
 
13
+ import { readHeaderValue } from './headers'
14
+
13
15
  export const MCP_SESSION_HEADER = 'mcp-session-id'
14
16
 
15
17
  /** What a session token carries. */
@@ -105,21 +107,7 @@ export function decodeSessionId(value: unknown): SessionTokenPayload | null {
105
107
  * transports lowercase header keys; the fallback scan covers hand-built extras.
106
108
  */
107
109
  export function readMcpSessionHeader(headers: unknown): string | undefined {
108
- if (!headers || typeof headers !== 'object') {
109
- return undefined
110
- }
111
- const record = headers as Record<string, unknown>
112
- let value = record[MCP_SESSION_HEADER]
113
- if (value === undefined) {
114
- const key = Object.keys(record).find((k) => k.toLowerCase() === MCP_SESSION_HEADER)
115
- value = key === undefined ? undefined : record[key]
116
- }
117
- const first = Array.isArray(value) ? value[0] : value
118
- if (typeof first !== 'string') {
119
- return undefined
120
- }
121
- const trimmed = first.trim()
122
- return trimmed.length > 0 ? trimmed : undefined
110
+ return readHeaderValue(headers, MCP_SESSION_HEADER)
123
111
  }
124
112
 
125
113
  /**