@armature-tech/mcp-analytics 0.6.2 → 0.6.4

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,4 +1,5 @@
1
1
  import type { AnalyticsEventKind, AnalyticsIngestBatch, AnalyticsIngestEvent, McpClientInfo, RequestExtra, TelemetryArgs } from "./types.js";
2
+ import { type BoundedKeySet } from "./utils.js";
2
3
  export declare const buildActorId: ({ actorSeed, }: {
3
4
  actorSeed: string;
4
5
  }) => string;
@@ -21,10 +22,9 @@ export declare const buildToolCallEvent: ({ toolName, telemetry, input, output,
21
22
  startedAt: string;
22
23
  finishedAt: string;
23
24
  }) => AnalyticsIngestEvent;
24
- export declare const buildSessionInitEvent: ({ actorId, sessionId, requestId, startedAt, extra, clientInfo, }: {
25
+ export declare const buildSessionInitEvent: ({ actorId, sessionId, startedAt, extra, clientInfo, }: {
25
26
  actorId: string;
26
27
  sessionId: string;
27
- requestId: string;
28
28
  startedAt: string;
29
29
  extra?: RequestExtra;
30
30
  clientInfo?: McpClientInfo;
@@ -34,16 +34,15 @@ export declare const buildBatch: ({ event, extra, actorId, startedAt, sessionIni
34
34
  extra?: RequestExtra;
35
35
  actorId: string;
36
36
  startedAt: string;
37
- sessionInitKeys: Set<string>;
37
+ sessionInitKeys: BoundedKeySet;
38
38
  clientInfo?: McpClientInfo;
39
39
  }) => AnalyticsIngestBatch;
40
- export declare const buildSessionInitBatch: ({ actorId, sessionId, requestId, startedAt, extra, sessionInitKeys, clientInfo, }: {
40
+ export declare const buildSessionInitBatch: ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, }: {
41
41
  actorId: string;
42
42
  sessionId: string;
43
- requestId: string;
44
43
  startedAt: string;
45
44
  extra?: RequestExtra;
46
- sessionInitKeys: Set<string>;
45
+ sessionInitKeys: BoundedKeySet;
47
46
  clientInfo?: McpClientInfo;
48
47
  }) => AnalyticsIngestBatch | null;
49
48
  export declare const normalizeSessionId: (eventSessionId: string | undefined, extra: RequestExtra | undefined) => string | undefined;
@@ -65,9 +65,15 @@ const buildToolCallEvent = ({ toolName, telemetry, input, output, status, durati
65
65
  };
66
66
  };
67
67
  exports.buildToolCallEvent = buildToolCallEvent;
68
- const buildSessionInitEvent = ({ actorId, sessionId, requestId, startedAt, extra, clientInfo, }) => {
68
+ const buildSessionInitEvent = ({ actorId, sessionId, startedAt, extra, clientInfo, }) => {
69
69
  return {
70
- event_id: (0, exports.buildEventId)({ actorId, requestId, kind: "session_init" }),
70
+ // Stable per (actorId, sessionId): a session has exactly one session_init,
71
+ // so seeding the id with the sessionId lets ingest de-dup it on its own —
72
+ // independent of the in-memory `sessionInitKeys` set (which is now bounded
73
+ // and may evict) and idempotent across process restarts / serverless cold
74
+ // starts that re-handle the same session. `kind` is already in the hash, so
75
+ // there's no collision with tool_call ids that reuse the same seed.
76
+ event_id: (0, exports.buildEventId)({ actorId, requestId: sessionId, kind: "session_init" }),
71
77
  kind: "session_init",
72
78
  actor_id: actorId,
73
79
  session_id_hint: sessionId,
@@ -105,7 +111,6 @@ const buildBatch = ({ event, extra, actorId, startedAt, sessionInitKeys, clientI
105
111
  events.push((0, exports.buildSessionInitEvent)({
106
112
  actorId,
107
113
  sessionId: extra.sessionId,
108
- requestId: `${event.event_id}:session_init`,
109
114
  startedAt,
110
115
  extra,
111
116
  clientInfo,
@@ -116,7 +121,7 @@ const buildBatch = ({ event, extra, actorId, startedAt, sessionInitKeys, clientI
116
121
  return { schema_version: utils_js_1.SCHEMA_VERSION, events };
117
122
  };
118
123
  exports.buildBatch = buildBatch;
119
- const buildSessionInitBatch = ({ actorId, sessionId, requestId, startedAt, extra, sessionInitKeys, clientInfo, }) => {
124
+ const buildSessionInitBatch = ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, }) => {
120
125
  const key = `${actorId}:${sessionId}`;
121
126
  if (sessionInitKeys.has(key))
122
127
  return null;
@@ -127,7 +132,6 @@ const buildSessionInitBatch = ({ actorId, sessionId, requestId, startedAt, extra
127
132
  (0, exports.buildSessionInitEvent)({
128
133
  actorId,
129
134
  sessionId,
130
- requestId,
131
135
  startedAt,
132
136
  extra,
133
137
  clientInfo,
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createAnalyticsRecorder = void 0;
4
- const node_crypto_1 = require("node:crypto");
5
4
  const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
6
5
  const events_js_1 = require("./events.js");
7
6
  const emit_js_1 = require("./emit.js");
@@ -49,7 +48,13 @@ const createAnalyticsContext = async (config, input) => {
49
48
  };
50
49
  const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) => {
51
50
  const { emitBatch, flush } = (0, emit_js_1.createFlushableEmitter)(config);
52
- const sessionInitKeys = new Set();
51
+ // Tracks which (actorId, sessionId) pairs have already emitted a session_init,
52
+ // so we emit it at most once per session. Bounded with FIFO eviction: MCP
53
+ // gives no reliable session-closed signal, so an unbounded set would leak on
54
+ // long-running servers with high session churn. Eviction is safe because the
55
+ // session_init event_id is now stable per (actorId, sessionId), so a re-emit
56
+ // after eviction collapses to the same id at ingest. 10k × ~60 bytes ≈ 600KB.
57
+ const sessionInitKeys = (0, utils_js_1.createBoundedKeySet)(10_000);
53
58
  // Patch the SDK's Server.prototype the first time any recorder is created
54
59
  // so that the very next `initialize` handshake feeds the per-session client
55
60
  // info cache. Without this the dashboard's "Client" column would stay at
@@ -89,7 +94,6 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
89
94
  const batch = (0, events_js_1.buildSessionInitBatch)({
90
95
  actorId: context.actorId,
91
96
  sessionId,
92
- requestId: event.requestId ?? (0, node_crypto_1.randomUUID)(),
93
97
  startedAt,
94
98
  extra: event.extra,
95
99
  sessionInitKeys,
@@ -8,6 +8,11 @@ export declare const isJsonObjectSchema: (value: unknown) => value is JsonObject
8
8
  export declare const isRawShape: (value: unknown) => value is Record<string, unknown>;
9
9
  export declare const readEnv: (key: string) => string | undefined;
10
10
  export declare const sha256Hex: (value: string) => string;
11
+ export type BoundedKeySet = {
12
+ has: (key: string) => boolean;
13
+ add: (key: string) => void;
14
+ };
15
+ export declare const createBoundedKeySet: (maxEntries: number) => BoundedKeySet;
11
16
  export declare const stringifyPreview: (value: unknown) => string;
12
17
  export declare const truncateUtf8: (value: string, maxBytes: number) => {
13
18
  value: string;
package/dist/cjs/utils.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.headerValue = exports.truncateUtf8 = exports.stringifyPreview = exports.sha256Hex = exports.readEnv = exports.isRawShape = exports.isJsonObjectSchema = exports.isRecord = exports.MAX_CAPABILITIES_BYTES = exports.MAX_PREVIEW_BYTES = exports.MAX_SOURCE_BYTES = exports.SCHEMA_VERSION = void 0;
3
+ exports.headerValue = exports.truncateUtf8 = exports.stringifyPreview = exports.createBoundedKeySet = exports.sha256Hex = exports.readEnv = exports.isRawShape = exports.isJsonObjectSchema = exports.isRecord = exports.MAX_CAPABILITIES_BYTES = exports.MAX_PREVIEW_BYTES = exports.MAX_SOURCE_BYTES = exports.SCHEMA_VERSION = void 0;
4
4
  const node_crypto_1 = require("node:crypto");
5
5
  exports.SCHEMA_VERSION = 1;
6
6
  exports.MAX_SOURCE_BYTES = 32 * 1024;
@@ -29,6 +29,31 @@ const sha256Hex = (value) => {
29
29
  return (0, node_crypto_1.createHash)("sha256").update(value).digest("hex");
30
30
  };
31
31
  exports.sha256Hex = sha256Hex;
32
+ // A `Set<string>` capped at `maxEntries` with FIFO eviction (Map/Set iteration
33
+ // order is insertion order in JS, so the first key is the oldest). MCP fires no
34
+ // reliable "session-closed" signal, so an unbounded set of session keys would
35
+ // leak forever on a long-running server with high session churn — the same
36
+ // reasoning behind the client-info cache's bound. Eviction is safe because the
37
+ // only consumers (`session_init` de-dup) now derive a stable `event_id` per
38
+ // (actorId, sessionId), so a re-emitted `session_init` after eviction collapses
39
+ // to the same id at ingest rather than double-counting.
40
+ const createBoundedKeySet = (maxEntries) => {
41
+ const keys = new Set();
42
+ return {
43
+ has: (key) => keys.has(key),
44
+ add: (key) => {
45
+ if (keys.has(key))
46
+ return;
47
+ if (keys.size >= maxEntries) {
48
+ const oldest = keys.values().next().value;
49
+ if (oldest !== undefined)
50
+ keys.delete(oldest);
51
+ }
52
+ keys.add(key);
53
+ },
54
+ };
55
+ };
56
+ exports.createBoundedKeySet = createBoundedKeySet;
32
57
  const stringifyPreview = (value) => {
33
58
  if (value === undefined)
34
59
  return "undefined";
@@ -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) => {
@@ -1,4 +1,5 @@
1
1
  import type { AnalyticsEventKind, AnalyticsIngestBatch, AnalyticsIngestEvent, McpClientInfo, RequestExtra, TelemetryArgs } from "./types.js";
2
+ import { type BoundedKeySet } from "./utils.js";
2
3
  export declare const buildActorId: ({ actorSeed, }: {
3
4
  actorSeed: string;
4
5
  }) => string;
@@ -21,10 +22,9 @@ export declare const buildToolCallEvent: ({ toolName, telemetry, input, output,
21
22
  startedAt: string;
22
23
  finishedAt: string;
23
24
  }) => AnalyticsIngestEvent;
24
- export declare const buildSessionInitEvent: ({ actorId, sessionId, requestId, startedAt, extra, clientInfo, }: {
25
+ export declare const buildSessionInitEvent: ({ actorId, sessionId, startedAt, extra, clientInfo, }: {
25
26
  actorId: string;
26
27
  sessionId: string;
27
- requestId: string;
28
28
  startedAt: string;
29
29
  extra?: RequestExtra;
30
30
  clientInfo?: McpClientInfo;
@@ -34,16 +34,15 @@ export declare const buildBatch: ({ event, extra, actorId, startedAt, sessionIni
34
34
  extra?: RequestExtra;
35
35
  actorId: string;
36
36
  startedAt: string;
37
- sessionInitKeys: Set<string>;
37
+ sessionInitKeys: BoundedKeySet;
38
38
  clientInfo?: McpClientInfo;
39
39
  }) => AnalyticsIngestBatch;
40
- export declare const buildSessionInitBatch: ({ actorId, sessionId, requestId, startedAt, extra, sessionInitKeys, clientInfo, }: {
40
+ export declare const buildSessionInitBatch: ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, }: {
41
41
  actorId: string;
42
42
  sessionId: string;
43
- requestId: string;
44
43
  startedAt: string;
45
44
  extra?: RequestExtra;
46
- sessionInitKeys: Set<string>;
45
+ sessionInitKeys: BoundedKeySet;
47
46
  clientInfo?: McpClientInfo;
48
47
  }) => AnalyticsIngestBatch | null;
49
48
  export declare const normalizeSessionId: (eventSessionId: string | undefined, extra: RequestExtra | undefined) => string | undefined;
@@ -59,9 +59,15 @@ export const buildToolCallEvent = ({ toolName, telemetry, input, output, status,
59
59
  search_calls: [],
60
60
  };
61
61
  };
62
- export const buildSessionInitEvent = ({ actorId, sessionId, requestId, startedAt, extra, clientInfo, }) => {
62
+ export const buildSessionInitEvent = ({ actorId, sessionId, startedAt, extra, clientInfo, }) => {
63
63
  return {
64
- event_id: buildEventId({ actorId, requestId, kind: "session_init" }),
64
+ // Stable per (actorId, sessionId): a session has exactly one session_init,
65
+ // so seeding the id with the sessionId lets ingest de-dup it on its own —
66
+ // independent of the in-memory `sessionInitKeys` set (which is now bounded
67
+ // and may evict) and idempotent across process restarts / serverless cold
68
+ // starts that re-handle the same session. `kind` is already in the hash, so
69
+ // there's no collision with tool_call ids that reuse the same seed.
70
+ event_id: buildEventId({ actorId, requestId: sessionId, kind: "session_init" }),
65
71
  kind: "session_init",
66
72
  actor_id: actorId,
67
73
  session_id_hint: sessionId,
@@ -98,7 +104,6 @@ export const buildBatch = ({ event, extra, actorId, startedAt, sessionInitKeys,
98
104
  events.push(buildSessionInitEvent({
99
105
  actorId,
100
106
  sessionId: extra.sessionId,
101
- requestId: `${event.event_id}:session_init`,
102
107
  startedAt,
103
108
  extra,
104
109
  clientInfo,
@@ -108,7 +113,7 @@ export const buildBatch = ({ event, extra, actorId, startedAt, sessionInitKeys,
108
113
  events.push(event);
109
114
  return { schema_version: SCHEMA_VERSION, events };
110
115
  };
111
- export const buildSessionInitBatch = ({ actorId, sessionId, requestId, startedAt, extra, sessionInitKeys, clientInfo, }) => {
116
+ export const buildSessionInitBatch = ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, }) => {
112
117
  const key = `${actorId}:${sessionId}`;
113
118
  if (sessionInitKeys.has(key))
114
119
  return null;
@@ -119,7 +124,6 @@ export const buildSessionInitBatch = ({ actorId, sessionId, requestId, startedAt
119
124
  buildSessionInitEvent({
120
125
  actorId,
121
126
  sessionId,
122
- requestId,
123
127
  startedAt,
124
128
  extra,
125
129
  clientInfo,
@@ -1,9 +1,8 @@
1
- import { randomUUID } from "node:crypto";
2
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
2
  import { buildActorId, buildBatch, buildSessionInitBatch, buildToolCallEvent, normalizeRequestId, normalizeSessionId, normalizeStartedAt, } from "./events.js";
4
3
  import { createFlushableEmitter, defaultMcpAnalyticsConfig, resolveActorSeed, } from "./emit.js";
5
4
  import { decorateInputSchemaWithTelemetry, extractTelemetryArguments, INTENT_DESCRIPTION, TELEMETRY_PROPERTY_DESCRIPTION, } from "./schema.js";
6
- import { isJsonObjectSchema, isRecord } from "./utils.js";
5
+ import { createBoundedKeySet, isJsonObjectSchema, isRecord } from "./utils.js";
7
6
  import { getClientInfoForSessionId, installClientInfoCapture, } from "./client-info-cache.js";
8
7
  const TELEMETRY_DESCRIPTION_HINT = "\n\nPass telemetry.intent with a one-line user intent for analytics.";
9
8
  const TELEMETRY_DESCRIPTION_HINT_MARKER = TELEMETRY_DESCRIPTION_HINT.trim();
@@ -46,7 +45,13 @@ const createAnalyticsContext = async (config, input) => {
46
45
  };
47
46
  export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
48
47
  const { emitBatch, flush } = createFlushableEmitter(config);
49
- const sessionInitKeys = new Set();
48
+ // Tracks which (actorId, sessionId) pairs have already emitted a session_init,
49
+ // so we emit it at most once per session. Bounded with FIFO eviction: MCP
50
+ // gives no reliable session-closed signal, so an unbounded set would leak on
51
+ // long-running servers with high session churn. Eviction is safe because the
52
+ // session_init event_id is now stable per (actorId, sessionId), so a re-emit
53
+ // after eviction collapses to the same id at ingest. 10k × ~60 bytes ≈ 600KB.
54
+ const sessionInitKeys = createBoundedKeySet(10_000);
50
55
  // Patch the SDK's Server.prototype the first time any recorder is created
51
56
  // so that the very next `initialize` handshake feeds the per-session client
52
57
  // info cache. Without this the dashboard's "Client" column would stay at
@@ -86,7 +91,6 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
86
91
  const batch = buildSessionInitBatch({
87
92
  actorId: context.actorId,
88
93
  sessionId,
89
- requestId: event.requestId ?? randomUUID(),
90
94
  startedAt,
91
95
  extra: event.extra,
92
96
  sessionInitKeys,
@@ -8,6 +8,11 @@ export declare const isJsonObjectSchema: (value: unknown) => value is JsonObject
8
8
  export declare const isRawShape: (value: unknown) => value is Record<string, unknown>;
9
9
  export declare const readEnv: (key: string) => string | undefined;
10
10
  export declare const sha256Hex: (value: string) => string;
11
+ export type BoundedKeySet = {
12
+ has: (key: string) => boolean;
13
+ add: (key: string) => void;
14
+ };
15
+ export declare const createBoundedKeySet: (maxEntries: number) => BoundedKeySet;
11
16
  export declare const stringifyPreview: (value: unknown) => string;
12
17
  export declare const truncateUtf8: (value: string, maxBytes: number) => {
13
18
  value: string;
package/dist/esm/utils.js CHANGED
@@ -21,6 +21,30 @@ export const readEnv = (key) => {
21
21
  export const sha256Hex = (value) => {
22
22
  return createHash("sha256").update(value).digest("hex");
23
23
  };
24
+ // A `Set<string>` capped at `maxEntries` with FIFO eviction (Map/Set iteration
25
+ // order is insertion order in JS, so the first key is the oldest). MCP fires no
26
+ // reliable "session-closed" signal, so an unbounded set of session keys would
27
+ // leak forever on a long-running server with high session churn — the same
28
+ // reasoning behind the client-info cache's bound. Eviction is safe because the
29
+ // only consumers (`session_init` de-dup) now derive a stable `event_id` per
30
+ // (actorId, sessionId), so a re-emitted `session_init` after eviction collapses
31
+ // to the same id at ingest rather than double-counting.
32
+ export const createBoundedKeySet = (maxEntries) => {
33
+ const keys = new Set();
34
+ return {
35
+ has: (key) => keys.has(key),
36
+ add: (key) => {
37
+ if (keys.has(key))
38
+ return;
39
+ if (keys.size >= maxEntries) {
40
+ const oldest = keys.values().next().value;
41
+ if (oldest !== undefined)
42
+ keys.delete(oldest);
43
+ }
44
+ keys.add(key);
45
+ },
46
+ };
47
+ };
24
48
  export const stringifyPreview = (value) => {
25
49
  if (value === undefined)
26
50
  return "undefined";
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.4",
4
4
  "type": "module",
5
5
  "description": "MCP analytics wrapper SDK that instruments MCP tool declarations with telemetry.",
6
6
  "license": "Apache-2.0",