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