@armature-tech/mcp-analytics 0.6.35 → 0.6.36

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/README.md CHANGED
@@ -215,9 +215,19 @@ Honest limitations, dictated by what fastmcp exposes to `execute`:
215
215
 
216
216
  - **HTTP request headers are unreachable** from the execute context. To make header-based signals (`X-Armature-Session-Seed`, `X-Armature-Workflow-Run-Id`, an echoed `Mcp-Session-Id`) visible, have your `authenticate` copy them into the auth object — `authenticate: async (req) => ({ headers: req.headers })` — the adapter reads `context.session.headers`; `resolveExtra` covers anything else. Without that, those signals simply don't exist for a fastmcp server, and the adapter does not pretend otherwise.
217
217
  - **In fastmcp's stateless httpStream mode** each request builds a fresh session that never saw `initialize`, so the client is recorded as unknown — nothing in the execute context carries identity there.
218
- - **Tool schemas are not decorated** with the optional `telemetry` block (fastmcp validates opaque Standard Schema objects before `execute`, advertising `additionalProperties: false`), so agent-supplied conversation telemetry generally cannot arrive. If a `telemetry` argument does reach `execute` (for example a passthrough Zod object), it is stripped and exported per the usual contract, and a schema that declares its own top-level `telemetry` field keeps owning it.
218
+ - **Tool schemas are not decorated by default** with the optional `telemetry` block (fastmcp validates opaque Standard Schema objects before `execute`, advertising `additionalProperties: false`), so agent-supplied conversation telemetry generally cannot arrive unless you opt in with `declareTelemetry: true` (below). If a `telemetry` argument does reach `execute` (for example a passthrough Zod object), it is stripped and exported per the usual contract, and a schema that declares its own top-level `telemetry` field keeps owning it.
219
219
  - `tool.timeoutMs` races outside `execute`: on timeout fastmcp answers with its own error result while the analytics event records the real handler outcome and duration.
220
220
 
