@armature-tech/mcp-analytics 0.6.2 → 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;
@@ -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) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@armature-tech/mcp-analytics",
3
- "version": "0.6.2",
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",