@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.
package/dist/cjs/v2.js ADDED
@@ -0,0 +1,630 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultMcpAnalyticsConfig = exports.wrapMcpHandler = exports.instrumentedFactory = exports.withMcpAnalytics = exports.flushMcpAnalytics = exports.conversationIdFromBaggage = exports.SESSION_SEED_HEADER = void 0;
4
+ const server_1 = require("@modelcontextprotocol/server");
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 events_js_1 = require("./events.js");
9
+ const sanitize_js_1 = require("./sanitize.js");
10
+ const utils_js_1 = require("./utils.js");
11
+ const stdio_session_js_1 = require("./stdio-session.js");
12
+ const stateless_http_js_1 = require("./stateless-http.js");
13
+ // Adapter for the v2 MCP TypeScript SDK (@modelcontextprotocol/server 2.x,
14
+ // protocol revision 2026-07-28). The v2 protocol is stateless: there is no
15
+ // initialize handshake and no Mcp-Session-Id — client identity travels
16
+ // per-request in the reserved `_meta` envelope, and session identity has to be
17
+ // derived per request (see the ladder in `resolveV2SessionId`). This module
18
+ // therefore never loads the v1 `@modelcontextprotocol/sdk` package: both peers
19
+ // are optional, and a v2-only install imports `@armature-tech/mcp-analytics/v2`
20
+ // exclusively (the package root still requires the v1 SDK at runtime).
21
+ /** Header a caller can set to pin the analytics session id (rung 2 of the ladder). */
22
+ exports.SESSION_SEED_HEADER = "x-armature-session-seed";
23
+ const REQUEST_META_MAX_BYTES = 4 * 1024;
24
+ // Wrapped callbacks are tagged so re-instrumenting a server (or re-running
25
+ // `withMcpAnalytics` over a factory-produced instance) can never double-wrap
26
+ // and double-record a tool.
27
+ const WRAPPED_CALLBACK = Symbol.for("armature.mcpAnalytics.v2.wrappedCallback");
28
+ // ─── Per-request capture ────────────────────────────────────────────────────
29
+ /**
30
+ * Parse `gen_ai.conversation.id` out of a W3C `baggage` value: comma-separated
31
+ * `key=value` list entries, each optionally carrying `;`-separated properties,
32
+ * values URL-decoded. Rung 1 of the session-id ladder.
33
+ */
34
+ const conversationIdFromBaggage = (baggage) => {
35
+ if (typeof baggage !== "string")
36
+ return undefined;
37
+ for (const entry of baggage.split(",")) {
38
+ const member = entry.split(";")[0]?.trim();
39
+ if (!member)
40
+ continue;
41
+ const separator = member.indexOf("=");
42
+ if (separator <= 0)
43
+ continue;
44
+ if (member.slice(0, separator).trim() !== "gen_ai.conversation.id")
45
+ continue;
46
+ const raw = member.slice(separator + 1).trim();
47
+ if (!raw)
48
+ continue;
49
+ try {
50
+ const decoded = decodeURIComponent(raw).trim();
51
+ return decoded.length > 0 ? decoded : undefined;
52
+ }
53
+ catch {
54
+ return raw;
55
+ }
56
+ }
57
+ return undefined;
58
+ };
59
+ exports.conversationIdFromBaggage = conversationIdFromBaggage;
60
+ const trimOrUndefined = (value) => {
61
+ if (typeof value !== "string")
62
+ return undefined;
63
+ const trimmed = value.trim();
64
+ return trimmed.length > 0 ? trimmed : undefined;
65
+ };
66
+ // The reserved io.modelcontextprotocol/* keys are lifted out of params._meta
67
+ // into ctx.mcpReq.envelope before handlers run. The published 2.0.0 d.ts
68
+ // declares `type RequestMetaEnvelope = {}`, so envelope access needs the
69
+ // record cast below; the runtime object is keyed by the full reserved strings
70
+ // (the exported *_META_KEY constants).
71
+ const clientInfoFromEnvelope = (envelope) => {
72
+ if (!envelope)
73
+ return undefined;
74
+ const rawInfo = envelope[server_1.CLIENT_INFO_META_KEY];
75
+ const info = (0, utils_js_1.isRecord)(rawInfo) ? rawInfo : undefined;
76
+ // clientInfo is OPTIONAL per the final 2026-07-28 spec (a SHOULD): the
77
+ // required per-request pair is protocolVersion + clientCapabilities, so a
78
+ // missing clientInfo is a legitimate steady state — never assume it.
79
+ const name = trimOrUndefined(info?.name);
80
+ const version = trimOrUndefined(info?.version);
81
+ const protocolVersion = trimOrUndefined(envelope[server_1.PROTOCOL_VERSION_META_KEY]);
82
+ const rawCapabilities = envelope[server_1.CLIENT_CAPABILITIES_META_KEY];
83
+ const capabilities = (0, utils_js_1.isRecord)(rawCapabilities) ? rawCapabilities : undefined;
84
+ if (name === undefined
85
+ && version === undefined
86
+ && protocolVersion === undefined
87
+ && capabilities === undefined) {
88
+ return undefined;
89
+ }
90
+ return {
91
+ ...(name !== undefined ? { name } : {}),
92
+ ...(version !== undefined ? { version } : {}),
93
+ ...(protocolVersion !== undefined ? { protocolVersion } : {}),
94
+ capabilities: capabilities ?? null,
95
+ };
96
+ };
97
+ // Request `_meta`, captured into tool_call metadata as `request_meta`, capped
98
+ // at 4KB. Note the reserved envelope keys are already lifted OUT of `_meta` by
99
+ // the SDK before handlers run, so this is typically the W3C trace slots
100
+ // (`traceparent`, `tracestate`, `baggage` keep their bare names and are NOT
101
+ // lifted) plus any custom keys the client sent. Custom keys are client-
102
+ // controlled free text, so the capture runs through the same
103
+ // preview-preparation pipeline as tool inputs/results — base64/binary
104
+ // sanitization plus built-in secret redaction (when enabled) — before the cap
105
+ // is applied; previously raw `_meta` under 4KB shipped verbatim.
106
+ const capRequestMeta = (meta, redactSecrets) => {
107
+ if (!meta || Object.keys(meta).length === 0)
108
+ return {};
109
+ const prepared = (0, sanitize_js_1.prepareForPreview)(meta, undefined, { redactSecrets });
110
+ const serialized = (0, utils_js_1.stringifyPreview)(prepared);
111
+ const { value, truncated } = (0, utils_js_1.truncateUtf8)(serialized, REQUEST_META_MAX_BYTES);
112
+ return truncated
113
+ ? { request_meta: value, request_meta_truncated: true }
114
+ : { request_meta: prepared };
115
+ };
116
+ // Never let an integrator-supplied metadata hook break a tool call (or its
117
+ // recording): a throw yields no extra keys, same as returning undefined.
118
+ const safeMetadataHook = (hook, ctx) => {
119
+ if (typeof hook !== "function")
120
+ return undefined;
121
+ try {
122
+ const extra = hook(ctx);
123
+ return (0, utils_js_1.isRecord)(extra) ? extra : undefined;
124
+ }
125
+ catch {
126
+ return undefined;
127
+ }
128
+ };
129
+ const captureV2Request = (ctxValue, defaults, config, options) => {
130
+ const ctx = (0, utils_js_1.isRecord)(ctxValue) ? ctxValue : {};
131
+ const mcpReq = (0, utils_js_1.isRecord)(ctx.mcpReq) ? ctx.mcpReq : undefined;
132
+ const envelope = (0, utils_js_1.isRecord)(mcpReq?.envelope)
133
+ ? mcpReq.envelope
134
+ : undefined;
135
+ const meta = (0, utils_js_1.isRecord)(mcpReq?._meta)
136
+ ? mcpReq._meta
137
+ : undefined;
138
+ const http = (0, utils_js_1.isRecord)(ctx.http) ? ctx.http : undefined;
139
+ const req = (0, utils_js_1.isRecord)(http?.req) ? http.req : undefined;
140
+ const reqHeaders = req?.headers;
141
+ const headers = ((reqHeaders instanceof Headers || (0, utils_js_1.isRecord)(reqHeaders))
142
+ ? reqHeaders
143
+ : undefined) ?? defaults?.headers;
144
+ const authInfo = ((0, utils_js_1.isRecord)(http?.authInfo) ? http.authInfo : undefined)
145
+ ?? defaults?.authInfo;
146
+ const clientInfo = clientInfoFromEnvelope(envelope);
147
+ // Session-id ladder (falling priority):
148
+ // 1. `gen_ai.conversation.id` from the `baggage` _meta slot — the agent's
149
+ // own conversation identity, when the caller propagates it.
150
+ // 2. The X-Armature-Session-Seed request header. When the request ALSO
151
+ // echoes an Mcp-Session-Id that was minted FROM that seed (the
152
+ // `wrapMcpHandler` legacy flow embeds the seed uuid in the
153
+ // `mcp_<name>_v_<version>_<uuid>` id), the two name the same session,
154
+ // so the richer identity-bearing id wins the rung — otherwise the two
155
+ // headers would split one legacy conversation into two sessions.
156
+ // 3. Legacy-era session identity: `ctx.sessionId` (set only by sessionful
157
+ // legacy transports; under `createMcpHandler` the legacy leg is
158
+ // stateless and mints no Mcp-Session-Id, so it rarely fires there),
159
+ // then an `Mcp-Session-Id` REQUEST header a legacy client echoes —
160
+ // which is what `wrapMcpHandler` mints on legacy initialize responses.
161
+ // 4. The stdio process-scoped id, only when there is no HTTP context at
162
+ // all (neither on the handler ctx nor on the factory request context).
163
+ // 5. undefined — the event ships with a null hint and ingest buckets it.
164
+ const seed = headers
165
+ ? trimOrUndefined((0, utils_js_1.headerValue)(headers, exports.SESSION_SEED_HEADER))
166
+ : undefined;
167
+ const echoedSessionId = headers
168
+ ? trimOrUndefined((0, utils_js_1.headerValue)(headers, "mcp-session-id"))
169
+ : undefined;
170
+ const seedRung = seed !== undefined
171
+ && echoedSessionId !== undefined
172
+ && echoedSessionId.toLowerCase().endsWith(`_${seed.toLowerCase()}`)
173
+ ? echoedSessionId
174
+ : seed;
175
+ const sessionId = (0, exports.conversationIdFromBaggage)(meta?.[server_1.BAGGAGE_META_KEY])
176
+ ?? seedRung
177
+ ?? trimOrUndefined(ctx.sessionId)
178
+ ?? echoedSessionId
179
+ ?? (http == null && defaults?.hasHttpRequest !== true
180
+ ? (0, stdio_session_js_1.processScopedSessionId)()
181
+ : undefined);
182
+ const extra = {
183
+ ...(sessionId !== undefined ? { sessionId } : {}),
184
+ ...(authInfo !== undefined ? { authInfo } : {}),
185
+ ...(headers !== undefined ? { requestInfo: { headers } } : {}),
186
+ };
187
+ // The User-Agent header, so v2 sessions keep the per-session harness signal
188
+ // v1 recorded (ingest's extractHarness reads metadata.user_agent). Captured
189
+ // from the handler ctx's HTTP request headers with the factory-context
190
+ // requestInfo fallback (the `headers` chain above), and stamped on
191
+ // tool_call metadata too — session_init picks it up from
192
+ // extra.requestInfo.headers in events.ts.
193
+ const userAgent = headers
194
+ ? trimOrUndefined((0, utils_js_1.headerValue)(headers, "user-agent"))
195
+ : undefined;
196
+ // Client identity is per-request on the 2026-07-28 revision, so it is
197
+ // stamped on every tool_call event too — not only session_init — using the
198
+ // same metadata keys. Contract keys still win on collision (events.ts).
199
+ const metadataExtra = {
200
+ // Which protocol leg served this request: a lifted `_meta` envelope
201
+ // exists only on 2026-07-28 ("modern") requests; everything else came
202
+ // through the legacy leg.
203
+ protocol_era: envelope !== undefined ? "modern" : "legacy",
204
+ ...(clientInfo?.name !== undefined ? { client_name: clientInfo.name } : {}),
205
+ ...(clientInfo?.version !== undefined ? { client_version: clientInfo.version } : {}),
206
+ ...(clientInfo?.protocolVersion !== undefined
207
+ ? { protocol_version: clientInfo.protocolVersion }
208
+ : {}),
209
+ // Per-request clientCapabilities, same key and byte cap as session_init
210
+ // (over-cap objects are dropped to null, never truncated into bad JSON).
211
+ ...((0, utils_js_1.isRecord)(clientInfo?.capabilities)
212
+ ? { capabilities: (0, events_js_1.capCapabilities)(clientInfo.capabilities) }
213
+ : {}),
214
+ ...(userAgent !== undefined ? { user_agent: userAgent } : {}),
215
+ ...capRequestMeta(meta, config.armature?.redactSecrets !== false),
216
+ // Integrator hook last: its keys win over the adapter-derived keys above
217
+ // (contract keys still win over everything, events.ts).
218
+ ...(safeMetadataHook(options?.metadata, ctxValue) ?? {}),
219
+ };
220
+ return {
221
+ ...(sessionId !== undefined ? { sessionId } : {}),
222
+ ...(clientInfo !== undefined ? { clientInfo } : {}),
223
+ extra,
224
+ ...(Object.keys(metadataExtra).length > 0 ? { metadataExtra } : {}),
225
+ };
226
+ };
227
+ // ─── Recorder state (shared across per-request server instances) ────────────
228
+ const createV2RecorderState = (config) => {
229
+ const toolModes = new Map();
230
+ const core = (0, recorder_core_js_1.createAnalyticsRecorderCore)(config, {
231
+ isToolTelemetryOwned: (name) => toolModes.get(name) === "owned",
232
+ });
233
+ return { core, config, toolModes };
234
+ };
235
+ // `createMcpHandler` runs its factory PER REQUEST (both eras), so there is no
236
+ // long-lived server instance to hang state off. Session-init dedupe and the
237
+ // privacy queue must outlive the server: they are keyed on the CONFIG object
238
+ // (WeakMap), so hoisting the config — the natural shape — shares one recorder
239
+ // across every request. A per-call fresh config object still converges at
240
+ // ingest (session_init event ids are content-addressed), it just re-emits.
241
+ const recorderStatesByConfig = new WeakMap();
242
+ let defaultRecorderState;
243
+ const recorderStateFor = (config) => {
244
+ if (config === undefined || config === emit_js_1.defaultMcpAnalyticsConfig) {
245
+ defaultRecorderState ??= createV2RecorderState(emit_js_1.defaultMcpAnalyticsConfig);
246
+ return defaultRecorderState;
247
+ }
248
+ let state = recorderStatesByConfig.get(config);
249
+ if (!state) {
250
+ state = createV2RecorderState(config);
251
+ recorderStatesByConfig.set(config, state);
252
+ }
253
+ return state;
254
+ };
255
+ /**
256
+ * Drain the analytics pipeline tied to a config object (or the default
257
+ * config). Call before process exit / serverless freeze when not using
258
+ * `delivery: "await"` or a `schedule` hook.
259
+ */
260
+ const flushMcpAnalytics = (config) => {
261
+ return recorderStateFor(config).core.flush();
262
+ };
263
+ exports.flushMcpAnalytics = flushMcpAnalytics;
264
+ // ─── Tool wrapping ──────────────────────────────────────────────────────────
265
+ // v2 telemetry mode, resolved once per tool at wrap time — always against the
266
+ // tool's ORIGINAL schema, before any declareTelemetry decoration runs, so a
267
+ // telemetry property the ADAPTER added can never flip the tool to
268
+ // customer-owned ("owned" is reserved for schemas whose author declared
269
+ // telemetry themselves). By default the v2 adapter does not decorate input
270
+ // schemas, and "injected" means only: strip-and-export a `telemetry` argument
271
+ // if the client sends one. With `declareTelemetry: true` the advertised
272
+ // schema is additionally rebuilt to carry the telemetry property (see
273
+ // decorateAdvertisedSchema).
274
+ const resolveToolMode = (server, name, inputSchema, config) => {
275
+ let owned = false;
276
+ try {
277
+ // The SDK's own registration-time JSON conversion covers ANY Standard
278
+ // Schema (zod, arktype, valibot, fromJsonSchema); the structural check on
279
+ // the raw value is the fallback when the helper is absent or throws.
280
+ const json = typeof server.toolInputSchemaJson === "function"
281
+ ? server.toolInputSchemaJson(name)
282
+ : undefined;
283
+ owned = (0, schema_js_1.schemaDeclaresTelemetry)(json) || (0, schema_js_1.schemaDeclaresTelemetry)(inputSchema);
284
+ }
285
+ catch {
286
+ owned = (0, schema_js_1.schemaDeclaresTelemetry)(inputSchema);
287
+ }
288
+ if (owned)
289
+ return "owned";
290
+ return (0, schema_js_1.isCaptureEnabled)(config) ? "injected" : "scrub";
291
+ };
292
+ // Builds the declareTelemetry replacement schema for one tool, or undefined
293
+ // when the tool must stay undecorated. Mechanism (chosen after probing the
294
+ // SDK, see also V2AdapterOptions.declareTelemetry):
295
+ //
296
+ // 1. `server.toolInputSchemaJson(name)` yields the exact JSON Schema
297
+ // `tools/list` would advertise — the SDK's own registration-time
298
+ // conversion, covering any Standard Schema vendor (zod v4, arktype,
299
+ // valibot, fromJsonSchema) without this package converting anything
300
+ // itself. Schema-less tools yield the SDK's empty object schema.
301
+ // 2. The telemetry property is added to that JSON (byte-identical
302
+ // descriptions to v1 via createTelemetryJsonSchema). A top-level
303
+ // `additionalProperties: false` needs no lifting: JSON Schema applies it
304
+ // only to keys NOT in `properties`, so declaring `telemetry` makes it
305
+ // pass validation while every other unknown key is still rejected.
306
+ // 3. `fromJsonSchema` wraps the decorated JSON back into a Standard Schema
307
+ // whose `~standard.jsonSchema` returns it verbatim, and
308
+ // `RegisteredTool.update({ paramsSchema })` swaps it in — invalidating
309
+ // the SDK's memoized JSON so `tools/list`, the SEP-2243 pre-dispatch
310
+ // header validation, and the Ajv input validation (which all run BEFORE
311
+ // the analytics wrapper) uniformly see and accept `telemetry`. The
312
+ // wrapper then strips it, so the customer callback receives args that
313
+ // satisfy the original schema. Zod is bypassed entirely.
314
+ const decorateAdvertisedSchema = (server, name, config) => {
315
+ if (typeof server.toolInputSchemaJson !== "function")
316
+ return undefined;
317
+ try {
318
+ const json = server.toolInputSchemaJson(name);
319
+ if (!(0, utils_js_1.isRecord)(json))
320
+ return undefined;
321
+ // Only object roots can carry the property; a non-object `type` cannot be
322
+ // a valid MCP input schema anyway. (`type` may be absent on zod
323
+ // discriminated-union roots — those are object-shaped by construction.)
324
+ if (json.type !== undefined && json.type !== "object")
325
+ return undefined;
326
+ const properties = (0, utils_js_1.isRecord)(json.properties) ? json.properties : {};
327
+ if ("telemetry" in properties)
328
+ return undefined;
329
+ return (0, server_1.fromJsonSchema)({
330
+ ...json,
331
+ type: "object",
332
+ properties: { ...properties, telemetry: (0, schema_js_1.createTelemetryJsonSchema)(config) },
333
+ });
334
+ }
335
+ catch {
336
+ // Conversion or rebuild failure: leave the tool undecorated rather than
337
+ // risking its registration — strip-and-export still applies.
338
+ return undefined;
339
+ }
340
+ };
341
+ // Shallow snapshot of a tool result's envelope and its _meta, taken
342
+ // synchronously before the record pipeline runs: the v2 SDK stamps
343
+ // `io.modelcontextprotocol/serverInfo` into every 2026-era response's _meta
344
+ // AFTER the wrapped callback returns, so recording the live reference would
345
+ // capture a nondeterministically mutated object (the same race the Go SDK's
346
+ // -race build caught). The live object is still what the SDK receives.
347
+ const snapshotToolResult = (result) => {
348
+ if (!(0, utils_js_1.isRecord)(result))
349
+ return result;
350
+ const snapshot = { ...result };
351
+ if ((0, utils_js_1.isRecord)(result._meta))
352
+ snapshot._meta = { ...result._meta };
353
+ return snapshot;
354
+ };
355
+ const wrapToolCallback = (state, name,
356
+ // The SDK dispatches according to the REGISTERED schema — (args, ctx) when
357
+ // present, (ctx) when absent — while the original callback expects arguments
358
+ // per the schema the customer declared. The two differ when declareTelemetry
359
+ // adds a schema to a previously schema-less tool, so both flags are needed
360
+ // (same split as the v1 prototype patch in server.ts).
361
+ originalHasInputSchema, registeredHasInputSchema, originalCallback, defaults, options) => {
362
+ const wrapped = async (...callbackArgs) => {
363
+ const rawArgs = registeredHasInputSchema ? callbackArgs[0] : {};
364
+ const ctx = registeredHasInputSchema ? callbackArgs[1] : callbackArgs[0];
365
+ const capture = captureV2Request(ctx, defaults, state.config, options);
366
+ return state.core.instrumentToolCall({
367
+ name,
368
+ args: rawArgs,
369
+ telemetryMode: state.toolModes.get(name) ?? "injected",
370
+ ctx,
371
+ extra: capture.extra,
372
+ captureResult: snapshotToolResult,
373
+ ...(capture.sessionId !== undefined ? { sessionId: capture.sessionId } : {}),
374
+ ...(capture.clientInfo !== undefined ? { clientInfo: capture.clientInfo } : {}),
375
+ ...(capture.metadataExtra !== undefined
376
+ ? { metadataExtra: capture.metadataExtra }
377
+ : {}),
378
+ }, (strippedArgs) => originalHasInputSchema
379
+ ? originalCallback(strippedArgs, ctx)
380
+ : originalCallback(ctx));
381
+ };
382
+ wrapped[WRAPPED_CALLBACK] = true;
383
+ return wrapped;
384
+ };
385
+ const instrumentRegisteredTool = (state, server, name, tool, defaults, options) => {
386
+ const registered = tool;
387
+ if (typeof registered?.update !== "function"
388
+ || typeof registered?.handler !== "function") {
389
+ return;
390
+ }
391
+ const handler = registered.handler;
392
+ if (handler[WRAPPED_CALLBACK])
393
+ return;
394
+ // Mode is resolved against the ORIGINAL schema, before decoration — an
395
+ // adapter-added telemetry property must stay armature-owned (strip+export),
396
+ // never customer-owned.
397
+ const mode = resolveToolMode(server, name, registered.inputSchema, state.config);
398
+ state.toolModes.set(name, mode);
399
+ const originalHasInputSchema = registered.inputSchema !== undefined;
400
+ // declareTelemetry only decorates tools in "injected" mode: an "owned"
401
+ // schema already declares telemetry (the customer's contract), and "scrub"
402
+ // means capture is off — advertising the field would solicit telemetry we
403
+ // would then drop.
404
+ const decoratedSchema = options?.declareTelemetry === true && mode === "injected"
405
+ ? decorateAdvertisedSchema(server, name, state.config)
406
+ : undefined;
407
+ const registeredHasInputSchema = decoratedSchema !== undefined
408
+ ? true
409
+ : originalHasInputSchema;
410
+ // `update(...)` is the SDK's public path: it swaps the stored handler (and,
411
+ // when decorating, the input schema + description) AND regenerates the
412
+ // schema-keyed executor in one step, so dispatch arity stays exactly what
413
+ // the SDK uses for the registered inputSchema. A paramsSchema update also
414
+ // drops the SDK's memoized JSON conversion, so tools/list and pre-dispatch
415
+ // validation pick up the decorated schema.
416
+ registered.update({
417
+ ...(decoratedSchema !== undefined
418
+ ? {
419
+ paramsSchema: decoratedSchema,
420
+ // Same idempotent description nudge as v1 (ARM-24).
421
+ description: (0, schema_js_1.appendTelemetryHint)(registered.description),
422
+ }
423
+ : {}),
424
+ callback: wrapToolCallback(state, name, originalHasInputSchema, registeredHasInputSchema, handler, defaults, options),
425
+ });
426
+ };
427
+ let warnedNotWrappable = false;
428
+ const instrumentV2Server = (server, state, defaults, options) => {
429
+ if (server === null || typeof server !== "object")
430
+ return server;
431
+ const internals = server;
432
+ if (internals[WRAPPED_CALLBACK])
433
+ return server;
434
+ if (typeof internals.registerTool !== "function") {
435
+ // A factory may return a low-level `Server` (no registerTool registry);
436
+ // there is nothing to wrap there — leave it running rather than breaking
437
+ // the server over analytics.
438
+ if (!warnedNotWrappable) {
439
+ warnedNotWrappable = true;
440
+ // eslint-disable-next-line no-console
441
+ console.warn("[mcp-analytics] withMcpAnalytics(v2) received a server without registerTool (a low-level Server?); tool calls will not be recorded for it.");
442
+ }
443
+ return server;
444
+ }
445
+ Object.defineProperty(internals, WRAPPED_CALLBACK, {
446
+ value: true,
447
+ configurable: true,
448
+ });
449
+ // Tools registered BEFORE instrumentation (the instrumentedFactory shape:
450
+ // the factory registers its tools, then the wrapper runs).
451
+ if ((0, utils_js_1.isRecord)(internals._registeredTools)) {
452
+ for (const [name, tool] of Object.entries(internals._registeredTools)) {
453
+ instrumentRegisteredTool(state, internals, name, tool, defaults, options);
454
+ }
455
+ }
456
+ // Tools registered AFTER instrumentation: instance-level wrap (deliberately
457
+ // not a prototype patch — the v2 packages ship distinct ESM/CJS builds with
458
+ // distinct prototypes, and client/server bundle separate core copies, so
459
+ // instance wrapping is the only targeting that always hits).
460
+ const originalRegisterTool = internals.registerTool;
461
+ Object.defineProperty(internals, "registerTool", {
462
+ configurable: true,
463
+ writable: true,
464
+ value: function instrumentedRegisterTool(...registerArgs) {
465
+ const registered = originalRegisterTool.apply(this, registerArgs);
466
+ const name = registerArgs[0];
467
+ if (typeof name === "string") {
468
+ instrumentRegisteredTool(state, internals, name, registered, defaults, options);
469
+ }
470
+ return registered;
471
+ },
472
+ });
473
+ return server;
474
+ };
475
+ // ─── Public API ─────────────────────────────────────────────────────────────
476
+ /**
477
+ * Instrument a v2 `McpServer` instance: every tool registered on it (before or
478
+ * after this call) records a `tool_call` analytics event with the same wire
479
+ * shape as the v1 SDK integration, plus a `session_init` on first sight of
480
+ * each session key. Returns the same (mutated) server instance.
481
+ *
482
+ * Under `createMcpHandler` the factory runs per request — prefer
483
+ * `instrumentedFactory`, or hoist the config object so every request shares
484
+ * one recorder (delivery queue + session_init dedupe are keyed on it).
485
+ *
486
+ * `options` (see V2AdapterOptions): `declareTelemetry` advertises the
487
+ * Armature telemetry property on each tool's schema (v1 parity, opt-in);
488
+ * `metadata` adds per-event metadata keys.
489
+ */
490
+ const withMcpAnalytics = (server, config, options) => {
491
+ return instrumentV2Server(server, recorderStateFor(config), undefined, options);
492
+ };
493
+ exports.withMcpAnalytics = withMcpAnalytics;
494
+ const defaultsFromFactoryContext = (contextValue) => {
495
+ if (!(0, utils_js_1.isRecord)(contextValue))
496
+ return undefined;
497
+ const context = contextValue;
498
+ const requestInfo = context.requestInfo;
499
+ const headers = (0, utils_js_1.isRecord)(requestInfo) || requestInfo instanceof Request
500
+ ? requestInfo.headers
501
+ : undefined;
502
+ const authInfo = (0, utils_js_1.isRecord)(context.authInfo)
503
+ ? context.authInfo
504
+ : undefined;
505
+ const usableHeaders = headers instanceof Headers || (0, utils_js_1.isRecord)(headers)
506
+ ? headers
507
+ : undefined;
508
+ if (usableHeaders === undefined && authInfo === undefined && requestInfo === undefined) {
509
+ return undefined;
510
+ }
511
+ return {
512
+ ...(usableHeaders !== undefined ? { headers: usableHeaders } : {}),
513
+ ...(authInfo !== undefined ? { authInfo } : {}),
514
+ hasHttpRequest: requestInfo !== undefined,
515
+ };
516
+ };
517
+ /**
518
+ * Wrap a `createMcpHandler` / `serveStdio` factory so every server it produces
519
+ * is instrumented with `withMcpAnalytics`. One recorder (privacy queue +
520
+ * session_init dedupe) is shared across all servers the wrapped factory
521
+ * creates, and the factory's `McpRequestContext` (`requestInfo`, `authInfo`)
522
+ * backfills header-based capture when the handler ctx carries no HTTP request
523
+ * (the low-level `Server` sets `ctx.http.authInfo` without `req`).
524
+ */
525
+ const instrumentedFactory = (factory, config, options) => {
526
+ const state = recorderStateFor(config);
527
+ return (...args) => {
528
+ const defaults = defaultsFromFactoryContext(args[0]);
529
+ const produced = factory(...args);
530
+ if (produced !== null
531
+ && typeof produced === "object"
532
+ && typeof produced.then === "function") {
533
+ return Promise.resolve(produced).then((server) => instrumentV2Server(server, state, defaults, options));
534
+ }
535
+ return instrumentV2Server(produced, state, defaults, options);
536
+ };
537
+ };
538
+ exports.instrumentedFactory = instrumentedFactory;
539
+ const SESSION_ID_HEADER = "mcp-session-id";
540
+ /**
541
+ * Wrap a `createMcpHandler` handler's `fetch`.
542
+ *
543
+ * v2's `createMcpHandler` serves 2025-era clients through its stateless legacy
544
+ * leg, which mints NO `Mcp-Session-Id` (and offers no option to) — so a
545
+ * legacy client through a v2 handler silently loses session attribution.
546
+ * This wrapper repairs that: on a legacy `initialize` request it mints an
547
+ * identity-bearing session id (`mcp_<name>_v_<version>_<uuid>`, honoring
548
+ * `X-Armature-Session-Seed` as the uuid seed — the same scheme as
549
+ * `resolveStatelessHttpSession` in the v1 integration), attaches it as the
550
+ * response's `Mcp-Session-Id`, records the session_init, and echoes the id on
551
+ * later legacy responses. Conforming legacy clients echo the header on every
552
+ * subsequent request, where rung 3 of the session-id ladder picks it up.
553
+ *
554
+ * Composable and optional: `withMcpAnalytics` / `instrumentedFactory` work
555
+ * standalone (modern-era attribution needs no handler wrapper); pass the SAME
556
+ * config object to both so they share one recorder. Modern-era requests pass
557
+ * through this wrapper untouched (they carry no `initialize`).
558
+ */
559
+ const wrapMcpHandler = (handler, config) => {
560
+ const state = recorderStateFor(config);
561
+ const inner = handler;
562
+ const originalFetch = inner.fetch.bind(handler);
563
+ const withSessionIdHeader = (response, sessionId) => {
564
+ if (response.headers.get(SESSION_ID_HEADER))
565
+ return response;
566
+ const headers = new Headers(response.headers);
567
+ headers.set(SESSION_ID_HEADER, sessionId);
568
+ return new Response(response.body, {
569
+ status: response.status,
570
+ statusText: response.statusText,
571
+ headers,
572
+ });
573
+ };
574
+ const wrappedFetch = async (request, ...rest) => {
575
+ // createMcpHandler's fetch contract is `fetch(request, { authInfo })` —
576
+ // the caller verifies the bearer token and hands the result in via the
577
+ // options bag. Forward it into session_init actor resolution so custom
578
+ // actorId/actorIdentifier resolvers see the same authInfo shape the
579
+ // tool-call path receives.
580
+ const fetchOptions = (0, utils_js_1.isRecord)(rest[0]) ? rest[0] : undefined;
581
+ const authInfo = (0, utils_js_1.isRecord)(fetchOptions?.authInfo)
582
+ ? fetchOptions.authInfo
583
+ : undefined;
584
+ let session;
585
+ if (request.method === "POST") {
586
+ try {
587
+ const raw = await request.clone().text();
588
+ const body = raw ? JSON.parse(raw) : undefined;
589
+ // `initialize` exists only on the 2025 era, so `isInitialize` doubles
590
+ // as the legacy detector; modern-era requests fall through untouched.
591
+ session = (0, stateless_http_js_1.resolveStatelessHttpSession)({ body, headers: request.headers });
592
+ }
593
+ catch {
594
+ session = undefined;
595
+ }
596
+ }
597
+ const response = await originalFetch(request, ...rest);
598
+ if (session?.isInitialize && response.ok) {
599
+ // The identity-bearing id embeds the initialize body's clientInfo, and
600
+ // the recorder recovers name/version from it (parseStatelessSessionClientInfo)
601
+ // — so the session_init recorded here is attributed even though the
602
+ // initialize landed on a throwaway per-request server instance.
603
+ try {
604
+ await state.core.recordSessionInit({
605
+ sessionId: session.sessionId,
606
+ headers: request.headers,
607
+ ...(authInfo !== undefined ? { authInfo } : {}),
608
+ extra: {
609
+ sessionId: session.sessionId,
610
+ requestInfo: { headers: request.headers },
611
+ ...(authInfo !== undefined ? { authInfo } : {}),
612
+ },
613
+ });
614
+ }
615
+ catch {
616
+ // Recording is best-effort; never break the MCP response over it.
617
+ }
618
+ return withSessionIdHeader(response, session.sessionId);
619
+ }
620
+ // Echo an id the legacy client is already carrying, so it keeps carrying it.
621
+ const echoed = request.headers.get(SESSION_ID_HEADER)?.trim();
622
+ if (echoed)
623
+ return withSessionIdHeader(response, echoed);
624
+ return response;
625
+ };
626
+ return { ...handler, fetch: wrappedFetch };
627
+ };
628
+ exports.wrapMcpHandler = wrapMcpHandler;
629
+ var emit_js_2 = require("./emit.js");
630
+ Object.defineProperty(exports, "defaultMcpAnalyticsConfig", { enumerable: true, get: function () { return emit_js_2.defaultMcpAnalyticsConfig; } });
@@ -1,5 +1,6 @@
1
1
  import type { AnalyticsEventKind, AnalyticsIngestBatch, AnalyticsIngestEvent, McpClientInfo, RedactEventHook, RedactFunction, RequestExtra, TelemetryArgs } from "./types.js";
