@armature-tech/mcp-analytics 0.6.34 → 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 +11 -1
- package/dist/cjs/fastmcp.d.ts +25 -0
- package/dist/cjs/fastmcp.js +163 -14
- package/dist/cjs/mcp-handler.js +1 -31
- package/dist/cjs/stateless-http.d.ts +1 -0
- package/dist/cjs/stateless-http.js +31 -1
- package/dist/cjs/v2.js +9 -5
- package/dist/esm/fastmcp.d.ts +25 -0
- package/dist/esm/fastmcp.js +164 -15
- package/dist/esm/mcp-handler.js +1 -31
- package/dist/esm/stateless-http.d.ts +1 -0
- package/dist/esm/stateless-http.js +29 -0
- package/dist/esm/v2.js +10 -6
- package/package.json +1 -1
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
|
package/dist/cjs/fastmcp.d.ts
CHANGED
|
@@ -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
|
package/dist/cjs/fastmcp.js
CHANGED
|
@@ -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`
|
|
60
|
-
//
|
|
61
|
-
//
|
|
62
|
-
//
|
|
63
|
-
//
|
|
64
|
-
//
|
|
65
|
-
//
|
|
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,
|
|
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
|
-
|
|
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
|
|
416
|
+
return toolOrTools.map((tool) => wrapFastmcpTool(tool, state, runtime, options));
|
|
268
417
|
}
|
|
269
|
-
return wrapFastmcpTool(toolOrTools, state, runtime, options
|
|
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
|
|
467
|
+
? wrapFastmcpTool(tool, state, runtime, options)
|
|
319
468
|
: tool;
|
|
320
469
|
const originalAddTool = internals.addTool;
|
|
321
470
|
Object.defineProperty(internals, "addTool", {
|
package/dist/cjs/mcp-handler.js
CHANGED
|
@@ -4,7 +4,6 @@ exports.defaultMcpAnalyticsConfig = exports.withMcpHandlerAnalytics = exports.fl
|
|
|
4
4
|
const recorder_core_js_1 = require("./recorder-core.js");
|
|
5
5
|
const emit_js_1 = require("./emit.js");
|
|
6
6
|
const stateless_http_js_1 = require("./stateless-http.js");
|
|
7
|
-
const utils_js_1 = require("./utils.js");
|
|
8
7
|
const SESSION_ID_HEADER = "mcp-session-id";
|
|
9
8
|
// Keyed on the config object so every request shares one recorder (privacy
|
|
10
9
|
// queue + session_init dedupe) — hoist the config, same contract as the v2
|
|
@@ -29,35 +28,6 @@ const flushMcpHandlerAnalytics = (config) => {
|
|
|
29
28
|
return recorderStateFor(config).core.flush();
|
|
30
29
|
};
|
|
31
30
|
exports.flushMcpHandlerAnalytics = flushMcpHandlerAnalytics;
|
|
32
|
-
const trimOrUndefined = (value) => {
|
|
33
|
-
if (typeof value !== "string")
|
|
34
|
-
return undefined;
|
|
35
|
-
const trimmed = value.trim();
|
|
36
|
-
return trimmed.length > 0 ? trimmed : undefined;
|
|
37
|
-
};
|
|
38
|
-
// Full-fidelity clientInfo from the initialize body itself (name, version,
|
|
39
|
-
// protocolVersion, capabilities) — richer than what the minted id can carry,
|
|
40
|
-
// so the session_init recorded at initialize matches what a stateful v1
|
|
41
|
-
// deployment would report.
|
|
42
|
-
const clientInfoFromInitializeBody = (body) => {
|
|
43
|
-
const messages = Array.isArray(body) ? body : [body];
|
|
44
|
-
const initialize = messages.find((message) => (0, utils_js_1.isRecord)(message) && message.method === "initialize");
|
|
45
|
-
const params = (0, utils_js_1.isRecord)(initialize?.params) ? initialize.params : undefined;
|
|
46
|
-
if (!params)
|
|
47
|
-
return undefined;
|
|
48
|
-
const info = (0, utils_js_1.isRecord)(params.clientInfo) ? params.clientInfo : undefined;
|
|
49
|
-
const name = trimOrUndefined(info?.name);
|
|
50
|
-
if (name === undefined)
|
|
51
|
-
return undefined;
|
|
52
|
-
const version = trimOrUndefined(info?.version);
|
|
53
|
-
const protocolVersion = trimOrUndefined(params.protocolVersion);
|
|
54
|
-
return {
|
|
55
|
-
name,
|
|
56
|
-
...(version !== undefined ? { version } : {}),
|
|
57
|
-
...(protocolVersion !== undefined ? { protocolVersion } : {}),
|
|
58
|
-
capabilities: (0, utils_js_1.isRecord)(params.capabilities) ? params.capabilities : null,
|
|
59
|
-
};
|
|
60
|
-
};
|
|
61
31
|
const withSessionIdHeader = (response, sessionId) => {
|
|
62
32
|
if (response.headers.get(SESSION_ID_HEADER))
|
|
63
33
|
return response;
|
|
@@ -113,7 +83,7 @@ const withMcpHandlerAnalytics = (handler, config) => {
|
|
|
113
83
|
await state.core.recordSessionInit({
|
|
114
84
|
sessionId: session.sessionId,
|
|
115
85
|
headers: request.headers,
|
|
116
|
-
clientInfo: clientInfoFromInitializeBody(body),
|
|
86
|
+
clientInfo: (0, stateless_http_js_1.clientInfoFromInitializeBody)(body),
|
|
117
87
|
extra: {
|
|
118
88
|
sessionId: session.sessionId,
|
|
119
89
|
requestInfo: { headers: request.headers },
|
|
@@ -3,6 +3,7 @@ import type { HeaderBag, McpClientInfo } from "./types.js";
|
|
|
3
3
|
export declare const buildStatelessSessionId: (clientInfo?: McpClientInfo, sessionSeed?: string) => string;
|
|
4
4
|
/** Recover the client identity from an identity-bearing session id. */
|
|
5
5
|
export declare const parseStatelessSessionClientInfo: (sessionId: string | undefined) => McpClientInfo | undefined;
|
|
6
|
+
export declare const clientInfoFromInitializeBody: (body: unknown) => McpClientInfo | undefined;
|
|
6
7
|
export type StatelessHttpSession = {
|
|
7
8
|
/** Stable session id: minted at initialize, parsed from the echoed header otherwise. */
|
|
8
9
|
sessionId: string;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.resolveStatelessHttpSession = exports.parseStatelessSessionClientInfo = exports.buildStatelessSessionId = void 0;
|
|
3
|
+
exports.resolveStatelessHttpSession = exports.clientInfoFromInitializeBody = exports.parseStatelessSessionClientInfo = exports.buildStatelessSessionId = void 0;
|
|
4
4
|
const node_crypto_1 = require("node:crypto");
|
|
5
5
|
const utils_js_1 = require("./utils.js");
|
|
6
6
|
// Stateless HTTP deployments (Vercel, Lambda, Cloud Run with no sticky
|
|
@@ -71,6 +71,36 @@ const clientInfoFromInitialize = (message) => {
|
|
|
71
71
|
...(typeof info.version === "string" ? { version: info.version } : {}),
|
|
72
72
|
};
|
|
73
73
|
};
|
|
74
|
+
const trimOrUndefined = (value) => {
|
|
75
|
+
if (typeof value !== "string")
|
|
76
|
+
return undefined;
|
|
77
|
+
const trimmed = value.trim();
|
|
78
|
+
return trimmed.length > 0 ? trimmed : undefined;
|
|
79
|
+
};
|
|
80
|
+
// Full-fidelity clientInfo from the initialize body itself (name, version,
|
|
81
|
+
// protocolVersion, capabilities) — richer than what the minted id can carry,
|
|
82
|
+
// so the session_init recorded at initialize matches what a stateful v1
|
|
83
|
+
// deployment would report. Shared by the stateless-handler wrappers
|
|
84
|
+
// (withMcpHandlerAnalytics and the v2 wrapMcpHandler legacy leg).
|
|
85
|
+
const clientInfoFromInitializeBody = (body) => {
|
|
86
|
+
const initialize = findInitializeMessage(body);
|
|
87
|
+
const params = initialize && (0, utils_js_1.isRecord)(initialize.params) ? initialize.params : undefined;
|
|
88
|
+
if (!params)
|
|
89
|
+
return undefined;
|
|
90
|
+
const info = (0, utils_js_1.isRecord)(params.clientInfo) ? params.clientInfo : undefined;
|
|
91
|
+
const name = trimOrUndefined(info?.name);
|
|
92
|
+
if (name === undefined)
|
|
93
|
+
return undefined;
|
|
94
|
+
const version = trimOrUndefined(info?.version);
|
|
95
|
+
const protocolVersion = trimOrUndefined(params.protocolVersion);
|
|
96
|
+
return {
|
|
97
|
+
name,
|
|
98
|
+
...(version !== undefined ? { version } : {}),
|
|
99
|
+
...(protocolVersion !== undefined ? { protocolVersion } : {}),
|
|
100
|
+
capabilities: (0, utils_js_1.isRecord)(params.capabilities) ? params.capabilities : null,
|
|
101
|
+
};
|
|
102
|
+
};
|
|
103
|
+
exports.clientInfoFromInitializeBody = clientInfoFromInitializeBody;
|
|
74
104
|
const resolveStatelessHttpSession = (input) => {
|
|
75
105
|
const initialize = findInitializeMessage(input.body);
|
|
76
106
|
if (initialize) {
|
package/dist/cjs/v2.js
CHANGED
|
@@ -582,10 +582,11 @@ const wrapMcpHandler = (handler, config) => {
|
|
|
582
582
|
? fetchOptions.authInfo
|
|
583
583
|
: undefined;
|
|
584
584
|
let session;
|
|
585
|
+
let body;
|
|
585
586
|
if (request.method === "POST") {
|
|
586
587
|
try {
|
|
587
588
|
const raw = await request.clone().text();
|
|
588
|
-
|
|
589
|
+
body = raw ? JSON.parse(raw) : undefined;
|
|
589
590
|
// `initialize` exists only on the 2025 era, so `isInitialize` doubles
|
|
590
591
|
// as the legacy detector; modern-era requests fall through untouched.
|
|
591
592
|
session = (0, stateless_http_js_1.resolveStatelessHttpSession)({ body, headers: request.headers });
|
|
@@ -596,14 +597,17 @@ const wrapMcpHandler = (handler, config) => {
|
|
|
596
597
|
}
|
|
597
598
|
const response = await originalFetch(request, ...rest);
|
|
598
599
|
if (session?.isInitialize && response.ok) {
|
|
599
|
-
//
|
|
600
|
-
//
|
|
601
|
-
//
|
|
602
|
-
// initialize landed on a throwaway per-request server
|
|
600
|
+
// Full-fidelity clientInfo from the initialize body: the minted id only
|
|
601
|
+
// carries name/version, so without this the session_init would lose the
|
|
602
|
+
// negotiated protocolVersion (and capabilities) — recorded here even
|
|
603
|
+
// though the initialize landed on a throwaway per-request server
|
|
604
|
+
// instance.
|
|
605
|
+
const clientInfo = (0, stateless_http_js_1.clientInfoFromInitializeBody)(body);
|
|
603
606
|
try {
|
|
604
607
|
await state.core.recordSessionInit({
|
|
605
608
|
sessionId: session.sessionId,
|
|
606
609
|
headers: request.headers,
|
|
610
|
+
...(clientInfo !== undefined ? { clientInfo } : {}),
|
|
607
611
|
...(authInfo !== undefined ? { authInfo } : {}),
|
|
608
612
|
extra: {
|
|
609
613
|
sessionId: session.sessionId,
|
package/dist/esm/fastmcp.d.ts
CHANGED
|
@@ -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
|
package/dist/esm/fastmcp.js
CHANGED
|
@@ -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`
|
|
56
|
-
//
|
|
57
|
-
//
|
|
58
|
-
//
|
|
59
|
-
//
|
|
60
|
-
//
|
|
61
|
-
//
|
|
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,
|
|
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
|
-
|
|
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
|
|
410
|
+
return toolOrTools.map((tool) => wrapFastmcpTool(tool, state, runtime, options));
|
|
262
411
|
}
|
|
263
|
-
return wrapFastmcpTool(toolOrTools, state, runtime, options
|
|
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
|
|
461
|
+
? wrapFastmcpTool(tool, state, runtime, options)
|
|
313
462
|
: tool;
|
|
314
463
|
const originalAddTool = internals.addTool;
|
|
315
464
|
Object.defineProperty(internals, "addTool", {
|
package/dist/esm/mcp-handler.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { createAnalyticsRecorderCore, } from "./recorder-core.js";
|
|
2
2
|
import { defaultMcpAnalyticsConfig } from "./emit.js";
|
|
3
|
-
import { resolveStatelessHttpSession } from "./stateless-http.js";
|
|
4
|
-
import { isRecord } from "./utils.js";
|
|
3
|
+
import { clientInfoFromInitializeBody, resolveStatelessHttpSession, } from "./stateless-http.js";
|
|
5
4
|
const SESSION_ID_HEADER = "mcp-session-id";
|
|
6
5
|
// Keyed on the config object so every request shares one recorder (privacy
|
|
7
6
|
// queue + session_init dedupe) — hoist the config, same contract as the v2
|
|
@@ -25,35 +24,6 @@ const recorderStateFor = (config) => {
|
|
|
25
24
|
export const flushMcpHandlerAnalytics = (config) => {
|
|
26
25
|
return recorderStateFor(config).core.flush();
|
|
27
26
|
};
|
|
28
|
-
const trimOrUndefined = (value) => {
|
|
29
|
-
if (typeof value !== "string")
|
|
30
|
-
return undefined;
|
|
31
|
-
const trimmed = value.trim();
|
|
32
|
-
return trimmed.length > 0 ? trimmed : undefined;
|
|
33
|
-
};
|
|
34
|
-
// Full-fidelity clientInfo from the initialize body itself (name, version,
|
|
35
|
-
// protocolVersion, capabilities) — richer than what the minted id can carry,
|
|
36
|
-
// so the session_init recorded at initialize matches what a stateful v1
|
|
37
|
-
// deployment would report.
|
|
38
|
-
const clientInfoFromInitializeBody = (body) => {
|
|
39
|
-
const messages = Array.isArray(body) ? body : [body];
|
|
40
|
-
const initialize = messages.find((message) => isRecord(message) && message.method === "initialize");
|
|
41
|
-
const params = isRecord(initialize?.params) ? initialize.params : undefined;
|
|
42
|
-
if (!params)
|
|
43
|
-
return undefined;
|
|
44
|
-
const info = isRecord(params.clientInfo) ? params.clientInfo : undefined;
|
|
45
|
-
const name = trimOrUndefined(info?.name);
|
|
46
|
-
if (name === undefined)
|
|
47
|
-
return undefined;
|
|
48
|
-
const version = trimOrUndefined(info?.version);
|
|
49
|
-
const protocolVersion = trimOrUndefined(params.protocolVersion);
|
|
50
|
-
return {
|
|
51
|
-
name,
|
|
52
|
-
...(version !== undefined ? { version } : {}),
|
|
53
|
-
...(protocolVersion !== undefined ? { protocolVersion } : {}),
|
|
54
|
-
capabilities: isRecord(params.capabilities) ? params.capabilities : null,
|
|
55
|
-
};
|
|
56
|
-
};
|
|
57
27
|
const withSessionIdHeader = (response, sessionId) => {
|
|
58
28
|
if (response.headers.get(SESSION_ID_HEADER))
|
|
59
29
|
return response;
|
|
@@ -3,6 +3,7 @@ import type { HeaderBag, McpClientInfo } from "./types.js";
|
|
|
3
3
|
export declare const buildStatelessSessionId: (clientInfo?: McpClientInfo, sessionSeed?: string) => string;
|
|
4
4
|
/** Recover the client identity from an identity-bearing session id. */
|
|
5
5
|
export declare const parseStatelessSessionClientInfo: (sessionId: string | undefined) => McpClientInfo | undefined;
|
|
6
|
+
export declare const clientInfoFromInitializeBody: (body: unknown) => McpClientInfo | undefined;
|
|
6
7
|
export type StatelessHttpSession = {
|
|
7
8
|
/** Stable session id: minted at initialize, parsed from the echoed header otherwise. */
|
|
8
9
|
sessionId: string;
|
|
@@ -66,6 +66,35 @@ const clientInfoFromInitialize = (message) => {
|
|
|
66
66
|
...(typeof info.version === "string" ? { version: info.version } : {}),
|
|
67
67
|
};
|
|
68
68
|
};
|
|
69
|
+
const trimOrUndefined = (value) => {
|
|
70
|
+
if (typeof value !== "string")
|
|
71
|
+
return undefined;
|
|
72
|
+
const trimmed = value.trim();
|
|
73
|
+
return trimmed.length > 0 ? trimmed : undefined;
|
|
74
|
+
};
|
|
75
|
+
// Full-fidelity clientInfo from the initialize body itself (name, version,
|
|
76
|
+
// protocolVersion, capabilities) — richer than what the minted id can carry,
|
|
77
|
+
// so the session_init recorded at initialize matches what a stateful v1
|
|
78
|
+
// deployment would report. Shared by the stateless-handler wrappers
|
|
79
|
+
// (withMcpHandlerAnalytics and the v2 wrapMcpHandler legacy leg).
|
|
80
|
+
export const clientInfoFromInitializeBody = (body) => {
|
|
81
|
+
const initialize = findInitializeMessage(body);
|
|
82
|
+
const params = initialize && isRecord(initialize.params) ? initialize.params : undefined;
|
|
83
|
+
if (!params)
|
|
84
|
+
return undefined;
|
|
85
|
+
const info = isRecord(params.clientInfo) ? params.clientInfo : undefined;
|
|
86
|
+
const name = trimOrUndefined(info?.name);
|
|
87
|
+
if (name === undefined)
|
|
88
|
+
return undefined;
|
|
89
|
+
const version = trimOrUndefined(info?.version);
|
|
90
|
+
const protocolVersion = trimOrUndefined(params.protocolVersion);
|
|
91
|
+
return {
|
|
92
|
+
name,
|
|
93
|
+
...(version !== undefined ? { version } : {}),
|
|
94
|
+
...(protocolVersion !== undefined ? { protocolVersion } : {}),
|
|
95
|
+
capabilities: isRecord(params.capabilities) ? params.capabilities : null,
|
|
96
|
+
};
|
|
97
|
+
};
|
|
69
98
|
export const resolveStatelessHttpSession = (input) => {
|
|
70
99
|
const initialize = findInitializeMessage(input.body);
|
|
71
100
|
if (initialize) {
|
package/dist/esm/v2.js
CHANGED
|
@@ -6,7 +6,7 @@ import { capCapabilities } from "./events.js";
|
|
|
6
6
|
import { prepareForPreview } from "./sanitize.js";
|
|
7
7
|
import { headerValue, isRecord, stringifyPreview, truncateUtf8 } from "./utils.js";
|
|
8
8
|
import { processScopedSessionId } from "./stdio-session.js";
|
|
9
|
-
import { resolveStatelessHttpSession } from "./stateless-http.js";
|
|
9
|
+
import { clientInfoFromInitializeBody, resolveStatelessHttpSession, } from "./stateless-http.js";
|
|
10
10
|
// Adapter for the v2 MCP TypeScript SDK (@modelcontextprotocol/server 2.x,
|
|
11
11
|
// protocol revision 2026-07-28). The v2 protocol is stateless: there is no
|
|
12
12
|
// initialize handshake and no Mcp-Session-Id — client identity travels
|
|
@@ -575,10 +575,11 @@ export const wrapMcpHandler = (handler, config) => {
|
|
|
575
575
|
? fetchOptions.authInfo
|
|
576
576
|
: undefined;
|
|
577
577
|
let session;
|
|
578
|
+
let body;
|
|
578
579
|
if (request.method === "POST") {
|
|
579
580
|
try {
|
|
580
581
|
const raw = await request.clone().text();
|
|
581
|
-
|
|
582
|
+
body = raw ? JSON.parse(raw) : undefined;
|
|
582
583
|
// `initialize` exists only on the 2025 era, so `isInitialize` doubles
|
|
583
584
|
// as the legacy detector; modern-era requests fall through untouched.
|
|
584
585
|
session = resolveStatelessHttpSession({ body, headers: request.headers });
|
|
@@ -589,14 +590,17 @@ export const wrapMcpHandler = (handler, config) => {
|
|
|
589
590
|
}
|
|
590
591
|
const response = await originalFetch(request, ...rest);
|
|
591
592
|
if (session?.isInitialize && response.ok) {
|
|
592
|
-
//
|
|
593
|
-
//
|
|
594
|
-
//
|
|
595
|
-
// initialize landed on a throwaway per-request server
|
|
593
|
+
// Full-fidelity clientInfo from the initialize body: the minted id only
|
|
594
|
+
// carries name/version, so without this the session_init would lose the
|
|
595
|
+
// negotiated protocolVersion (and capabilities) — recorded here even
|
|
596
|
+
// though the initialize landed on a throwaway per-request server
|
|
597
|
+
// instance.
|
|
598
|
+
const clientInfo = clientInfoFromInitializeBody(body);
|
|
596
599
|
try {
|
|
597
600
|
await state.core.recordSessionInit({
|
|
598
601
|
sessionId: session.sessionId,
|
|
599
602
|
headers: request.headers,
|
|
603
|
+
...(clientInfo !== undefined ? { clientInfo } : {}),
|
|
600
604
|
...(authInfo !== undefined ? { authInfo } : {}),
|
|
601
605
|
extra: {
|
|
602
606
|
sessionId: session.sessionId,
|