@armature-tech/mcp-analytics 0.6.1 → 0.6.3

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.
@@ -2,10 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.__getMaxClientInfoCacheEntries = exports.__getClientInfoCacheSize = exports.__isInitializePatchInstalled = exports.__clearClientInfoCache = exports.__setClientInfoForSessionId = exports.getClientInfoForSessionId = exports.installClientInfoCapture = void 0;
4
4
  const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
5
- // In-process map keyed by transport sessionId. Populated by the patched
6
- // `Server.prototype._oninitialize` and read by the recorder at tool-call time.
7
- // Same instance the customer constructs, because `@modelcontextprotocol/sdk`
8
- // is a peer dependency.
5
+ const utils_js_1 = require("./utils.js");
6
+ // In-process map keyed by session id (transport sessionId and/or the
7
+ // `Mcp-Session-Id` request header). Populated by the patched
8
+ // `Server.prototype._onrequest` on `initialize` and read by the recorder at
9
+ // tool-call time. Same instance the customer constructs, because
10
+ // `@modelcontextprotocol/sdk` is a peer dependency.
9
11
  //
10
12
  // Bounded by `MAX_CACHE_ENTRIES` with FIFO eviction (Map iteration order is
11
13
  // insertion order in JS, so the first key is the oldest). MCP `initialize`
@@ -27,6 +29,7 @@ const setCachedClientInfo = (sessionId, info) => {
27
29
  clientInfoBySessionId.set(sessionId, info);
28
30
  };
29
31
  let initializePatchInstalled = false;