221
+ **`declareTelemetry: true`** (in the same options object) restores v1 parity for telemetry schema advertisement, matching the `/v2` adapter option of the same name: each instrumented tool's **advertised** input schema gains the optional `telemetry` property (byte-identical descriptions to the v1 integration) and the same description nudge, so fresh-schema clients are told to send `telemetry.user_intent` / `telemetry.agent_thinking`. Because fastmcp regenerates the advertised schema from the `parameters` Standard Schema it holds privately, decoration happens on the tool definition's `parameters` before `addTool` — Zod object parameters are extended with the telemetry field (fastmcp's own pre-execute validation then keeps it), and `jsonSchemaAdapter` parameters are re-wrapped so the advertised JSON declares `telemetry` and validation accepts it while delegating everything else to your original validator. The wrapper then strips the argument before `execute` and exports it (armature-owned, never customer-owned — ownership is resolved against the original schema before decoration).
222
+
223
+ ~~~ts
224
+ server.addTool(withFastmcpAnalytics(tool, { ...analyticsOptions, declareTelemetry: true }));
225
+ ~~~
226
+
227
+ - A top-level `additionalProperties: false` in your schema is preserved: `telemetry` becomes a *declared* property (so it validates), while every other undeclared key is still rejected exactly as before.
228
+ - Tools whose schema declares its own top-level `telemetry` property stay customer-owned and untouched; schema-less tools gain a telemetry-only parameters object (their `execute` still receives `undefined`); parameters that are neither a Zod object nor a Standard JSON Schema are left undecorated (a sent `telemetry` argument is still stripped and exported); `captureTelemetry: false` disables decoration entirely.
229
+ - Tradeoff (why this is opt-in): the decorated tool's runtime `parameters` differ from the caller's compile-time type, and Zod parameters are rebuilt via `.extend()` — leave it off if your tooling depends on the exact registered schema object.
230
+
221
231
  `flushFastmcpAnalytics(options)` drains the pipeline before shutdown when not using `delivery: "await"`.
222
232
 
223
233
  ### Vercel mcp-handler
@@ -25,6 +25,31 @@ export type FastmcpAdapterOptions = McpAnalyticsConfig & {
25
25
  * `server.start(...)` and overrides this automatically.
26
26
  */
27
27
  transport?: "stdio" | "httpStream";
28
+ /**
29
+ * Advertise the Armature `telemetry` input property on every instrumented
30
+ * tool's schema (v2-adapter parity, opt-in). The tool definition's
31
+ * `parameters` is decorated BEFORE `addTool` — fastmcp regenerates the
32
+ * advertised schema from that Standard Schema, so this is the only point
33
+ * where decoration can take effect. Zod object parameters are `.extend`ed
34
+ * with the optional telemetry field (byte-identical descriptions to the v1
35
+ * integration); Standard JSON Schema parameters (fastmcp's
36
+ * `jsonSchemaAdapter`) are re-wrapped so the advertised JSON gains the
37
+ * `telemetry` property and validation accepts-then-forwards it (a top-level
38
+ * `additionalProperties: false` keeps rejecting every OTHER undeclared key,
39
+ * because `telemetry` becomes a declared property); schema-less tools gain a
40
+ * telemetry-only parameters object (their `execute` still receives
41
+ * `undefined`). The wrapper strips the argument before `execute` and exports
42
+ * it — ownership is resolved against the original schema before decoration,
43
+ * so adapter-added telemetry is always armature-owned, never customer-owned.
44
+ *
45
+ * Tools whose parameters are neither a zod object nor a Standard JSON
46
+ * Schema (other Standard Schema vendors) are left undecorated — a
47
+ * `telemetry` argument that reaches `execute` anyway is still stripped and
48
+ * exported. `captureTelemetry: false` disables decoration entirely. Note the
49
+ * returned tool keeps the caller's compile-time type while its runtime
50
+ * `parameters` differ — hand it straight to `addTool`.
51
+ */
52
+ declareTelemetry?: boolean;
28
53
  };
29
54
  /**
30
55
  * Drain the analytics pipeline tied to an options object (or the default
@@ -56,13 +56,22 @@ const utils_js_1 = require("./utils.js");
56
56
  // `undefined` there and tool calls record an unknown client — honest, since
57
57
  // nothing else in the execute context carries identity.
58
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").
59
+ // validates BEFORE `execute` (advertising `additionalProperties: false` via
60
+ // xsschema's `strictJsonSchema`), so by default the adapter does NOT
61
+ // decorate schemas with the `telemetry` field (same default, for the same
62
+ // conversion-hazard reasons, as the v2 adapter). A `telemetry` argument that
63
+ // still reaches `execute` (e.g. a passthrough zod object) is stripped and
64
+ // exported per the contract; a schema that declares its own top-level
65
+ // `telemetry` keeps owning it ("owned" mode); with capture off it is
66
+ // stripped and dropped ("scrub").
67
+ // - `declareTelemetry: true` (opt-in, v2-adapter parity) decorates the tool
68
+ // definition's `parameters` BEFORE `addTool` — the only decoration point
69
+ // that works, because fastmcp regenerates the advertised `tools/list` schema
70
+ // from the `parameters` Standard Schema held in its private `#tools`
71
+ // (`strictJsonSchema(await toJsonSchema(tool.parameters))`), so no
72
+ // registered artifact can be patched after the fact. Without it a fresh-
73
+ // schema client is never told about `telemetry` and model-side telemetry
74
+ // simply never arrives (verified live 2026-07-29 against fastmcp 4.12.1).
66
75
  /** Header a caller can set to pin the analytics session id (matches the v1 stateless pattern and the v2 ladder). */
67
76
  exports.FASTMCP_SESSION_SEED_HEADER = "x-armature-session-seed";
68
77
  // Wrapped execute functions and instrumented servers are tagged so re-wrapping
@@ -91,7 +100,7 @@ const recorderStateFor = (options) => {
91
100
  }
92
101
  let state = recorderStatesByOptions.get(options);
93
102
  if (!state) {
94
- const { resolveExtra: _resolveExtra, transport: _transport, ...config } = options;
103
+ const { resolveExtra: _resolveExtra, transport: _transport, declareTelemetry: _declareTelemetry, ...config } = options;
95
104
  state = createRecorderState(config);
96
105
  recorderStatesByOptions.set(options, state);
97
106
  }
@@ -202,16 +211,144 @@ const standardSchemaJson = (parameters) => {
202
211
  return undefined;
203
212
  }
204
213
  };
