@armature-tech/mcp-analytics 0.6.35 → 0.6.37
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 +7 -4
- package/dist/cjs/stateless-http.d.ts +18 -4
- package/dist/cjs/stateless-http.js +14 -2
- package/dist/cjs/v2.js +7 -4
- package/dist/esm/fastmcp.d.ts +25 -0
- package/dist/esm/fastmcp.js +164 -15
- package/dist/esm/mcp-handler.js +7 -4
- package/dist/esm/stateless-http.d.ts +18 -4
- package/dist/esm/stateless-http.js +14 -2
- package/dist/esm/v2.js +7 -4
- 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
|
@@ -78,14 +78,17 @@ const withMcpHandlerAnalytics = (handler, config) => {
|
|
|
78
78
|
}
|
|
79
79
|
}
|
|
80
80
|
const response = await handler(request, ...rest);
|
|
81
|
-
|
|
81
|
+
// `sessionId` is always minted on initialize; the check narrows the type
|
|
82
|
+
// for the non-initialize case, where it is now optional.
|
|
83
|
+
if (session?.isInitialize && session.sessionId && response.ok) {
|
|
84
|
+
const mintedSessionId = session.sessionId;
|
|
82
85
|
try {
|
|
83
86
|
await state.core.recordSessionInit({
|
|
84
|
-
sessionId:
|
|
87
|
+
sessionId: mintedSessionId,
|
|
85
88
|
headers: request.headers,
|
|
86
89
|
clientInfo: (0, stateless_http_js_1.clientInfoFromInitializeBody)(body),
|
|
87
90
|
extra: {
|
|
88
|
-
sessionId:
|
|
91
|
+
sessionId: mintedSessionId,
|
|
89
92
|
requestInfo: { headers: request.headers },
|
|
90
93
|
},
|
|
91
94
|
});
|
|
@@ -93,7 +96,7 @@ const withMcpHandlerAnalytics = (handler, config) => {
|
|
|
93
96
|
catch {
|
|
94
97
|
// Recording is best-effort; never break the MCP response over it.
|
|
95
98
|
}
|
|
96
|
-
return withSessionIdHeader(response,
|
|
99
|
+
return withSessionIdHeader(response, mintedSessionId);
|
|
97
100
|
}
|
|
98
101
|
// Echo an id the client is already carrying, so it keeps carrying it.
|
|
99
102
|
const echoed = request.headers.get(SESSION_ID_HEADER)?.trim();
|
|
@@ -5,8 +5,12 @@ export declare const buildStatelessSessionId: (clientInfo?: McpClientInfo, sessi
|
|
|
5
5
|
export declare const parseStatelessSessionClientInfo: (sessionId: string | undefined) => McpClientInfo | undefined;
|
|
6
6
|
export declare const clientInfoFromInitializeBody: (body: unknown) => McpClientInfo | undefined;
|
|
7
7
|
export type StatelessHttpSession = {
|
|
8
|
-
/**
|
|
9
|
-
|
|
8
|
+
/**
|
|
9
|
+
* Stable session id: minted at initialize, parsed from the echoed header
|
|
10
|
+
* otherwise. Undefined when the request carries neither — see
|
|
11
|
+
* `resolveStatelessHttpSession`.
|
|
12
|
+
*/
|
|
13
|
+
sessionId?: string;
|
|
10
14
|
/** Client identity recovered from the echoed session id (tool-call requests only). */
|
|
11
15
|
clientInfo?: McpClientInfo;
|
|
12
16
|
/**
|
|
@@ -17,10 +21,20 @@ export type StatelessHttpSession = {
|
|
|
17
21
|
sessionIdGenerator?: () => string;
|
|
18
22
|
/** True when the request (or any message in a batch) is `initialize`. */
|
|
19
23
|
isInitialize: boolean;
|
|
20
|
-
/**
|
|
24
|
+
/**
|
|
25
|
+
* Spread into `dispatch(name, args, { ctx, ...dispatchContext })`.
|
|
26
|
+
*
|
|
27
|
+
* When there is no session id the request headers ride along instead. The
|
|
28
|
+
* recorder reads "no session id AND no headers" as "no HTTP request at
|
|
29
|
+
* all" and falls back to the process-scoped stdio id, which would merge
|
|
30
|
+
* every concurrent conversation in a long-lived server into one session.
|
|
31
|
+
* Passing the headers keeps the request identifiable as HTTP-with-no-id,
|
|
32
|
+
* so the event ships a null hint and ingest groups it.
|
|
33
|
+
*/
|
|
21
34
|
dispatchContext: {
|
|
22
|
-
sessionId
|
|
35
|
+
sessionId?: string;
|
|
23
36
|
clientInfo?: McpClientInfo;
|
|
37
|
+
headers?: HeaderBag;
|
|
24
38
|
};
|
|
25
39
|
};
|
|
26
40
|
export declare const resolveStatelessHttpSession: (input: {
|
|
@@ -113,8 +113,20 @@ const resolveStatelessHttpSession = (input) => {
|
|
|
113
113
|
dispatchContext: { sessionId },
|
|
114
114
|
};
|
|
115
115
|
}
|
|
116
|
-
const
|
|
117
|
-
|
|
116
|
+
const sessionId = (0, utils_js_1.headerValue)(input.headers, "mcp-session-id")?.trim();
|
|
117
|
+
if (!sessionId) {
|
|
118
|
+
// No initialize to mint from and no echo to recover: either modern-era
|
|
119
|
+
// traffic (identified through `_meta` / the session seed) or a client
|
|
120
|
+
// that drops the header. Minting here would stamp a distinct id on every
|
|
121
|
+
// POST, and ingest trusts an explicit hint, so each tool call would land
|
|
122
|
+
// in its own single-event session. Reporting no id ships
|
|
123
|
+
// `session_id_hint: null` and lets ingest group by actor + client with
|
|
124
|
+
// its inactivity window instead. Matches the Go SDK's empty session id.
|
|
125
|
+
return {
|
|
126
|
+
isInitialize: false,
|
|
127
|
+
dispatchContext: input.headers ? { headers: input.headers } : {},
|
|
128
|
+
};
|
|
129
|
+
}
|
|
118
130
|
const clientInfo = (0, exports.parseStatelessSessionClientInfo)(sessionId);
|
|
119
131
|
return {
|
|
120
132
|
sessionId,
|
package/dist/cjs/v2.js
CHANGED
|
@@ -596,7 +596,10 @@ const wrapMcpHandler = (handler, config) => {
|
|
|
596
596
|
}
|
|
597
597
|
}
|
|
598
598
|
const response = await originalFetch(request, ...rest);
|
|
599
|
-
|
|
599
|
+
// `sessionId` is always minted on initialize; the check narrows the type
|
|
600
|
+
// for the non-initialize case, where it is now optional.
|
|
601
|
+
if (session?.isInitialize && session.sessionId && response.ok) {
|
|
602
|
+
const mintedSessionId = session.sessionId;
|
|
600
603
|
// Full-fidelity clientInfo from the initialize body: the minted id only
|
|
601
604
|
// carries name/version, so without this the session_init would lose the
|
|
602
605
|
// negotiated protocolVersion (and capabilities) — recorded here even
|
|
@@ -605,12 +608,12 @@ const wrapMcpHandler = (handler, config) => {
|
|
|
605
608
|
const clientInfo = (0, stateless_http_js_1.clientInfoFromInitializeBody)(body);
|
|
606
609
|
try {
|
|
607
610
|
await state.core.recordSessionInit({
|
|
608
|
-
sessionId:
|
|
611
|
+
sessionId: mintedSessionId,
|
|
609
612
|
headers: request.headers,
|
|
610
613
|
...(clientInfo !== undefined ? { clientInfo } : {}),
|
|
611
614
|
...(authInfo !== undefined ? { authInfo } : {}),
|
|
612
615
|
extra: {
|
|
613
|
-
sessionId:
|
|
616
|
+
sessionId: mintedSessionId,
|
|
614
617
|
requestInfo: { headers: request.headers },
|
|
615
618
|
...(authInfo !== undefined ? { authInfo } : {}),
|
|
616
619
|
},
|
|
@@ -619,7 +622,7 @@ const wrapMcpHandler = (handler, config) => {
|
|
|
619
622
|
catch {
|
|
620
623
|
// Recording is best-effort; never break the MCP response over it.
|
|
621
624
|
}
|
|
622
|
-
return withSessionIdHeader(response,
|
|
625
|
+
return withSessionIdHeader(response, mintedSessionId);
|
|
623
626
|
}
|
|
624
627
|
// Echo an id the legacy client is already carrying, so it keeps carrying it.
|
|
625
628
|
const echoed = request.headers.get(SESSION_ID_HEADER)?.trim();
|
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
|
@@ -74,14 +74,17 @@ export const withMcpHandlerAnalytics = (handler, config) => {
|
|
|
74
74
|
}
|
|
75
75
|
}
|
|
76
76
|
const response = await handler(request, ...rest);
|
|
77
|
-
|
|
77
|
+
// `sessionId` is always minted on initialize; the check narrows the type
|
|
78
|
+
// for the non-initialize case, where it is now optional.
|
|
79
|
+
if (session?.isInitialize && session.sessionId && response.ok) {
|
|
80
|
+
const mintedSessionId = session.sessionId;
|
|
78
81
|
try {
|
|
79
82
|
await state.core.recordSessionInit({
|
|
80
|
-
sessionId:
|
|
83
|
+
sessionId: mintedSessionId,
|
|
81
84
|
headers: request.headers,
|
|
82
85
|
clientInfo: clientInfoFromInitializeBody(body),
|
|
83
86
|
extra: {
|
|
84
|
-
sessionId:
|
|
87
|
+
sessionId: mintedSessionId,
|
|
85
88
|
requestInfo: { headers: request.headers },
|
|
86
89
|
},
|
|
87
90
|
});
|
|
@@ -89,7 +92,7 @@ export const withMcpHandlerAnalytics = (handler, config) => {
|
|
|
89
92
|
catch {
|
|
90
93
|
// Recording is best-effort; never break the MCP response over it.
|
|
91
94
|
}
|
|
92
|
-
return withSessionIdHeader(response,
|
|
95
|
+
return withSessionIdHeader(response, mintedSessionId);
|
|
93
96
|
}
|
|
94
97
|
// Echo an id the client is already carrying, so it keeps carrying it.
|
|
95
98
|
const echoed = request.headers.get(SESSION_ID_HEADER)?.trim();
|
|
@@ -5,8 +5,12 @@ export declare const buildStatelessSessionId: (clientInfo?: McpClientInfo, sessi
|
|
|
5
5
|
export declare const parseStatelessSessionClientInfo: (sessionId: string | undefined) => McpClientInfo | undefined;
|
|
6
6
|
export declare const clientInfoFromInitializeBody: (body: unknown) => McpClientInfo | undefined;
|
|
7
7
|
export type StatelessHttpSession = {
|
|
8
|
-
/**
|
|
9
|
-
|
|
8
|
+
/**
|
|
9
|
+
* Stable session id: minted at initialize, parsed from the echoed header
|
|
10
|
+
* otherwise. Undefined when the request carries neither — see
|
|
11
|
+
* `resolveStatelessHttpSession`.
|
|
12
|
+
*/
|
|
13
|
+
sessionId?: string;
|
|
10
14
|
/** Client identity recovered from the echoed session id (tool-call requests only). */
|
|
11
15
|
clientInfo?: McpClientInfo;
|
|
12
16
|
/**
|
|
@@ -17,10 +21,20 @@ export type StatelessHttpSession = {
|
|
|
17
21
|
sessionIdGenerator?: () => string;
|
|
18
22
|
/** True when the request (or any message in a batch) is `initialize`. */
|
|
19
23
|
isInitialize: boolean;
|
|
20
|
-
/**
|
|
24
|
+
/**
|
|
25
|
+
* Spread into `dispatch(name, args, { ctx, ...dispatchContext })`.
|
|
26
|
+
*
|
|
27
|
+
* When there is no session id the request headers ride along instead. The
|
|
28
|
+
* recorder reads "no session id AND no headers" as "no HTTP request at
|
|
29
|
+
* all" and falls back to the process-scoped stdio id, which would merge
|
|
30
|
+
* every concurrent conversation in a long-lived server into one session.
|
|
31
|
+
* Passing the headers keeps the request identifiable as HTTP-with-no-id,
|
|
32
|
+
* so the event ships a null hint and ingest groups it.
|
|
33
|
+
*/
|
|
21
34
|
dispatchContext: {
|
|
22
|
-
sessionId
|
|
35
|
+
sessionId?: string;
|
|
23
36
|
clientInfo?: McpClientInfo;
|
|
37
|
+
headers?: HeaderBag;
|
|
24
38
|
};
|
|
25
39
|
};
|
|
26
40
|
export declare const resolveStatelessHttpSession: (input: {
|
|
@@ -107,8 +107,20 @@ export const resolveStatelessHttpSession = (input) => {
|
|
|
107
107
|
dispatchContext: { sessionId },
|
|
108
108
|
};
|
|
109
109
|
}
|
|
110
|
-
const
|
|
111
|
-
|
|
110
|
+
const sessionId = headerValue(input.headers, "mcp-session-id")?.trim();
|
|
111
|
+
if (!sessionId) {
|
|
112
|
+
// No initialize to mint from and no echo to recover: either modern-era
|
|
113
|
+
// traffic (identified through `_meta` / the session seed) or a client
|
|
114
|
+
// that drops the header. Minting here would stamp a distinct id on every
|
|
115
|
+
// POST, and ingest trusts an explicit hint, so each tool call would land
|
|
116
|
+
// in its own single-event session. Reporting no id ships
|
|
117
|
+
// `session_id_hint: null` and lets ingest group by actor + client with
|
|
118
|
+
// its inactivity window instead. Matches the Go SDK's empty session id.
|
|
119
|
+
return {
|
|
120
|
+
isInitialize: false,
|
|
121
|
+
dispatchContext: input.headers ? { headers: input.headers } : {},
|
|
122
|
+
};
|
|
123
|
+
}
|
|
112
124
|
const clientInfo = parseStatelessSessionClientInfo(sessionId);
|
|
113
125
|
return {
|
|
114
126
|
sessionId,
|
package/dist/esm/v2.js
CHANGED
|
@@ -589,7 +589,10 @@ export const wrapMcpHandler = (handler, config) => {
|
|
|
589
589
|
}
|
|
590
590
|
}
|
|
591
591
|
const response = await originalFetch(request, ...rest);
|
|
592
|
-
|
|
592
|
+
// `sessionId` is always minted on initialize; the check narrows the type
|
|
593
|
+
// for the non-initialize case, where it is now optional.
|
|
594
|
+
if (session?.isInitialize && session.sessionId && response.ok) {
|
|
595
|
+
const mintedSessionId = session.sessionId;
|
|
593
596
|
// Full-fidelity clientInfo from the initialize body: the minted id only
|
|
594
597
|
// carries name/version, so without this the session_init would lose the
|
|
595
598
|
// negotiated protocolVersion (and capabilities) — recorded here even
|
|
@@ -598,12 +601,12 @@ export const wrapMcpHandler = (handler, config) => {
|
|
|
598
601
|
const clientInfo = clientInfoFromInitializeBody(body);
|
|
599
602
|
try {
|
|
600
603
|
await state.core.recordSessionInit({
|
|
601
|
-
sessionId:
|
|
604
|
+
sessionId: mintedSessionId,
|
|
602
605
|
headers: request.headers,
|
|
603
606
|
...(clientInfo !== undefined ? { clientInfo } : {}),
|
|
604
607
|
...(authInfo !== undefined ? { authInfo } : {}),
|
|
605
608
|
extra: {
|
|
606
|
-
sessionId:
|
|
609
|
+
sessionId: mintedSessionId,
|
|
607
610
|
requestInfo: { headers: request.headers },
|
|
608
611
|
...(authInfo !== undefined ? { authInfo } : {}),
|
|
609
612
|
},
|
|
@@ -612,7 +615,7 @@ export const wrapMcpHandler = (handler, config) => {
|
|
|
612
615
|
catch {
|
|
613
616
|
// Recording is best-effort; never break the MCP response over it.
|
|
614
617
|
}
|
|
615
|
-
return withSessionIdHeader(response,
|
|
618
|
+
return withSessionIdHeader(response, mintedSessionId);
|
|
616
619
|
}
|
|
617
620
|
// Echo an id the legacy client is already carrying, so it keeps carrying it.
|
|
618
621
|
const echoed = request.headers.get(SESSION_ID_HEADER)?.trim();
|