32
+ const HEADER_SESSION_ID = "mcp-session-id";
30
33
  const extractInitializeParams = (request) => {
31
34
  if (typeof request !== "object" || request === null)
32
35
  return {};
@@ -35,12 +38,61 @@ const extractInitializeParams = (request) => {
35
38
  ? params
36
39
  : {};
37
40
  };
38
- // `Server.prototype._oninitialize` is a private method that runs on every
39
- // `initialize` request, right before the handshake response is sent. Wrapping
40
- // it lets us snapshot `clientInfo` and key it by `transport.sessionId` so the
41
- // tool-call path can recover the client name even when the framework around
42
- // the SDK (e.g. Mastra's `MCPServer`) never surfaces the underlying `Server`
43
- // instance to the tool handler.
41
+ const headersFromExtra = (extra) => {
42
+ if (!(0, utils_js_1.isRecord)(extra))
43
+ return undefined;
44
+ const requestInfo = extra.requestInfo;
45
+ if (!(0, utils_js_1.isRecord)(requestInfo))
46
+ return undefined;
47
+ return requestInfo.headers;
48
+ };
49
+ // Snapshot `clientInfo` from an `initialize` request and cache it under every
50
+ // session-id key we can observe. Stateless Streamable HTTP (Vercel et al.)
51
+ // disables `sessionIdGenerator`, so `transport.sessionId` is undefined and the
52
+ // client's identity instead arrives via the `Mcp-Session-Id` request header —
53
+ // the same value the tool-call path later normalizes to. Keying by transport
54
+ // id AND header id AND `_meta.sessionId` means the tool-call lookup hits
55
+ // regardless of which one that request resolves to.
56
+ const captureClientInfoFromInitialize = (server, request, extra) => {
57
+ const params = extractInitializeParams(request);
58
+ const info = params.clientInfo;
59
+ const name = typeof info?.name === "string" ? info.name.trim() : "";
60
+ if (name.length === 0)
61
+ return;
62
+ const headerSessionId = (0, utils_js_1.headerValue)(headersFromExtra(extra), HEADER_SESSION_ID) ?? undefined;
63
+ const sessionIds = new Set();
64
+ if (server.transport?.sessionId)
65
+ sessionIds.add(server.transport.sessionId);
66
+ if (headerSessionId)
67
+ sessionIds.add(headerSessionId);
68
+ if (params._meta?.sessionId)
69
+ sessionIds.add(params._meta.sessionId);
70
+ if (sessionIds.size === 0)
71
+ return;
72
+ const clientInfo = {
73
+ name,
74
+ version: typeof info?.version === "string" ? info.version : undefined,
75
+ protocolVersion: typeof params.protocolVersion === "string"
76
+ ? params.protocolVersion
77
+ : undefined,
78
+ capabilities: typeof params.capabilities === "object" && params.capabilities !== null
79
+ ? params.capabilities
80
+ : null,
81
+ };
82
+ for (const sessionId of sessionIds) {
83
+ setCachedClientInfo(sessionId, clientInfo);
84
+ }
85
+ };
86
+ // `Server.prototype._onrequest` (inherited from `Protocol`) is the private
87
+ // dispatcher invoked for every inbound JSON-RPC request, and unlike the
88
+ // `initialize` handler — which the SDK registers as `request =>
89
+ // this._oninitialize(request)`, dropping the second argument — it receives both
90
+ // the request AND the per-request `extra` carrying `requestInfo.headers`. That
91
+ // makes it the only frame where the `initialize` payload's `clientInfo` and the
92
+ // `Mcp-Session-Id` header are in scope together, which we need for stateless
93
+ // HTTP. Wrapping it here also keeps the capture working when the framework
94
+ // around the SDK (e.g. Mastra's `MCPServer`) never surfaces the underlying
95
+ // `Server` instance to the tool handler.
44
96
  //
45
97
  // Defensive: if the SDK ever renames the method, the patch is a no-op and the
46
98
  // dashboard regresses to today's behaviour rather than breaking the server.
@@ -48,34 +100,20 @@ const installClientInfoCapture = () => {
48
100
  if (initializePatchInstalled)
49
101
  return;
50
102
  const proto = index_js_1.Server.prototype;
51
- if (typeof proto._oninitialize !== "function")
103
+ if (typeof proto._onrequest !== "function")
52
104
  return;
53
105
  initializePatchInstalled = true;
54
- const original = proto._oninitialize;
55
- proto._oninitialize = async function patchedOnInitialize(request) {
56
- const result = await original.call(this, request);
106
+ const original = proto._onrequest;
107
+ proto._onrequest = function patchedOnRequest(request, extra) {
57
108
  try {
58
- const params = extractInitializeParams(request);
59
- const sessionId = this.transport?.sessionId ?? params._meta?.sessionId ?? undefined;
60
- const info = params.clientInfo;
61
- const name = typeof info?.name === "string" ? info.name.trim() : "";
62
- if (sessionId && name.length > 0) {
63
- setCachedClientInfo(sessionId, {
64
- name,
65
- version: typeof info?.version === "string" ? info.version : undefined,
66
- protocolVersion: typeof params.protocolVersion === "string"
67
- ? params.protocolVersion
68
- : undefined,
69
- capabilities: typeof params.capabilities === "object" && params.capabilities !== null
70
- ? params.capabilities
71
- : null,
72
- });
109
+ if ((0, utils_js_1.isRecord)(request) && request.method === "initialize") {
110
+ captureClientInfoFromInitialize(this, request, extra);
73
111
  }
74
112
  }
75
113
  catch {
76
- // Capture is best-effort; never break the handshake.
114
+ // Capture is best-effort; never break request handling.
77
115
  }
78
- return result;
116
+ return original.call(this, request, extra);
79
117
  };
80
118
  };
81
119
  exports.installClientInfoCapture = installClientInfoCapture;
@@ -47,7 +47,7 @@ export declare const buildSessionInitBatch: ({ actorId, sessionId, requestId, st
47
47
  clientInfo?: McpClientInfo;
48
48
  }) => AnalyticsIngestBatch | null;
49
49
  export declare const normalizeSessionId: (eventSessionId: string | undefined, extra: RequestExtra | undefined) => string | undefined;
50
- export declare const normalizeRequestId: (eventRequestId: string | undefined, extra: RequestExtra | undefined) => string;
50
+ export declare const normalizeRequestId: (eventRequestId: string | undefined) => string;
51
51
  export declare const normalizeStartedAt: ({ startedAt, durationMs, finishedAtMs, }: {
52
52
  startedAt?: string | Date | number;
53
53
  durationMs?: number;
@@ -143,8 +143,16 @@ const normalizeSessionId = (eventSessionId, extra) => {
143
143
  return trimOrUndefined((0, utils_js_1.headerValue)(extra?.requestInfo?.headers, "mcp-session-id"));
144
144
  };
145
145
  exports.normalizeSessionId = normalizeSessionId;
146
- const normalizeRequestId = (eventRequestId, extra) => {
147
- return eventRequestId ?? (extra?.requestId === undefined ? (0, node_crypto_1.randomUUID)() : String(extra.requestId));
146
+ // The analytics request id seeds `event_id` (see `buildEventId`), so it MUST be
147
+ // unique per tool-call invocation. We intentionally do NOT derive it from the
148
+ // MCP JSON-RPC request id (`extra.requestId`): that is an in-memory per-client
149
+ // counter (0, 1, 2, …) that restarts on reconnect, across stateless gateway
150
+ // instances, etc., so two unrelated tool calls routinely share `extra.requestId`
151
+ // and would collide on `event_id` — making ingest dedupe the second call away.
152
+ // An explicit caller-supplied id still wins (it's a deliberate idempotency key);
153
+ // otherwise we mint a fresh uuid, matching the prototype-patch path in server.ts.
154
+ const normalizeRequestId = (eventRequestId) => {
155
+ return eventRequestId ?? (0, node_crypto_1.randomUUID)();
148
156
  };
149
157
  exports.normalizeRequestId = normalizeRequestId;
150
158
  const normalizeStartedAt = ({ startedAt, durationMs, finishedAtMs, }) => {
@@ -109,7 +109,11 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
109
109
  ctx: mastraContext,
110
110
  extra,
111
111
  sessionId: extra?.sessionId,
112
- requestId: extra?.requestId === undefined ? undefined : String(extra.requestId),
112
+ // Deliberately NOT forwarding `extra.requestId` (the MCP JSON-RPC id):
113
+ // it's a per-client counter that resets on reconnect, so reusing it as
114
+ // the event-id seed causes cross-session `event_id` collisions and lost
115
+ // events. Let the recorder mint a fresh per-call id (see
116
+ // `normalizeRequestId`). The JSON-RPC id stays available via `extra`.
113
117
  authInfo: extra?.authInfo,
114
118
  headers: extra?.requestInfo?.headers,
115
119
  }, (strippedArgs) => originalExecute(strippedArgs, mastraContext));
@@ -115,7 +115,7 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
115
115
  durationMs,
116
116
  finishedAtMs,
117
117
  });
118
- const requestId = (0, events_js_1.normalizeRequestId)(event.requestId, event.extra);
118
+ const requestId = (0, events_js_1.normalizeRequestId)(event.requestId);
119
119
  const sessionId = (0, events_js_1.normalizeSessionId)(event.sessionId, event.extra);
120
120
  const errorMessage = event.error === undefined
121
121
  ? undefined
@@ -193,7 +193,12 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
193
193
  const buildHandlerContext = (extra) => ({
194
194
  extra,
195
195
  sessionId: extra?.sessionId,
196
- requestId: extra?.requestId === undefined ? undefined : String(extra.requestId),
196
+ // Deliberately NOT surfacing `extra.requestId` (the MCP JSON-RPC id) as
197
+ // `context.requestId`: `dispatch` spreads the handler context into
198
+ // `instrumentToolCall`, so a handler that forwards its context into a nested
199
+ // tool call would seed that call's `event_id` with the JSON-RPC id — a
200
+ // per-client counter that resets on reconnect — re-introducing the exact
201
+ // collisions this fix removes. The id stays reachable via `context.extra`.
197
202
  authInfo: extra?.authInfo,
198
203
  headers: extra?.requestInfo?.headers,
199
204
  ctx: extra,
@@ -1,8 +1,10 @@
1
1
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
- // In-process map keyed by transport sessionId. Populated by the patched
3
- // `Server.prototype._oninitialize` and read by the recorder at tool-call time.
4
- // Same instance the customer constructs, because `@modelcontextprotocol/sdk`
5
- // is a peer dependency.
2
+ import { headerValue, isRecord } from "./utils.js";
3
+ // In-process map keyed by session id (transport sessionId and/or the
4
+ // `Mcp-Session-Id` request header). Populated by the patched
5
+ // `Server.prototype._onrequest` on `initialize` and read by the recorder at
6
+ // tool-call time. Same instance the customer constructs, because
7
+ // `@modelcontextprotocol/sdk` is a peer dependency.
6
8
  //
7
9
  // Bounded by `MAX_CACHE_ENTRIES` with FIFO eviction (Map iteration order is
8
10
  // insertion order in JS, so the first key is the oldest). MCP `initialize`
@@ -24,6 +26,7 @@ const setCachedClientInfo = (sessionId, info) => {
24
26
  clientInfoBySessionId.set(sessionId, info);
25
27
  };
26
28
  let initializePatchInstalled = false;
29
+ const HEADER_SESSION_ID = "mcp-session-id";
27
30
  const extractInitializeParams = (request) => {
28
31
  if (typeof request !== "object" || request === null)
29
32
  return {};
@@ -32,12 +35,61 @@ const extractInitializeParams = (request) => {
32
35
  ? params
33
36
  : {};
34
37
  };
35
- // `Server.prototype._oninitialize` is a private method that runs on every
36
- // `initialize` request, right before the handshake response is sent. Wrapping
37
- // it lets us snapshot `clientInfo` and key it by `transport.sessionId` so the
38
- // tool-call path can recover the client name even when the framework around
39
- // the SDK (e.g. Mastra's `MCPServer`) never surfaces the underlying `Server`
40
- // instance to the tool handler.
38
+ const headersFromExtra = (extra) => {
39
+ if (!isRecord(extra))
40
+ return undefined;
41
+ const requestInfo = extra.requestInfo;
42
+ if (!isRecord(requestInfo))
43
+ return undefined;
44
+ return requestInfo.headers;
45
+ };
46
+ // Snapshot `clientInfo` from an `initialize` request and cache it under every
47
+ // session-id key we can observe. Stateless Streamable HTTP (Vercel et al.)
48
+ // disables `sessionIdGenerator`, so `transport.sessionId` is undefined and the
49
+ // client's identity instead arrives via the `Mcp-Session-Id` request header —
50
+ // the same value the tool-call path later normalizes to. Keying by transport
51
+ // id AND header id AND `_meta.sessionId` means the tool-call lookup hits
52
+ // regardless of which one that request resolves to.
53
+ const captureClientInfoFromInitialize = (server, request, extra) => {
54
+ const params = extractInitializeParams(request);
55
+ const info = params.clientInfo;
56
+ const name = typeof info?.name === "string" ? info.name.trim() : "";
57
+ if (name.length === 0)
58
+ return;
59
+ const headerSessionId = headerValue(headersFromExtra(extra), HEADER_SESSION_ID) ?? undefined;
60
+ const sessionIds = new Set();
61
+ if (server.transport?.sessionId)
62
+ sessionIds.add(server.transport.sessionId);
63
+ if (headerSessionId)
64
+ sessionIds.add(headerSessionId);
65
+ if (params._meta?.sessionId)
66
+ sessionIds.add(params._meta.sessionId);
67
+ if (sessionIds.size === 0)
68
+ return;
69
+ const clientInfo = {
70
+ name,
71
+ version: typeof info?.version === "string" ? info.version : undefined,
72
+ protocolVersion: typeof params.protocolVersion === "string"
73
+ ? params.protocolVersion
74
+ : undefined,
75
+ capabilities: typeof params.capabilities === "object" && params.capabilities !== null
76
+ ? params.capabilities
77
+ : null,
78
+ };
79
+ for (const sessionId of sessionIds) {
80
+ setCachedClientInfo(sessionId, clientInfo);
81
+ }
82
+ };
83
+ // `Server.prototype._onrequest` (inherited from `Protocol`) is the private
84
+ // dispatcher invoked for every inbound JSON-RPC request, and unlike the
85
+ // `initialize` handler — which the SDK registers as `request =>
86
+ // this._oninitialize(request)`, dropping the second argument — it receives both
87
+ // the request AND the per-request `extra` carrying `requestInfo.headers`. That
88
+ // makes it the only frame where the `initialize` payload's `clientInfo` and the
89
+ // `Mcp-Session-Id` header are in scope together, which we need for stateless
90
+ // HTTP. Wrapping it here also keeps the capture working when the framework
91
+ // around the SDK (e.g. Mastra's `MCPServer`) never surfaces the underlying
92
+ // `Server` instance to the tool handler.
41
93
  //
42
94
  // Defensive: if the SDK ever renames the method, the patch is a no-op and the
43
95
  // dashboard regresses to today's behaviour rather than breaking the server.
@@ -45,34 +97,20 @@ export const installClientInfoCapture = () => {
45
97
  if (initializePatchInstalled)
46
98
  return;
47
99
  const proto = Server.prototype;
48
- if (typeof proto._oninitialize !== "function")
100
+ if (typeof proto._onrequest !== "function")
49
101
  return;
50
102
  initializePatchInstalled = true;
51
- const original = proto._oninitialize;
52
- proto._oninitialize = async function patchedOnInitialize(request) {
53
- const result = await original.call(this, request);
103
+ const original = proto._onrequest;
104
+ proto._onrequest = function patchedOnRequest(request, extra) {
54
105
  try {
55
- const params = extractInitializeParams(request);
56
- const sessionId = this.transport?.sessionId ?? params._meta?.sessionId ?? undefined;
57
- const info = params.clientInfo;
58
- const name = typeof info?.name === "string" ? info.name.trim() : "";
59
- if (sessionId && name.length > 0) {
60
- setCachedClientInfo(sessionId, {
61
- name,
62
- version: typeof info?.version === "string" ? info.version : undefined,
63
- protocolVersion: typeof params.protocolVersion === "string"
64
- ? params.protocolVersion
65
- : undefined,
66
- capabilities: typeof params.capabilities === "object" && params.capabilities !== null
67
- ? params.capabilities
68
- : null,
69
- });
106
+ if (isRecord(request) && request.method === "initialize") {
107
+ captureClientInfoFromInitialize(this, request, extra);
70
108
  }
71
109
  }
72
110
  catch {
73
- // Capture is best-effort; never break the handshake.
111
+ // Capture is best-effort; never break request handling.
74
112
  }
75
- return result;
113
+ return original.call(this, request, extra);
76
114
  };
77
115
  };
78
116
  export const getClientInfoForSessionId = (sessionId) => {
@@ -47,7 +47,7 @@ export declare const buildSessionInitBatch: ({ actorId, sessionId, requestId, st
47
47
  clientInfo?: McpClientInfo;
48
48
  }) => AnalyticsIngestBatch | null;
49
49
  export declare const normalizeSessionId: (eventSessionId: string | undefined, extra: RequestExtra | undefined) => string | undefined;
50
- export declare const normalizeRequestId: (eventRequestId: string | undefined, extra: RequestExtra | undefined) => string;
50
+ export declare const normalizeRequestId: (eventRequestId: string | undefined) => string;
51
51
  export declare const normalizeStartedAt: ({ startedAt, durationMs, finishedAtMs, }: {
52
52
  startedAt?: string | Date | number;
53
53
  durationMs?: number;
@@ -133,8 +133,16 @@ export const normalizeSessionId = (eventSessionId, extra) => {
133
133
  return explicit;
134
134
  return trimOrUndefined(headerValue(extra?.requestInfo?.headers, "mcp-session-id"));
135
135
  };
136
- export const normalizeRequestId = (eventRequestId, extra) => {
137
- return eventRequestId ?? (extra?.requestId === undefined ? randomUUID() : String(extra.requestId));
136
+ // The analytics request id seeds `event_id` (see `buildEventId`), so it MUST be
137
+ // unique per tool-call invocation. We intentionally do NOT derive it from the
138
+ // MCP JSON-RPC request id (`extra.requestId`): that is an in-memory per-client
139
+ // counter (0, 1, 2, …) that restarts on reconnect, across stateless gateway
140
+ // instances, etc., so two unrelated tool calls routinely share `extra.requestId`
141
+ // and would collide on `event_id` — making ingest dedupe the second call away.
142
+ // An explicit caller-supplied id still wins (it's a deliberate idempotency key);
143
+ // otherwise we mint a fresh uuid, matching the prototype-patch path in server.ts.
144
+ export const normalizeRequestId = (eventRequestId) => {
145
+ return eventRequestId ?? randomUUID();
138
146
  };
139
147
  export const normalizeStartedAt = ({ startedAt, durationMs, finishedAtMs, }) => {
140
148
  if (startedAt instanceof Date)
@@ -105,7 +105,11 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
105
105
  ctx: mastraContext,
106
106
  extra,
107
107
  sessionId: extra?.sessionId,
108
- requestId: extra?.requestId === undefined ? undefined : String(extra.requestId),
108
+ // Deliberately NOT forwarding `extra.requestId` (the MCP JSON-RPC id):
109
+ // it's a per-client counter that resets on reconnect, so reusing it as
110
+ // the event-id seed causes cross-session `event_id` collisions and lost
111
+ // events. Let the recorder mint a fresh per-call id (see
112
+ // `normalizeRequestId`). The JSON-RPC id stays available via `extra`.
109
113
  authInfo: extra?.authInfo,
110
114
  headers: extra?.requestInfo?.headers,
111
115
  }, (strippedArgs) => originalExecute(strippedArgs, mastraContext));
@@ -112,7 +112,7 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
112
112
  durationMs,
113
113
  finishedAtMs,
114
114
  });
115
- const requestId = normalizeRequestId(event.requestId, event.extra);
115
+ const requestId = normalizeRequestId(event.requestId);
116
116
  const sessionId = normalizeSessionId(event.sessionId, event.extra);
117
117
  const errorMessage = event.error === undefined
118
118
  ? undefined
@@ -190,7 +190,12 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
190
190
  const buildHandlerContext = (extra) => ({
191
191
  extra,
192
192
  sessionId: extra?.sessionId,
193
- requestId: extra?.requestId === undefined ? undefined : String(extra.requestId),
193
+ // Deliberately NOT surfacing `extra.requestId` (the MCP JSON-RPC id) as
194
+ // `context.requestId`: `dispatch` spreads the handler context into
195
+ // `instrumentToolCall`, so a handler that forwards its context into a nested
196
+ // tool call would seed that call's `event_id` with the JSON-RPC id — a
197
+ // per-client counter that resets on reconnect — re-introducing the exact
198
+ // collisions this fix removes. The id stays reachable via `context.extra`.
194
199
  authInfo: extra?.authInfo,
195
200
  headers: extra?.requestInfo?.headers,
196
201
  ctx: extra,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@armature-tech/mcp-analytics",
3
- "version": "0.6.1",
3
+ "version": "0.6.3",
4
4
  "type": "module",
5
5
  "description": "MCP analytics wrapper SDK that instruments MCP tool declarations with telemetry.",
6
6
  "license": "Apache-2.0",