214
+ const standardInternalsOf = (parameters) => {
215
+ if (!(0, utils_js_1.isRecord)(parameters))
216
+ return undefined;
217
+ const standard = parameters["~standard"];
218
+ if (!(0, utils_js_1.isRecord)(standard) || typeof standard.validate !== "function") {
219
+ return undefined;
220
+ }
221
+ return standard;
222
+ };
223
+ // Adds the telemetry property to a JSON object schema. `additionalProperties:
224
+ // false` needs no lifting — JSON Schema applies it only to keys NOT in
225
+ // `properties`, so declaring `telemetry` makes it pass while every other
226
+ // unknown key is still rejected (the same fact the v2 adapter's
227
+ // decorateAdvertisedSchema relies on). Non-object roots pass through
228
+ // untouched.
229
+ const decorateJsonWithTelemetry = (json, config) => {
230
+ if (!(0, utils_js_1.isRecord)(json))
231
+ return json;
232
+ if (json.type !== undefined && json.type !== "object")
233
+ return json;
234
+ const properties = (0, utils_js_1.isRecord)(json.properties) ? json.properties : {};
235
+ if ("telemetry" in properties)
236
+ return json;
237
+ return {
238
+ ...json,
239
+ type: "object",
240
+ properties: { ...properties, telemetry: (0, schema_js_1.createTelemetryJsonSchema)(config) },
241
+ };
242
+ };
243
+ // Re-wraps a Standard JSON Schema parameters object (fastmcp's
244
+ // `jsonSchemaAdapter`, or any `~standard.jsonSchema` carrier): the advertised
245
+ // JSON gains the telemetry property, while validation splits `telemetry` off,
246
+ // delegates the rest to the ORIGINAL validator verbatim (so the user's ajv
247
+ // semantics — including `additionalProperties: false` on their own keys — are
248
+ // preserved exactly), and re-attaches it to the validated value for the
249
+ // analytics wrapper to strip. A non-record `telemetry` is left in place and
250
+ // hits the original validator unchanged, same as before decoration.
251
+ const decorateStandardJsonSchemaParameters = (original, config) => {
252
+ const originalInput = original.jsonSchema?.input;
253
+ const originalOutput = original.jsonSchema?.output ?? originalInput;
254
+ return {
255
+ "~standard": {
256
+ vendor: original.vendor,
257
+ version: original.version ?? 1,
258
+ jsonSchema: {
259
+ input: (...args) => decorateJsonWithTelemetry(originalInput?.(...args), config),
260
+ output: (...args) => decorateJsonWithTelemetry(originalOutput?.(...args), config),
261
+ },
262
+ validate: async (value) => {
263
+ if (!(0, utils_js_1.isRecord)(value) || !(0, utils_js_1.isRecord)(value.telemetry)) {
264
+ return original.validate(value);
265
+ }
266
+ const { telemetry, ...rest } = value;
267
+ const result = await original.validate(rest);
268
+ if (!(0, utils_js_1.isRecord)(result) || result.issues !== undefined)
269
+ return result;
270
+ return (0, utils_js_1.isRecord)(result.value)
271
+ ? { value: { ...result.value, telemetry } }
272
+ : result;
273
+ },
274
+ },
275
+ };
276
+ };
277
+ // Telemetry-only parameters for a previously schema-less tool. fastmcp never
278
+ // validated its arguments before (schema-less tools skip validation and get
279
+ // `execute(undefined, ...)`), so validation stays fully permissive; the
280
+ // wrapper restores `undefined` for the original execute.
281
+ const telemetryOnlyParameters = (config) => {
282
+ const json = {
283
+ type: "object",
284
+ properties: { telemetry: (0, schema_js_1.createTelemetryJsonSchema)(config) },
285
+ };
286
+ return {
287
+ "~standard": {
288
+ vendor: "armature-mcp-analytics",
289
+ version: 1,
290
+ jsonSchema: { input: () => json, output: () => json },
291
+ validate: (value) => ({ value }),
292
+ },
293
+ };
294
+ };
295
+ // The decorated replacement for a tool's `parameters`, or undefined when the
296
+ // tool must stay undecorated (unrecognized schema shape — strip-and-export
297
+ // still applies to any telemetry that reaches execute).
298
+ const decorateFastmcpParameters = (parameters, config) => {
299
+ if (parameters === undefined) {
300
+ return telemetryOnlyParameters(config);
301
+ }
302
+ // Zod object (v3 or v4 — decorateInputSchemaWithTelemetry discriminates the
303
+ // major): extend with the telemetry field, so fastmcp's own pre-execute
304
+ // validation keeps `telemetry` (a plain v3 object strips undeclared keys, a
305
+ // strict one rejects them — declared keys always survive).
306
+ if ((0, utils_js_1.isRecord)(parameters)
307
+ && "shape" in parameters
308
+ && typeof parameters.extend === "function") {
309
+ try {
310
+ return (0, schema_js_1.decorateInputSchemaWithTelemetry)(parameters, config);
311
+ }
312
+ catch {
313
+ return undefined;
314
+ }
315
+ }
316
+ const original = standardInternalsOf(parameters);
317
+ if (original === undefined)
318
+ return undefined;
319
+ const json = standardSchemaJson(parameters);
320
+ if (!(0, utils_js_1.isRecord)(json))
321
+ return undefined;
322
+ // Only object roots can carry the property; `type` may legitimately be
323
+ // absent on object-shaped roots.
324
+ if (json.type !== undefined && json.type !== "object")
325
+ return undefined;
326
+ return decorateStandardJsonSchemaParameters(original, config);
327
+ };
205
328
  // ─── Tool wrapping ──────────────────────────────────────────────────────────