2
2
  import { type BoundedKeySet } from "./utils.js";
3
+ export declare const capCapabilities: (capabilities: McpClientInfo["capabilities"]) => Record<string, unknown> | null;
3
4
  export declare const buildActorId: ({ actorSeed, }: {
4
5
  actorSeed: string;
5
6
  }) => string;
@@ -28,6 +29,7 @@ export type BuildToolCallEventInput = {
28
29
  finishedAt: string;
29
30
  workflowRunId?: string;
30
31
  capabilityRequest?: boolean;
32
+ metadataExtra?: Record<string, unknown>;
31
33
  redact?: RedactFunction;
32
34
  redactSecrets?: boolean;
33
35
  };
@@ -9,7 +9,11 @@ const trimOrUndefined = (value) => {
9
9
  const trimmed = value.trim();
10
10
  return trimmed.length > 0 ? trimmed : undefined;
11
11
  };
12
- const capCapabilities = (capabilities) => {
12
+ // Drops a client-capabilities object that would blow past the metadata byte
13
+ // cap (returns null) instead of truncating it into invalid JSON. Exported for
14
+ // the v2 adapter, which stamps per-request capabilities on tool_call events
15
+ // with the same cap as session_init.
16
+ export const capCapabilities = (capabilities) => {
13
17
  if (!isRecord(capabilities))
14
18
  return null;
15
19
  try {
@@ -144,6 +148,7 @@ const assembleToolCallEvent = (candidate, input) => {
144
148
  ok: candidate.status === "ok",
145
149
  error: candidate.errorMessage ?? null,
146
150
  metadata: {
151
+ ...(input.metadataExtra ?? {}),
147
152
  tool_name: candidate.toolName,
148
153
  user_intent: t?.user_intent ?? null,
149
154
  agent_thinking: t?.agent_thinking ?? null,