@armature-tech/mcp-analytics 0.6.33 → 0.6.34

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.
@@ -0,0 +1,359 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultMcpAnalyticsConfig = exports.instrumentFastMCP = exports.defaultFastmcpResolveExtra = exports.flushFastmcpAnalytics = exports.FASTMCP_SESSION_SEED_HEADER = void 0;
4
+ exports.withFastmcpAnalytics = withFastmcpAnalytics;
5
+ const recorder_core_js_1 = require("./recorder-core.js");
6
+ const emit_js_1 = require("./emit.js");
7
+ const schema_js_1 = require("./schema.js");
8
+ const utils_js_1 = require("./utils.js");
9
+ // Adapter for punkpeye/fastmcp (npm `fastmcp`, v1-SDK based). fastmcp routes
10
+ // tool calls through its own low-level `new Server(...)` +
11
+ // `setRequestHandler(CallToolRequestSchema, ...)` dispatcher
12
+ // (fastmcp/dist/chunk-*.js `setupToolHandlers`), so the package root's
13
+ // `McpServer.prototype` patches never see those calls — a fastmcp server was
14
+ // previously unrecorded. This module wraps the `execute` function of the tool
15
+ // definition objects users pass to `server.addTool(...)` instead.
16
+ //
17
+ // Structural typing only: NO runtime or type dependency on the `fastmcp`
18
+ // package, and none on `@modelcontextprotocol/*` either (the shared record
19
+ // pipeline in recorder-core.ts is SDK-free).
20
+ //
21
+ // Verified fastmcp API facts this adapter is built on (fastmcp 4.12.1,
22
+ // dist/FastMCP.d.ts + dist/chunk-*.js `setupToolHandlers`):
23
+ //
24
+ // - `execute(args, context)` — `args` is the Standard-Schema-validated value
25
+ // (or `undefined` when the tool declares no `parameters`); `context` carries
26
+ // `client.version` (the SDK Server's `getClientVersion()`, i.e. the
27
+ // `initialize` clientInfo), `log`, `reportProgress`, `streamContent`,
28
+ // `elicit`, `requestId` (from `params._meta.requestId`, rarely present),
29
+ // `session` (the value the user's `authenticate(request)` returned), and
30
+ // `sessionId` (the `Mcp-Session-Id`; HTTP transports only).
31
+ // - Errors: a throwing `execute` is caught by fastmcp and converted into an
32
+ // `isError: true` content result (`UserError` keeps its message verbatim,
33
+ // anything else becomes "Tool '<name>' execution failed: <message>"). A
34
+ // returned `isError: true` ContentResult passes through as-is. Both shapes
35
+ // are recorded here as failed calls; the value returned to fastmcp is
36
+ // untouched either way.
37
+ // - `tool.timeoutMs` races OUTSIDE `execute`: on timeout fastmcp returns a
38
+ // `UserError` result while the execute promise keeps running. The analytics
39
+ // event records the execute outcome (true handler duration/status), not the
40
+ // timeout envelope.
41
+ //
42
+ // What fastmcp does NOT expose to the execute context — documented limits,
43
+ // not gaps this adapter papers over:
44
+ //
45
+ // - HTTP request headers are unreachable from `execute`. `authenticate(request)`
46
+ // receives the `http.IncomingMessage`, but only what it copies into its
47
+ // return value (= `context.session`) survives. The adapter therefore reads
48
+ // `context.session.headers` when present (set `authenticate: async (req) =>
49
+ // ({ headers: req.headers, ... })` to opt in) and offers `resolveExtra` for
50
+ // anything else. Without that, the `x-armature-session-seed` and workflow
51
+ // headers are invisible and `session_init` identity comes only from
52
+ // `context.client.version`.
53
+ // - Client identity (`context.client.version`) is populated from the session's
54
+ // `initialize` handshake. In fastmcp's **stateless** httpStream mode every
55
+ // request builds a fresh session that never saw `initialize`, so it is
56
+ // `undefined` there and tool calls record an unknown client — honest, since
57
+ // nothing else in the execute context carries identity.
58
+ // - Tool input schemas are opaque Standard Schema objects that fastmcp
59
+ // validates BEFORE `execute` (advertising `additionalProperties: false`), so
60
+ // the adapter does NOT decorate schemas with the `telemetry` field (same
61
+ // decision, for the same conversion-hazard reasons, as the v2 adapter). A
62
+ // `telemetry` argument that still reaches `execute` (e.g. a passthrough zod
63
+ // object) is stripped and exported per the contract; a schema that declares
64
+ // its own top-level `telemetry` keeps owning it ("owned" mode); with capture
65
+ // off it is stripped and dropped ("scrub").
66
+ /** Header a caller can set to pin the analytics session id (matches the v1 stateless pattern and the v2 ladder). */
67
+ exports.FASTMCP_SESSION_SEED_HEADER = "x-armature-session-seed";
68
+ // Wrapped execute functions and instrumented servers are tagged so re-wrapping
69
+ // (double `withFastmcpAnalytics`, `instrumentFastMCP` over pre-wrapped tools,
70
+ // double `instrumentFastMCP`) can never double-record a call.
71
+ const WRAPPED_EXECUTE = Symbol.for("armature.mcpAnalytics.fastmcp.wrappedExecute");
72
+ const WRAPPED_SERVER = Symbol.for("armature.mcpAnalytics.fastmcp.wrappedServer");
73
+ // ─── Recorder state (shared per options object) ─────────────────────────────
74
+ // Keyed on the caller's options object so every wrap call that reuses the same
75
+ // options shares one recorder (privacy queue + session_init dedupe) — the same
76
+ // hoist-the-config contract as the v2 adapter. A fresh options object per call
77
+ // still converges at ingest (event ids are content-addressed).
78
+ const recorderStatesByOptions = new WeakMap();
79
+ let defaultRecorderState;
80
+ const createRecorderState = (config) => {
81
+ const toolModes = new Map();
82
+ const core = (0, recorder_core_js_1.createAnalyticsRecorderCore)(config, {
83
+ isToolTelemetryOwned: (name) => toolModes.get(name) === "owned",
84
+ });
85
+ return { core, config, toolModes };
86
+ };
87
+ const recorderStateFor = (options) => {
88
+ if (options === undefined || options === emit_js_1.defaultMcpAnalyticsConfig) {
89
+ defaultRecorderState ??= createRecorderState(emit_js_1.defaultMcpAnalyticsConfig);
90
+ return defaultRecorderState;
91
+ }
92
+ let state = recorderStatesByOptions.get(options);
93
+ if (!state) {
94
+ const { resolveExtra: _resolveExtra, transport: _transport, ...config } = options;
95
+ state = createRecorderState(config);
96
+ recorderStatesByOptions.set(options, state);
97
+ }
98
+ return state;
99
+ };
100
+ /**
101
+ * Drain the analytics pipeline tied to an options object (or the default
102
+ * config). Call before process exit when not using `delivery: "await"` or a
103
+ * `schedule` hook.
104
+ */
105
+ const flushFastmcpAnalytics = (options) => {
106
+ return recorderStateFor(options).core.flush();
107
+ };
108
+ exports.flushFastmcpAnalytics = flushFastmcpAnalytics;
109
+ // ─── Per-call capture ───────────────────────────────────────────────────────
110
+ const trimOrUndefined = (value) => {
111
+ if (typeof value !== "string")
112
+ return undefined;
113
+ const trimmed = value.trim();
114
+ return trimmed.length > 0 ? trimmed : undefined;
115
+ };
116
+ // `context.client.version` is the v1 SDK's `Implementation` from the session's
117
+ // `initialize` handshake ({ name, version }), or undefined when the session
118
+ // never saw one (fastmcp stateless httpStream mode).
119
+ const clientInfoFromContext = (context) => {
120
+ if (!(0, utils_js_1.isRecord)(context))
121
+ return undefined;
122
+ const client = (0, utils_js_1.isRecord)(context.client) ? context.client : undefined;
123
+ const version = (0, utils_js_1.isRecord)(client?.version) ? client.version : undefined;
124
+ const name = trimOrUndefined(version?.name);
125
+ if (name === undefined)
126
+ return undefined;
127
+ const clientVersion = trimOrUndefined(version?.version);
128
+ return { name, ...(clientVersion !== undefined ? { version: clientVersion } : {}) };
129
+ };
130
+ const headerBagFrom = (value) => {
131
+ if (value instanceof Headers)
132
+ return value;
133
+ return (0, utils_js_1.isRecord)(value) ? value : undefined;
134
+ };
135
+ /**
136
+ * The extra the adapter derives from fastmcp's execute context on its own:
137
+ * `context.sessionId` (the Mcp-Session-Id fastmcp surfaces on HTTP
138
+ * transports), request headers IF the user's `authenticate` copied them into
139
+ * the auth object as `headers` (`context.session.headers`), and the four
140
+ * actor-seed fields (`token`/`clientId`/`apiKey`/`principalId`) when the auth
141
+ * object carries them as strings. Exported for reuse in custom `resolveExtra`
142
+ * implementations.
143
+ */
144
+ const defaultFastmcpResolveExtra = (context) => {
145
+ if (!(0, utils_js_1.isRecord)(context))
146
+ return undefined;
147
+ const result = {};
148
+ const sessionId = trimOrUndefined(context.sessionId);
149
+ if (sessionId !== undefined)
150
+ result.sessionId = sessionId;
151
+ const session = (0, utils_js_1.isRecord)(context.session) ? context.session : undefined;
152
+ const headers = headerBagFrom(session?.headers);
153
+ if (headers !== undefined)
154
+ result.requestInfo = { headers };
155
+ if (session) {
156
+ // Same four-field narrowing as the Mastra adapter: never forward arbitrary
157
+ // auth-object properties down the analytics pipeline.
158
+ const authInfo = {};
159
+ if (typeof session.token === "string")
160
+ authInfo.token = session.token;
161
+ if (typeof session.clientId === "string")
162
+ authInfo.clientId = session.clientId;
163
+ if (typeof session.apiKey === "string")
164
+ authInfo.apiKey = session.apiKey;
165
+ if (typeof session.principalId === "string") {
166
+ authInfo.principalId = session.principalId;
167
+ }
168
+ if (Object.keys(authInfo).length > 0)
169
+ result.authInfo = authInfo;
170
+ }
171
+ return Object.keys(result).length > 0 ? result : undefined;
172
+ };
173
+ exports.defaultFastmcpResolveExtra = defaultFastmcpResolveExtra;
174
+ // fastmcp telemetry mode, resolved once per tool at wrap time. Schemas are
175
+ // never decorated (see module comment), so "injected" here means only:
176
+ // strip-and-export a `telemetry` argument if one reaches `execute`.
177
+ const resolveFastmcpToolMode = (parameters, config) => {
178
+ const owned = (0, schema_js_1.schemaDeclaresTelemetry)(parameters)
179
+ || (0, schema_js_1.schemaDeclaresTelemetry)(standardSchemaJson(parameters));
180
+ if (owned)
181
+ return "owned";
182
+ return (0, schema_js_1.isCaptureEnabled)(config) ? "injected" : "scrub";
183
+ };
184
+ // fastmcp's `jsonSchemaAdapter` (and any Standard JSON Schema-extension
185
+ // schema) carries the JSON Schema it was built from at
186
+ // `~standard.jsonSchema.input()` — the same object `schemaDeclaresTelemetry`
187
+ // already understands.
188
+ const standardSchemaJson = (parameters) => {
189
+ if (!(0, utils_js_1.isRecord)(parameters))
190
+ return undefined;
191
+ const standard = parameters["~standard"];
192
+ if (!(0, utils_js_1.isRecord)(standard))
193
+ return undefined;
194
+ const jsonSchema = standard.jsonSchema;
195
+ if (!(0, utils_js_1.isRecord)(jsonSchema) || typeof jsonSchema.input !== "function") {
196
+ return undefined;
197
+ }
198
+ try {
199
+ return jsonSchema.input();
200
+ }
201
+ catch {
202
+ return undefined;
203
+ }
204
+ };
205
+ // ─── Tool wrapping ──────────────────────────────────────────────────────────
206
+ const wrapFastmcpTool = (tool, state, runtime, resolveExtra) => {
207
+ if (typeof tool?.execute !== "function")
208
+ return tool;
209
+ const originalExecute = tool.execute;
210
+ if (originalExecute[WRAPPED_EXECUTE])
211
+ return tool;
212
+ const toolName = tool.name;
213
+ const mode = resolveFastmcpToolMode(tool.parameters, state.config);
214
+ state.toolModes.set(toolName, mode);
215
+ const wrappedExecute = (args, context) => {
216
+ const base = (0, exports.defaultFastmcpResolveExtra)(context);
217
+ const override = resolveExtra?.(context);
218
+ const extra = (0, utils_js_1.mergeRequestExtra)(base, override);
219
+ const headers = extra?.requestInfo?.headers;
220
+ // Session-id ladder (falling priority):
221
+ // 1. An explicit `resolveExtra` sessionId — the user override.
222
+ // 2. The X-Armature-Session-Seed header, when headers are reachable
223
+ // through `context.session.headers` / `resolveExtra`.
224
+ // 3. `context.sessionId` — the Mcp-Session-Id fastmcp surfaces (HTTP
225
+ // transports; stateful mode mints it, stateless echoes the client's).
226
+ // 4. An `mcp-session-id` value inside reachable headers, then — only
227
+ // when NO headers are reachable and the transport is not known to be
228
+ // HTTP — the stdio process-scoped id (both rungs live in
229
+ // recorder-core's resolveSessionId).
230
+ // 5. undefined — the event ships with a null hint and ingest buckets it.
231
+ const seed = trimOrUndefined((0, utils_js_1.headerValue)(headers, exports.FASTMCP_SESSION_SEED_HEADER));
232
+ const sessionId = override?.sessionId ?? seed ?? base?.sessionId;
233
+ // `{}` (not undefined) when the transport is known to be HTTP: recorder-
234
+ // core's stdio fallback keys on "no headers at all", and a long-lived HTTP
235
+ // server must not glue its anonymous sessions to one process id.
236
+ const effectiveHeaders = headers ?? (runtime.assumeHttp ? {} : undefined);
237
+ const clientInfo = clientInfoFromContext(context);
238
+ return state.core.instrumentToolCall({
239
+ name: toolName,
240
+ args,
241
+ telemetryMode: state.toolModes.get(toolName) ?? mode,
242
+ ctx: context,
243
+ ...(extra !== undefined ? { extra } : {}),
244
+ ...(sessionId !== undefined ? { sessionId } : {}),
245
+ ...(effectiveHeaders !== undefined ? { headers: effectiveHeaders } : {}),
246
+ ...(extra?.authInfo !== undefined ? { authInfo: extra.authInfo } : {}),
247
+ ...(clientInfo !== undefined ? { clientInfo } : {}),
248
+ // Deliberately NOT forwarding `context.requestId` as the event request
249
+ // id: it is client-supplied `_meta` data, and the contract (see
250
+ // TELEMETRY-CONTRACT.md, "tool_call request-id normalization") wants a
251
+ // freshly minted per-call id, not a transport-controlled seed.
252
+ },
253
+ // fastmcp calls execute(undefined, context) for tools without
254
+ // `parameters`; extractTelemetryArguments passes non-records through
255
+ // untouched, so `strippedArgs` is exactly what fastmcp supplied then.
256
+ (strippedArgs) => originalExecute(strippedArgs, context));
257
+ };
258
+ wrappedExecute[WRAPPED_EXECUTE] = true;
259
+ return { ...tool, execute: wrappedExecute };
260
+ };
261
+ function withFastmcpAnalytics(toolOrTools, options) {
262
+ const state = recorderStateFor(options);
263
+ const runtime = {
264
+ assumeHttp: options?.transport === "httpStream",
265
+ };
266
+ if (Array.isArray(toolOrTools)) {
267
+ return toolOrTools.map((tool) => wrapFastmcpTool(tool, state, runtime, options?.resolveExtra));
268
+ }
269
+ return wrapFastmcpTool(toolOrTools, state, runtime, options?.resolveExtra);
270
+ }
271
+ // Mirrors fastmcp's own `#parseRuntimeConfig` precedence exactly:
272
+ // `start` options → `--transport` CLI arg (accepting the `http-stream` alias)
273
+ // → `FASTMCP_TRANSPORT` env → "stdio".
274
+ const sniffFastmcpTransport = (startOptions) => {
275
+ const explicit = (0, utils_js_1.isRecord)(startOptions) ? startOptions.transportType : undefined;
276
+ if (explicit === "httpStream" || explicit === "stdio")
277
+ return explicit;
278
+ const args = typeof process !== "undefined" ? process.argv.slice(2) : [];
279
+ const index = args.findIndex((arg) => arg === "--transport");
280
+ const cliValue = index !== -1 ? args[index + 1] : undefined;
281
+ const fromCli = cliValue === "http-stream" ? "httpStream" : cliValue;
282
+ const fromEnv = typeof process !== "undefined"
283
+ ? process.env.FASTMCP_TRANSPORT
284
+ : undefined;
285
+ const resolved = fromCli || fromEnv || "stdio";
286
+ return resolved === "httpStream" ? "httpStream" : "stdio";
287
+ };
288
+ /**
289
+ * Instrument a `FastMCP` server instance-level (structurally typed — no
290
+ * import of the fastmcp package): every tool passed to `addTool`/`addTools`
291
+ * AFTER this call is wrapped with `withFastmcpAnalytics` semantics, and
292
+ * `server.start(...)` is sniffed for the real transport so httpStream
293
+ * deployments automatically opt out of the stdio session fallback.
294
+ *
295
+ * Limitation, stated rather than papered over: fastmcp keeps already-added
296
+ * tools in a private `#tools` field this function cannot reach — call it
297
+ * BEFORE `addTool`, or wrap earlier tools with `withFastmcpAnalytics`
298
+ * (pre-wrapped tools pass through here without double-recording). Returns the
299
+ * same (mutated) server; instrumenting twice is a no-op.
300
+ */
301
+ const instrumentFastMCP = (server, options) => {
302
+ if (server === null || typeof server !== "object")
303
+ return server;
304
+ const internals = server;
305
+ if (internals[WRAPPED_SERVER])
306
+ return server;
307
+ if (typeof internals.addTool !== "function")
308
+ return server;
309
+ Object.defineProperty(internals, WRAPPED_SERVER, {
310
+ value: true,
311
+ configurable: true,
312
+ });
313
+ const state = recorderStateFor(options);
314
+ const runtime = {
315
+ assumeHttp: options?.transport === "httpStream",
316
+ };
317
+ const wrap = (tool) => (0, utils_js_1.isRecord)(tool)
318
+ ? wrapFastmcpTool(tool, state, runtime, options?.resolveExtra)
319
+ : tool;
320
+ const originalAddTool = internals.addTool;
321
+ Object.defineProperty(internals, "addTool", {
322
+ configurable: true,
323
+ writable: true,
324
+ value: function instrumentedAddTool(...args) {
325
+ return originalAddTool.apply(this, [wrap(args[0]), ...args.slice(1)]);
326
+ },
327
+ });
328
+ // fastmcp's addTools does NOT delegate to addTool (both mutate `#tools`
329
+ // directly), so it needs its own wrap.
330
+ const originalAddTools = internals.addTools;
331
+ if (typeof originalAddTools === "function") {
332
+ Object.defineProperty(internals, "addTools", {
333
+ configurable: true,
334
+ writable: true,
335
+ value: function instrumentedAddTools(...args) {
336
+ const tools = Array.isArray(args[0]) ? args[0].map(wrap) : args[0];
337
+ return originalAddTools.apply(this, [tools, ...args.slice(1)]);
338
+ },
339
+ });
340
+ }
341
+ const originalStart = internals.start;
342
+ if (typeof originalStart === "function") {
343
+ Object.defineProperty(internals, "start", {
344
+ configurable: true,
345
+ writable: true,
346
+ value: function instrumentedStart(...args) {
347
+ // The started transport is ground truth; it overrides the
348
+ // `transport` option hint. `connect(transport)` (the in-process/test
349
+ // path) never runs this and keeps the stdio-like default.
350
+ runtime.assumeHttp = sniffFastmcpTransport(args[0]) === "httpStream";
351
+ return originalStart.apply(this, args);
352
+ },
353
+ });
354
+ }
355
+ return server;
356
+ };
357
+ exports.instrumentFastMCP = instrumentFastMCP;
358
+ var emit_js_2 = require("./emit.js");
359
+ Object.defineProperty(exports, "defaultMcpAnalyticsConfig", { enumerable: true, get: function () { return emit_js_2.defaultMcpAnalyticsConfig; } });
@@ -64,32 +64,7 @@ const defaultMastraResolveExtra = (mastraContext) => {
64
64
  return Object.keys(result).length > 0 ? result : undefined;
65
65
  };