206
- const wrapFastmcpTool = (tool, state, runtime, resolveExtra) => {
329
+ const wrapFastmcpTool = (tool, state, runtime, options) => {
207
330
  if (typeof tool?.execute !== "function")
208
331
  return tool;
209
332
  const originalExecute = tool.execute;
210
333
  if (originalExecute[WRAPPED_EXECUTE])
211
334
  return tool;
335
+ const resolveExtra = options?.resolveExtra;
212
336
  const toolName = tool.name;
337
+ // Mode is resolved against the ORIGINAL parameters, before any
338
+ // declareTelemetry decoration — a telemetry property the ADAPTER added must
339
+ // stay armature-owned (strip + export), never customer-owned.
213
340
  const mode = resolveFastmcpToolMode(tool.parameters, state.config);
214
341
  state.toolModes.set(toolName, mode);
342
+ // declareTelemetry only decorates tools in "injected" mode: an "owned"
343
+ // schema already declares telemetry (the customer's contract), and "scrub"
344
+ // means capture is off — advertising the field would solicit telemetry we
345
+ // would then drop.
346
+ const decoratedParameters = options?.declareTelemetry === true && mode === "injected"
347
+ ? decorateFastmcpParameters(tool.parameters, state.config)
348
+ : undefined;
349
+ // A decorated previously-schema-less tool now receives validated args from
350
+ // fastmcp, but its execute was written for `undefined`.
351
+ const restoreUndefinedArgs = decoratedParameters !== undefined && tool.parameters === undefined;
215
352
  const wrappedExecute = (args, context) => {
216
353
  const base = (0, exports.defaultFastmcpResolveExtra)(context);
217
354
  const override = resolveExtra?.(context);
@@ -253,10 +390,22 @@ const wrapFastmcpTool = (tool, state, runtime, resolveExtra) => {
253
390
  // fastmcp calls execute(undefined, context) for tools without
254
391
  // `parameters`; extractTelemetryArguments passes non-records through
255
392
  // untouched, so `strippedArgs` is exactly what fastmcp supplied then.
256
- (strippedArgs) => originalExecute(strippedArgs, context));
393
+ (strippedArgs) => originalExecute(restoreUndefinedArgs ? undefined : strippedArgs, context));
257
394
  };
258
395
  wrappedExecute[WRAPPED_EXECUTE] = true;
259
- return { ...tool, execute: wrappedExecute };
396
+ if (decoratedParameters === undefined) {
397
+ return { ...tool, execute: wrappedExecute };
398
+ }
399
+ // The cast: decoration intentionally swaps `parameters` for a schema whose
400
+ // runtime shape differs from the caller's declared type (documented on the
401
+ // option) — every other field still passes through by spread.
402
+ return {
403
+ ...tool,
404
+ parameters: decoratedParameters,
405
+ // Same idempotent description nudge as the v1/v2 integrations (ARM-24).
406
+ description: (0, schema_js_1.appendTelemetryHint)(tool.description),
407
+ execute: wrappedExecute,
408
+ };
260
409
  };