66
66
  exports.defaultMastraResolveExtra = defaultMastraResolveExtra;
67
- const mergeExtra = (base, override) => {
68
- if (!base)
69
- return override;
70
- if (!override)
71
- return base;
72
- return {
73
- ...base,
74
- ...override,
75
- ...(base.requestInfo || override.requestInfo
76
- ? {
77
- requestInfo: {
78
- ...(base.requestInfo ?? {}),
79
- ...(override.requestInfo ?? {}),
80
- },
81
- }
82
- : {}),
83
- ...(base.authInfo || override.authInfo
84
- ? {
85
- authInfo: {
86
- ...(base.authInfo ?? {}),
87
- ...(override.authInfo ?? {}),
88
- },
89
- }
90
- : {}),
91
- };
92
- };
67
+ const mergeExtra = utils_js_1.mergeRequestExtra;
93
68
  const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
94
69
  if (typeof tool?.execute !== "function") {
95
70
  return tool;
@@ -0,0 +1,31 @@
1
+ import type { McpAnalyticsConfig } from "./types.js";
2
+ export type McpRouteHandler = (request: Request, ...rest: unknown[]) => Promise<Response>;
3
+ /** Drain the analytics pipeline tied to a config object (or the default config). */
4
+ export declare const flushMcpHandlerAnalytics: (config?: McpAnalyticsConfig) => Promise<void>;
5
+ /**
6
+ * Wrap the handler returned by mcp-handler's `createMcpHandler` so MCP client
7
+ * and session identity survive its stateless transport. Pass the SAME config
8
+ * object here and to the `withMcpAnalytics` call inside your initialize
9
+ * callback so both share one delivery pipeline configuration:
10
+ *
11
+ * ~~~ts
12
+ * const handler = withMcpHandlerAnalytics(
13
+ * createMcpHandler((server) => {
14
+ * withMcpAnalytics(analyticsConfig, () => {
15
+ * server.tool(...); // instrumented by the package root's patch
16
+ * return server;
17
+ * });
18
+ * }),
19
+ * analyticsConfig,
20
+ * );
21
+ * export { handler as POST };
22
+ * ~~~
23
+ *
24
+ * Serverless note: `createMcpHandler` runs the initialize callback PER
25
+ * REQUEST, so use `delivery: "await"` (or a `schedule`/`waitUntil` hook) —
26
+ * a per-request background queue may be frozen before it delivers.
27
+ */
28
+ export declare const withMcpHandlerAnalytics: <H extends McpRouteHandler>(handler: H, config?: McpAnalyticsConfig) => H;
29
+ export type { AnalyticsRecorderCore } from "./recorder-core.js";
30
+ export type { McpAnalyticsConfig, McpClientInfo } from "./types.js";
31
+ export { defaultMcpAnalyticsConfig } from "./emit.js";
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultMcpAnalyticsConfig = exports.withMcpHandlerAnalytics = exports.flushMcpHandlerAnalytics = void 0;
4
+ const recorder_core_js_1 = require("./recorder-core.js");
5
+ const emit_js_1 = require("./emit.js");
6
+ const stateless_http_js_1 = require("./stateless-http.js");
7
+ const utils_js_1 = require("./utils.js");
8
+ const SESSION_ID_HEADER = "mcp-session-id";
9
+ // Keyed on the config object so every request shares one recorder (privacy
10
+ // queue + session_init dedupe) — hoist the config, same contract as the v2
11
+ // adapter. A fresh config per call still converges at ingest (session_init
12
+ // event ids are content-addressed per (actor, session)).
13
+ const recorderStatesByConfig = new WeakMap();
14
+ let defaultRecorderState;
15
+ const recorderStateFor = (config) => {
16
+ if (config === undefined || config === emit_js_1.defaultMcpAnalyticsConfig) {
17
+ defaultRecorderState ??= { core: (0, recorder_core_js_1.createAnalyticsRecorderCore)(emit_js_1.defaultMcpAnalyticsConfig) };
18
+ return defaultRecorderState;
19
+ }
20
+ let state = recorderStatesByConfig.get(config);
21
+ if (!state) {
22
+ state = { core: (0, recorder_core_js_1.createAnalyticsRecorderCore)(config) };
23
+ recorderStatesByConfig.set(config, state);
24
+ }
25
+ return state;
26
+ };
27
+ /** Drain the analytics pipeline tied to a config object (or the default config). */
28
+ const flushMcpHandlerAnalytics = (config) => {
29
+ return recorderStateFor(config).core.flush();
30
+ };
31
+ exports.flushMcpHandlerAnalytics = flushMcpHandlerAnalytics;
32
+ const trimOrUndefined = (value) => {
33
+ if (typeof value !== "string")
34
+ return undefined;
35
+ const trimmed = value.trim();
36
+ return trimmed.length > 0 ? trimmed : undefined;
37
+ };
38
+ // Full-fidelity clientInfo from the initialize body itself (name, version,
39
+ // protocolVersion, capabilities) — richer than what the minted id can carry,
40
+ // so the session_init recorded at initialize matches what a stateful v1
41
+ // deployment would report.
42
+ const clientInfoFromInitializeBody = (body) => {
43
+ const messages = Array.isArray(body) ? body : [body];
44
+ const initialize = messages.find((message) => (0, utils_js_1.isRecord)(message) && message.method === "initialize");
45
+ const params = (0, utils_js_1.isRecord)(initialize?.params) ? initialize.params : undefined;
46
+ if (!params)
47
+ return undefined;
48
+ const info = (0, utils_js_1.isRecord)(params.clientInfo) ? params.clientInfo : undefined;
49
+ const name = trimOrUndefined(info?.name);
50
+ if (name === undefined)
51
+ return undefined;
52
+ const version = trimOrUndefined(info?.version);
53
+ const protocolVersion = trimOrUndefined(params.protocolVersion);
54
+ return {
55
+ name,
56
+ ...(version !== undefined ? { version } : {}),
57
+ ...(protocolVersion !== undefined ? { protocolVersion } : {}),
58
+ capabilities: (0, utils_js_1.isRecord)(params.capabilities) ? params.capabilities : null,
59
+ };
60
+ };
61
+ const withSessionIdHeader = (response, sessionId) => {
62
+ if (response.headers.get(SESSION_ID_HEADER))
63
+ return response;
64
+ const headers = new Headers(response.headers);
65
+ headers.set(SESSION_ID_HEADER, sessionId);
66
+ return new Response(response.body, {
67
+ status: response.status,
68
+ statusText: response.statusText,
69
+ headers,
70
+ });
71
+ };
72
+ /**
73
+ * Wrap the handler returned by mcp-handler's `createMcpHandler` so MCP client
74
+ * and session identity survive its stateless transport. Pass the SAME config
75
+ * object here and to the `withMcpAnalytics` call inside your initialize
76
+ * callback so both share one delivery pipeline configuration:
77
+ *
78
+ * ~~~ts
79
+ * const handler = withMcpHandlerAnalytics(
80
+ * createMcpHandler((server) => {
81
+ * withMcpAnalytics(analyticsConfig, () => {
82
+ * server.tool(...); // instrumented by the package root's patch
83
+ * return server;
84
+ * });
85
+ * }),
86
+ * analyticsConfig,
87
+ * );
88
+ * export { handler as POST };
89
+ * ~~~
90
+ *
91
+ * Serverless note: `createMcpHandler` runs the initialize callback PER
92
+ * REQUEST, so use `delivery: "await"` (or a `schedule`/`waitUntil` hook) —
93
+ * a per-request background queue may be frozen before it delivers.
94
+ */
95
+ const withMcpHandlerAnalytics = (handler, config) => {
96
+ const state = recorderStateFor(config);
97
+ const wrapped = async (request, ...rest) => {
98
+ let session;
99
+ let body;
100
+ if (request.method === "POST") {
101
+ try {
102
+ const raw = await request.clone().text();
103
+ body = raw ? JSON.parse(raw) : undefined;
104
+ session = (0, stateless_http_js_1.resolveStatelessHttpSession)({ body, headers: request.headers });
105
+ }
106
+ catch {
107
+ session = undefined;
108
+ }
109
+ }
110
+ const response = await handler(request, ...rest);
111
+ if (session?.isInitialize && response.ok) {
112
+ try {
113
+ await state.core.recordSessionInit({
114
+ sessionId: session.sessionId,
115
+ headers: request.headers,
116
+ clientInfo: clientInfoFromInitializeBody(body),
117
+ extra: {
118
+ sessionId: session.sessionId,
119
+ requestInfo: { headers: request.headers },
120
+ },
121
+ });
122
+ }
123
+ catch {
124
+ // Recording is best-effort; never break the MCP response over it.
125
+ }
126
+ return withSessionIdHeader(response, session.sessionId);
127
+ }
128
+ // Echo an id the client is already carrying, so it keeps carrying it.
129
+ const echoed = request.headers.get(SESSION_ID_HEADER)?.trim();
130
+ if (echoed)
131
+ return withSessionIdHeader(response, echoed);
132
+ return response;
133
+ };
134
+ return wrapped;
135
+ };
136
+ exports.withMcpHandlerAnalytics = withMcpHandlerAnalytics;
137
+ var emit_js_2 = require("./emit.js");
138
+ Object.defineProperty(exports, "defaultMcpAnalyticsConfig", { enumerable: true, get: function () { return emit_js_2.defaultMcpAnalyticsConfig; } });
@@ -0,0 +1,24 @@
1
+ import type { ExtractedToolArguments, InstrumentToolCallEvent, McpAnalyticsConfig, McpClientInfo, RecordSessionInitEvent, RecordToolCallEvent, TelemetryMode, ToolCallHandler } from "./types.js";
2
+ export type RecorderCoreHooks = {
3
+ /**
4
+ * Session-scoped client identity lookup consulted when an event carries no
5
+ * explicit clientInfo. The v1 recorder wires the `_onrequest`-patch cache
6
+ * here; the v2 adapter passes clientInfo per event (per-request envelope)
7
+ * and needs no hook. The identity-bearing stateless session id parse runs
8
+ * as a built-in last resort either way.
9
+ */
10
+ clientInfoForSessionId?: (sessionId: string) => McpClientInfo | undefined;
11
+ /**
12
+ * True when the named tool owns its `telemetry` input field (mode "owned",
13
+ * TELEMETRY-CONTRACT.md): supplied telemetry must never be exported.
14
+ */
15
+ isToolTelemetryOwned?: (name: string) => boolean;
16
+ };
17
+ export type AnalyticsRecorderCore = {
18
+ extractTelemetry: (args: unknown, mode?: TelemetryMode) => ExtractedToolArguments;
19
+ recordToolCall: (event: RecordToolCallEvent) => Promise<void>;
20
+ recordSessionInit: (event: RecordSessionInitEvent) => Promise<void>;
21
+ instrumentToolCall: <T>(event: InstrumentToolCallEvent, handler: ToolCallHandler<T>) => Promise<T>;
22
+ flush: () => Promise<void>;
23
+ };
24
+ export declare const createAnalyticsRecorderCore: (config?: McpAnalyticsConfig, hooks?: RecorderCoreHooks) => AnalyticsRecorderCore;