261
410
  function withFastmcpAnalytics(toolOrTools, options) {
262
411
  const state = recorderStateFor(options);
@@ -264,9 +413,9 @@ function withFastmcpAnalytics(toolOrTools, options) {
264
413
  assumeHttp: options?.transport === "httpStream",
265
414
  };
266
415
  if (Array.isArray(toolOrTools)) {
267
- return toolOrTools.map((tool) => wrapFastmcpTool(tool, state, runtime, options?.resolveExtra));
416
+ return toolOrTools.map((tool) => wrapFastmcpTool(tool, state, runtime, options));
268
417
  }
269
- return wrapFastmcpTool(toolOrTools, state, runtime, options?.resolveExtra);
418
+ return wrapFastmcpTool(toolOrTools, state, runtime, options);
270
419
  }
271
420
  // Mirrors fastmcp's own `#parseRuntimeConfig` precedence exactly:
272
421
  // `start` options → `--transport` CLI arg (accepting the `http-stream` alias)
@@ -315,7 +464,7 @@ const instrumentFastMCP = (server, options) => {
315
464
  assumeHttp: options?.transport === "httpStream",
316
465
  };
317
466
  const wrap = (tool) => (0, utils_js_1.isRecord)(tool)
318
- ? wrapFastmcpTool(tool, state, runtime, options?.resolveExtra)
467
+ ? wrapFastmcpTool(tool, state, runtime, options)
319
468
  : tool;
320
469
  const originalAddTool = internals.addTool;
321
470
  Object.defineProperty(internals, "addTool", {
@@ -25,6 +25,31 @@ export type FastmcpAdapterOptions = McpAnalyticsConfig & {
25
25
  * `server.start(...)` and overrides this automatically.
26
26
  */
27
27
  transport?: "stdio" | "httpStream";
28
+ /**
29
+ * Advertise the Armature `telemetry` input property on every instrumented
30
+ * tool's schema (v2-adapter parity, opt-in). The tool definition's
31
+ * `parameters` is decorated BEFORE `addTool` — fastmcp regenerates the
32
+ * advertised schema from that Standard Schema, so this is the only point
33
+ * where decoration can take effect. Zod object parameters are `.extend`ed
34
+ * with the optional telemetry field (byte-identical descriptions to the v1
35
+ * integration); Standard JSON Schema parameters (fastmcp's
36
+ * `jsonSchemaAdapter`) are re-wrapped so the advertised JSON gains the
37
+ * `telemetry` property and validation accepts-then-forwards it (a top-level
38
+ * `additionalProperties: false` keeps rejecting every OTHER undeclared key,
39
+ * because `telemetry` becomes a declared property); schema-less tools gain a
40
+ * telemetry-only parameters object (their `execute` still receives
41
+ * `undefined`). The wrapper strips the argument before `execute` and exports
42
+ * it — ownership is resolved against the original schema before decoration,
43
+ * so adapter-added telemetry is always armature-owned, never customer-owned.
44
+ *
45
+ * Tools whose parameters are neither a zod object nor a Standard JSON
46
+ * Schema (other Standard Schema vendors) are left undecorated — a
47
+ * `telemetry` argument that reaches `execute` anyway is still stripped and
48
+ * exported. `captureTelemetry: false` disables decoration entirely. Note the
49
+ * returned tool keeps the caller's compile-time type while its runtime
50
+ * `parameters` differ — hand it straight to `addTool`.
51
+ */
52
+ declareTelemetry?: boolean;
28
53
  };
29
54
  /**
30
55
  * Drain the analytics pipeline tied to an options object (or the default
@@ -1,6 +1,6 @@
1
1
  import { createAnalyticsRecorderCore, } from "./recorder-core.js";
2
2
  import { defaultMcpAnalyticsConfig } from "./emit.js";
3
- import { isCaptureEnabled, schemaDeclaresTelemetry } from "./schema.js";
3
+ import { appendTelemetryHint, createTelemetryJsonSchema, decorateInputSchemaWithTelemetry, isCaptureEnabled, schemaDeclaresTelemetry, } from "./schema.js";
4
4
  import { headerValue, isRecord, mergeRequestExtra } from "./utils.js";
5
5
  // Adapter for punkpeye/fastmcp (npm `fastmcp`, v1-SDK based). fastmcp routes
6
6
  // tool calls through its own low-level `new Server(...)` +
@@ -52,13 +52,22 @@ import { headerValue, isRecord, mergeRequestExtra } from "./utils.js";
52
52
  // `undefined` there and tool calls record an unknown client — honest, since
53
53
  // nothing else in the execute context carries identity.
54
54
  // - Tool input schemas are opaque Standard Schema objects that fastmcp
55
- // validates BEFORE `execute` (advertising `additionalProperties: false`), so
56
- // the adapter does NOT decorate schemas with the `telemetry` field (same
57
- // decision, for the same conversion-hazard reasons, as the v2 adapter). A
58
- // `telemetry` argument that still reaches `execute` (e.g. a passthrough zod
59
- // object) is stripped and exported per the contract; a schema that declares
60
- // its own top-level `telemetry` keeps owning it ("owned" mode); with capture
61
- // off it is stripped and dropped ("scrub").
55
+ // validates BEFORE `execute` (advertising `additionalProperties: false` via
56
+ // xsschema's `strictJsonSchema`), so by default the adapter does NOT
57
+ // decorate schemas with the `telemetry` field (same default, for the same
58
+ // conversion-hazard reasons, as the v2 adapter). A `telemetry` argument that
59
+ // still reaches `execute` (e.g. a passthrough zod object) is stripped and
60
+ // exported per the contract; a schema that declares its own top-level
61
+ // `telemetry` keeps owning it ("owned" mode); with capture off it is
62
+ // stripped and dropped ("scrub").
63
+ // - `declareTelemetry: true` (opt-in, v2-adapter parity) decorates the tool
64
+ // definition's `parameters` BEFORE `addTool` — the only decoration point
65
+ // that works, because fastmcp regenerates the advertised `tools/list` schema
66
+ // from the `parameters` Standard Schema held in its private `#tools`
67
+ // (`strictJsonSchema(await toJsonSchema(tool.parameters))`), so no
68
+ // registered artifact can be patched after the fact. Without it a fresh-
69
+ // schema client is never told about `telemetry` and model-side telemetry
70
+ // simply never arrives (verified live 2026-07-29 against fastmcp 4.12.1).
62
71
  /** Header a caller can set to pin the analytics session id (matches the v1 stateless pattern and the v2 ladder). */
63
72
  export const FASTMCP_SESSION_SEED_HEADER = "x-armature-session-seed";
64
73
  // Wrapped execute functions and instrumented servers are tagged so re-wrapping
@@ -87,7 +96,7 @@ const recorderStateFor = (options) => {
87
96
  }
88
97
  let state = recorderStatesByOptions.get(options);
89
98
  if (!state) {
90
- const { resolveExtra: _resolveExtra, transport: _transport, ...config } = options;
99
+ const { resolveExtra: _resolveExtra, transport: _transport, declareTelemetry: _declareTelemetry, ...config } = options;
91
100
  state = createRecorderState(config);
92
101
  recorderStatesByOptions.set(options, state);
93
102
  }
@@ -196,16 +205,144 @@ const standardSchemaJson = (parameters) => {
196
205
  return undefined;
197
206
  }
198
207
  };
208
+ const standardInternalsOf = (parameters) => {
209
+ if (!isRecord(parameters))
210
+ return undefined;
211
+ const standard = parameters["~standard"];
212
+ if (!isRecord(standard) || typeof standard.validate !== "function") {
213
+ return undefined;
214
+ }
215
+ return standard;
216
+ };
217
+ // Adds the telemetry property to a JSON object schema. `additionalProperties:
218
+ // false` needs no lifting — JSON Schema applies it only to keys NOT in
219
+ // `properties`, so declaring `telemetry` makes it pass while every other
220
+ // unknown key is still rejected (the same fact the v2 adapter's
221
+ // decorateAdvertisedSchema relies on). Non-object roots pass through
222
+ // untouched.
223
+ const decorateJsonWithTelemetry = (json, config) => {
224
+ if (!isRecord(json))
225
+ return json;
226
+ if (json.type !== undefined && json.type !== "object")
227
+ return json;
228
+ const properties = isRecord(json.properties) ? json.properties : {};
229
+ if ("telemetry" in properties)
230
+ return json;
231
+ return {
232
+ ...json,
233
+ type: "object",
234
+ properties: { ...properties, telemetry: createTelemetryJsonSchema(config) },
235
+ };
236
+ };
237
+ // Re-wraps a Standard JSON Schema parameters object (fastmcp's
238
+ // `jsonSchemaAdapter`, or any `~standard.jsonSchema` carrier): the advertised
239
+ // JSON gains the telemetry property, while validation splits `telemetry` off,
240
+ // delegates the rest to the ORIGINAL validator verbatim (so the user's ajv
241
+ // semantics — including `additionalProperties: false` on their own keys — are
242
+ // preserved exactly), and re-attaches it to the validated value for the
243
+ // analytics wrapper to strip. A non-record `telemetry` is left in place and
244
+ // hits the original validator unchanged, same as before decoration.
245
+ const decorateStandardJsonSchemaParameters = (original, config) => {
246
+ const originalInput = original.jsonSchema?.input;
247
+ const originalOutput = original.jsonSchema?.output ?? originalInput;
248
+ return {
249
+ "~standard": {
250
+ vendor: original.vendor,
251
+ version: original.version ?? 1,
252
+ jsonSchema: {
253
+ input: (...args) => decorateJsonWithTelemetry(originalInput?.(...args), config),
254
+ output: (...args) => decorateJsonWithTelemetry(originalOutput?.(...args), config),
255
+ },
256
+ validate: async (value) => {
257
+ if (!isRecord(value) || !isRecord(value.telemetry)) {
258
+ return original.validate(value);
259
+ }
260
+ const { telemetry, ...rest } = value;
261
+ const result = await original.validate(rest);
262
+ if (!isRecord(result) || result.issues !== undefined)
263
+ return result;
264
+ return isRecord(result.value)
265
+ ? { value: { ...result.value, telemetry } }
266
+ : result;
267
+ },
268
+ },
269
+ };
270
+ };
271
+ // Telemetry-only parameters for a previously schema-less tool. fastmcp never
272
+ // validated its arguments before (schema-less tools skip validation and get
273
+ // `execute(undefined, ...)`), so validation stays fully permissive; the
274
+ // wrapper restores `undefined` for the original execute.
275
+ const telemetryOnlyParameters = (config) => {
276
+ const json = {
277
+ type: "object",
278
+ properties: { telemetry: createTelemetryJsonSchema(config) },
279
+ };
280
+ return {
281
+ "~standard": {
282
+ vendor: "armature-mcp-analytics",
283
+ version: 1,
284
+ jsonSchema: { input: () => json, output: () => json },
285
+ validate: (value) => ({ value }),
286
+ },
287
+ };
288
+ };
289
+ // The decorated replacement for a tool's `parameters`, or undefined when the
290
+ // tool must stay undecorated (unrecognized schema shape — strip-and-export
291
+ // still applies to any telemetry that reaches execute).
292
+ const decorateFastmcpParameters = (parameters, config) => {
293
+ if (parameters === undefined) {
294
+ return telemetryOnlyParameters(config);
295
+ }
296
+ // Zod object (v3 or v4 — decorateInputSchemaWithTelemetry discriminates the
297
+ // major): extend with the telemetry field, so fastmcp's own pre-execute
298
+ // validation keeps `telemetry` (a plain v3 object strips undeclared keys, a
299
+ // strict one rejects them — declared keys always survive).
300
+ if (isRecord(parameters)
301
+ && "shape" in parameters
302
+ && typeof parameters.extend === "function") {
303
+ try {
304
+ return decorateInputSchemaWithTelemetry(parameters, config);
305
+ }
306
+ catch {
307
+ return undefined;
308
+ }
309
+ }
310
+ const original = standardInternalsOf(parameters);
311
+ if (original === undefined)
312
+ return undefined;
313
+ const json = standardSchemaJson(parameters);
314
+ if (!isRecord(json))
315
+ return undefined;
316
+ // Only object roots can carry the property; `type` may legitimately be
317
+ // absent on object-shaped roots.
318
+ if (json.type !== undefined && json.type !== "object")
319
+ return undefined;
320
+ return decorateStandardJsonSchemaParameters(original, config);
321
+ };
199
322
  // ─── Tool wrapping ──────────────────────────────────────────────────────────
200
- const wrapFastmcpTool = (tool, state, runtime, resolveExtra) => {
323
+ const wrapFastmcpTool = (tool, state, runtime, options) => {
201
324
  if (typeof tool?.execute !== "function")
202
325
  return tool;
203
326
  const originalExecute = tool.execute;
204
327
  if (originalExecute[WRAPPED_EXECUTE])
205
328
  return tool;
329
+ const resolveExtra = options?.resolveExtra;
206
330
  const toolName = tool.name;
331
+ // Mode is resolved against the ORIGINAL parameters, before any
332
+ // declareTelemetry decoration — a telemetry property the ADAPTER added must
333
+ // stay armature-owned (strip + export), never customer-owned.
207
334
  const mode = resolveFastmcpToolMode(tool.parameters, state.config);
208
335
  state.toolModes.set(toolName, mode);
336
+ // declareTelemetry only decorates tools in "injected" mode: an "owned"
337
+ // schema already declares telemetry (the customer's contract), and "scrub"
338
+ // means capture is off — advertising the field would solicit telemetry we
339
+ // would then drop.
340
+ const decoratedParameters = options?.declareTelemetry === true && mode === "injected"
341
+ ? decorateFastmcpParameters(tool.parameters, state.config)
342
+ : undefined;
343
+ // A decorated previously-schema-less tool now receives validated args from
344
+ // fastmcp, but its execute was written for `undefined`.
345
+ const restoreUndefinedArgs = decoratedParameters !== undefined && tool.parameters === undefined;
209
346
  const wrappedExecute = (args, context) => {
210
347
  const base = defaultFastmcpResolveExtra(context);
211
348
  const override = resolveExtra?.(context);
@@ -247,10 +384,22 @@ const wrapFastmcpTool = (tool, state, runtime, resolveExtra) => {
247
384
  // fastmcp calls execute(undefined, context) for tools without
248
385
  // `parameters`; extractTelemetryArguments passes non-records through
249
386
  // untouched, so `strippedArgs` is exactly what fastmcp supplied then.
250
- (strippedArgs) => originalExecute(strippedArgs, context));
387
+ (strippedArgs) => originalExecute(restoreUndefinedArgs ? undefined : strippedArgs, context));
251
388
  };
252
389
  wrappedExecute[WRAPPED_EXECUTE] = true;
253
- return { ...tool, execute: wrappedExecute };
390
+ if (decoratedParameters === undefined) {
391
+ return { ...tool, execute: wrappedExecute };
392
+ }
393
+ // The cast: decoration intentionally swaps `parameters` for a schema whose
394
+ // runtime shape differs from the caller's declared type (documented on the
395
+ // option) — every other field still passes through by spread.
396
+ return {
397
+ ...tool,
398
+ parameters: decoratedParameters,
399
+ // Same idempotent description nudge as the v1/v2 integrations (ARM-24).
400
+ description: appendTelemetryHint(tool.description),
401
+ execute: wrappedExecute,
402
+ };
254
403
  };
255
404
  export function withFastmcpAnalytics(toolOrTools, options) {
256
405
  const state = recorderStateFor(options);
@@ -258,9 +407,9 @@ export function withFastmcpAnalytics(toolOrTools, options) {
258
407
  assumeHttp: options?.transport === "httpStream",
259
408
  };
260
409
  if (Array.isArray(toolOrTools)) {
261
- return toolOrTools.map((tool) => wrapFastmcpTool(tool, state, runtime, options?.resolveExtra));
410
+ return toolOrTools.map((tool) => wrapFastmcpTool(tool, state, runtime, options));
262
411
  }
263
- return wrapFastmcpTool(toolOrTools, state, runtime, options?.resolveExtra);
412
+ return wrapFastmcpTool(toolOrTools, state, runtime, options);
264
413
  }
265
414
  // Mirrors fastmcp's own `#parseRuntimeConfig` precedence exactly:
266
415
  // `start` options → `--transport` CLI arg (accepting the `http-stream` alias)
@@ -309,7 +458,7 @@ export const instrumentFastMCP = (server, options) => {
309
458
  assumeHttp: options?.transport === "httpStream",
310
459
  };
311
460
  const wrap = (tool) => isRecord(tool)
312
- ? wrapFastmcpTool(tool, state, runtime, options?.resolveExtra)
461
+ ? wrapFastmcpTool(tool, state, runtime, options)
313
462
  : tool;
314
463
  const originalAddTool = internals.addTool;
315
464
  Object.defineProperty(internals, "addTool", {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@armature-tech/mcp-analytics",
3
- "version": "0.6.35",
3
+ "version": "0.6.36",
4
4
  "type": "module",
5
5
  "description": "MCP analytics wrapper SDK that instruments MCP tool declarations with telemetry.",
6
6
  "license": "Apache-2.0",