@armature-tech/mcp-analytics 0.6.33 → 0.6.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,81 @@
1
+ import type { McpAnalyticsConfig, RequestExtra } from "./types.js";
2
+ /** Header a caller can set to pin the analytics session id (matches the v1 stateless pattern and the v2 ladder). */
3
+ export declare const FASTMCP_SESSION_SEED_HEADER = "x-armature-session-seed";
4
+ export type FastmcpToolExecute = (args: any, context?: any) => unknown | Promise<unknown>;
5
+ export type FastmcpToolLike = {
6
+ name: string;
7
+ description?: string;
8
+ parameters?: unknown;
9
+ outputSchema?: unknown;
10
+ execute?: FastmcpToolExecute;
11
+ };
12
+ export type FastmcpAdapterOptions = McpAnalyticsConfig & {
13
+ /**
14
+ * Layered on top of the adapter's own context extraction; its values win
15
+ * where both define a field (same contract as the Mastra adapter's
16
+ * `resolveExtra`). The argument is fastmcp's execute `context`.
17
+ */
18
+ resolveExtra?: (fastmcpContext: unknown) => RequestExtra | undefined;
19
+ /**
20
+ * Transport hint for the stdio-fallback decision when no session signal is
21
+ * reachable: `"stdio"` (default) buckets signal-less calls under the
22
+ * process-scoped stdio session id; `"httpStream"` suppresses that fallback
23
+ * so a long-lived HTTP server's anonymous sessions are not glued to one
24
+ * process id. `instrumentFastMCP` sniffs the real transport from
25
+ * `server.start(...)` and overrides this automatically.
26
+ */
27
+ transport?: "stdio" | "httpStream";
28
+ };
29
+ /**
30
+ * Drain the analytics pipeline tied to an options object (or the default
31
+ * config). Call before process exit when not using `delivery: "await"` or a
32
+ * `schedule` hook.
33
+ */
34
+ export declare const flushFastmcpAnalytics: (options?: FastmcpAdapterOptions) => Promise<void>;
35
+ /**
36
+ * The extra the adapter derives from fastmcp's execute context on its own:
37
+ * `context.sessionId` (the Mcp-Session-Id fastmcp surfaces on HTTP
38
+ * transports), request headers IF the user's `authenticate` copied them into
39
+ * the auth object as `headers` (`context.session.headers`), and the four
40
+ * actor-seed fields (`token`/`clientId`/`apiKey`/`principalId`) when the auth
41
+ * object carries them as strings. Exported for reuse in custom `resolveExtra`
42
+ * implementations.
43
+ */
44
+ export declare const defaultFastmcpResolveExtra: (context: unknown) => RequestExtra | undefined;
45
+ /**
46
+ * Wrap fastmcp tool definition object(s) before handing them to
47
+ * `server.addTool(...)` / `server.addTools(...)`: every call to the tool
48
+ * records a `tool_call` analytics event (timing, ok/error — including
49
+ * fastmcp's isError results and thrown errors — input/output previews) plus a
50
+ * `session_init` on first sight of each session key. The tool's result and
51
+ * every other field (`annotations`, `canAccess`, `timeoutMs`, `_meta`, …)
52
+ * pass through unchanged; wrapping an already-wrapped tool is a no-op.
53
+ *
54
+ * Hoist the options object — the recorder (delivery queue + session_init
55
+ * dedupe) is keyed on it. On an httpStream deployment pass
56
+ * `transport: "httpStream"` (or use `instrumentFastMCP`, which sniffs it from
57
+ * `server.start`).
58
+ */
59
+ export declare function withFastmcpAnalytics<T extends FastmcpToolLike>(tool: T, options?: FastmcpAdapterOptions): T;
60
+ export declare function withFastmcpAnalytics<T extends FastmcpToolLike>(tools: T[], options?: FastmcpAdapterOptions): T[];
61
+ /** Structural stand-in for a `FastMCP` server: anything with `addTool`. */
62
+ export type FastMCPLike = {
63
+ addTool: (tool: never) => unknown;
64
+ };
65
+ /**
66
+ * Instrument a `FastMCP` server instance-level (structurally typed — no
67
+ * import of the fastmcp package): every tool passed to `addTool`/`addTools`
68
+ * AFTER this call is wrapped with `withFastmcpAnalytics` semantics, and
69
+ * `server.start(...)` is sniffed for the real transport so httpStream
70
+ * deployments automatically opt out of the stdio session fallback.
71
+ *
72
+ * Limitation, stated rather than papered over: fastmcp keeps already-added
73
+ * tools in a private `#tools` field this function cannot reach — call it
74
+ * BEFORE `addTool`, or wrap earlier tools with `withFastmcpAnalytics`
75
+ * (pre-wrapped tools pass through here without double-recording). Returns the
76
+ * same (mutated) server; instrumenting twice is a no-op.
77
+ */
78
+ export declare const instrumentFastMCP: <S extends FastMCPLike>(server: S, options?: FastmcpAdapterOptions) => S;
79
+ export type { AnalyticsRecorderCore } from "./recorder-core.js";
80
+ export type { AnalyticsEventKind, AnalyticsIngestBatch, AnalyticsIngestEvent, McpAnalyticsConfig, McpClientInfo, TelemetryArgs, TelemetryEmitter, } from "./types.js";
81
+ export { defaultMcpAnalyticsConfig } from "./emit.js";
@@ -0,0 +1,351 @@
1
+ import { createAnalyticsRecorderCore, } from "./recorder-core.js";
2
+ import { defaultMcpAnalyticsConfig } from "./emit.js";
3
+ import { isCaptureEnabled, schemaDeclaresTelemetry } from "./schema.js";
4
+ import { headerValue, isRecord, mergeRequestExtra } from "./utils.js";
5
+ // Adapter for punkpeye/fastmcp (npm `fastmcp`, v1-SDK based). fastmcp routes
6
+ // tool calls through its own low-level `new Server(...)` +
7
+ // `setRequestHandler(CallToolRequestSchema, ...)` dispatcher
8
+ // (fastmcp/dist/chunk-*.js `setupToolHandlers`), so the package root's
9
+ // `McpServer.prototype` patches never see those calls — a fastmcp server was
10
+ // previously unrecorded. This module wraps the `execute` function of the tool
11
+ // definition objects users pass to `server.addTool(...)` instead.
12
+ //
13
+ // Structural typing only: NO runtime or type dependency on the `fastmcp`
14
+ // package, and none on `@modelcontextprotocol/*` either (the shared record
15
+ // pipeline in recorder-core.ts is SDK-free).
16
+ //
17
+ // Verified fastmcp API facts this adapter is built on (fastmcp 4.12.1,
18
+ // dist/FastMCP.d.ts + dist/chunk-*.js `setupToolHandlers`):
19
+ //
20
+ // - `execute(args, context)` — `args` is the Standard-Schema-validated value
21
+ // (or `undefined` when the tool declares no `parameters`); `context` carries
22
+ // `client.version` (the SDK Server's `getClientVersion()`, i.e. the
23
+ // `initialize` clientInfo), `log`, `reportProgress`, `streamContent`,
24
+ // `elicit`, `requestId` (from `params._meta.requestId`, rarely present),
25
+ // `session` (the value the user's `authenticate(request)` returned), and
26
+ // `sessionId` (the `Mcp-Session-Id`; HTTP transports only).
27
+ // - Errors: a throwing `execute` is caught by fastmcp and converted into an
28
+ // `isError: true` content result (`UserError` keeps its message verbatim,
29
+ // anything else becomes "Tool '<name>' execution failed: <message>"). A
30
+ // returned `isError: true` ContentResult passes through as-is. Both shapes
31
+ // are recorded here as failed calls; the value returned to fastmcp is
32
+ // untouched either way.
33
+ // - `tool.timeoutMs` races OUTSIDE `execute`: on timeout fastmcp returns a
34
+ // `UserError` result while the execute promise keeps running. The analytics
35
+ // event records the execute outcome (true handler duration/status), not the
36
+ // timeout envelope.
37
+ //
38
+ // What fastmcp does NOT expose to the execute context — documented limits,
39
+ // not gaps this adapter papers over:
40
+ //
41
+ // - HTTP request headers are unreachable from `execute`. `authenticate(request)`
42
+ // receives the `http.IncomingMessage`, but only what it copies into its
43
+ // return value (= `context.session`) survives. The adapter therefore reads
44
+ // `context.session.headers` when present (set `authenticate: async (req) =>
45
+ // ({ headers: req.headers, ... })` to opt in) and offers `resolveExtra` for
46
+ // anything else. Without that, the `x-armature-session-seed` and workflow
47
+ // headers are invisible and `session_init` identity comes only from
48
+ // `context.client.version`.
49
+ // - Client identity (`context.client.version`) is populated from the session's
50
+ // `initialize` handshake. In fastmcp's **stateless** httpStream mode every
51
+ // request builds a fresh session that never saw `initialize`, so it is
52
+ // `undefined` there and tool calls record an unknown client — honest, since
53
+ // nothing else in the execute context carries identity.
54
+ // - Tool input schemas are opaque Standard Schema objects that fastmcp
55
+ // validates BEFORE `execute` (advertising `additionalProperties: false`), so
56
+ // the adapter does NOT decorate schemas with the `telemetry` field (same
57
+ // decision, for the same conversion-hazard reasons, as the v2 adapter). A
58
+ // `telemetry` argument that still reaches `execute` (e.g. a passthrough zod
59
+ // object) is stripped and exported per the contract; a schema that declares
60
+ // its own top-level `telemetry` keeps owning it ("owned" mode); with capture
61
+ // off it is stripped and dropped ("scrub").
62
+ /** Header a caller can set to pin the analytics session id (matches the v1 stateless pattern and the v2 ladder). */
63
+ export const FASTMCP_SESSION_SEED_HEADER = "x-armature-session-seed";
64
+ // Wrapped execute functions and instrumented servers are tagged so re-wrapping
65
+ // (double `withFastmcpAnalytics`, `instrumentFastMCP` over pre-wrapped tools,
66
+ // double `instrumentFastMCP`) can never double-record a call.
67
+ const WRAPPED_EXECUTE = Symbol.for("armature.mcpAnalytics.fastmcp.wrappedExecute");
68
+ const WRAPPED_SERVER = Symbol.for("armature.mcpAnalytics.fastmcp.wrappedServer");
69
+ // ─── Recorder state (shared per options object) ─────────────────────────────
70
+ // Keyed on the caller's options object so every wrap call that reuses the same
71
+ // options shares one recorder (privacy queue + session_init dedupe) — the same
72
+ // hoist-the-config contract as the v2 adapter. A fresh options object per call
73
+ // still converges at ingest (event ids are content-addressed).
74
+ const recorderStatesByOptions = new WeakMap();
75
+ let defaultRecorderState;
76
+ const createRecorderState = (config) => {
77
+ const toolModes = new Map();
78
+ const core = createAnalyticsRecorderCore(config, {
79
+ isToolTelemetryOwned: (name) => toolModes.get(name) === "owned",
80
+ });
81
+ return { core, config, toolModes };
82
+ };
83
+ const recorderStateFor = (options) => {
84
+ if (options === undefined || options === defaultMcpAnalyticsConfig) {
85
+ defaultRecorderState ??= createRecorderState(defaultMcpAnalyticsConfig);
86
+ return defaultRecorderState;
87
+ }
88
+ let state = recorderStatesByOptions.get(options);
89
+ if (!state) {
90
+ const { resolveExtra: _resolveExtra, transport: _transport, ...config } = options;
91
+ state = createRecorderState(config);
92
+ recorderStatesByOptions.set(options, state);
93
+ }
94
+ return state;
95
+ };
96
+ /**
97
+ * Drain the analytics pipeline tied to an options object (or the default
98
+ * config). Call before process exit when not using `delivery: "await"` or a
99
+ * `schedule` hook.
100
+ */
101
+ export const flushFastmcpAnalytics = (options) => {
102
+ return recorderStateFor(options).core.flush();
103
+ };
104
+ // ─── Per-call capture ───────────────────────────────────────────────────────
105
+ const trimOrUndefined = (value) => {
106
+ if (typeof value !== "string")
107
+ return undefined;
108
+ const trimmed = value.trim();
109
+ return trimmed.length > 0 ? trimmed : undefined;
110
+ };
111
+ // `context.client.version` is the v1 SDK's `Implementation` from the session's
112
+ // `initialize` handshake ({ name, version }), or undefined when the session
113
+ // never saw one (fastmcp stateless httpStream mode).
114
+ const clientInfoFromContext = (context) => {
115
+ if (!isRecord(context))
116
+ return undefined;
117
+ const client = isRecord(context.client) ? context.client : undefined;
118
+ const version = isRecord(client?.version) ? client.version : undefined;
119
+ const name = trimOrUndefined(version?.name);
120
+ if (name === undefined)
121
+ return undefined;
122
+ const clientVersion = trimOrUndefined(version?.version);
123
+ return { name, ...(clientVersion !== undefined ? { version: clientVersion } : {}) };
124
+ };
125
+ const headerBagFrom = (value) => {
126
+ if (value instanceof Headers)
127
+ return value;
128
+ return isRecord(value) ? value : undefined;
129
+ };
130
+ /**
131
+ * The extra the adapter derives from fastmcp's execute context on its own:
132
+ * `context.sessionId` (the Mcp-Session-Id fastmcp surfaces on HTTP
133
+ * transports), request headers IF the user's `authenticate` copied them into
134
+ * the auth object as `headers` (`context.session.headers`), and the four
135
+ * actor-seed fields (`token`/`clientId`/`apiKey`/`principalId`) when the auth
136
+ * object carries them as strings. Exported for reuse in custom `resolveExtra`
137
+ * implementations.
138
+ */
139
+ export const defaultFastmcpResolveExtra = (context) => {
140
+ if (!isRecord(context))
141
+ return undefined;
142
+ const result = {};
143
+ const sessionId = trimOrUndefined(context.sessionId);
144
+ if (sessionId !== undefined)
145
+ result.sessionId = sessionId;
146
+ const session = isRecord(context.session) ? context.session : undefined;
147
+ const headers = headerBagFrom(session?.headers);
148
+ if (headers !== undefined)
149
+ result.requestInfo = { headers };
150
+ if (session) {
151
+ // Same four-field narrowing as the Mastra adapter: never forward arbitrary
152
+ // auth-object properties down the analytics pipeline.
153
+ const authInfo = {};
154
+ if (typeof session.token === "string")
155
+ authInfo.token = session.token;
156
+ if (typeof session.clientId === "string")
157
+ authInfo.clientId = session.clientId;
158
+ if (typeof session.apiKey === "string")
159
+ authInfo.apiKey = session.apiKey;
160
+ if (typeof session.principalId === "string") {
161
+ authInfo.principalId = session.principalId;
162
+ }
163
+ if (Object.keys(authInfo).length > 0)
164
+ result.authInfo = authInfo;
165
+ }
166
+ return Object.keys(result).length > 0 ? result : undefined;
167
+ };
168
+ // fastmcp telemetry mode, resolved once per tool at wrap time. Schemas are
169
+ // never decorated (see module comment), so "injected" here means only:
170
+ // strip-and-export a `telemetry` argument if one reaches `execute`.
171
+ const resolveFastmcpToolMode = (parameters, config) => {
172
+ const owned = schemaDeclaresTelemetry(parameters)
173
+ || schemaDeclaresTelemetry(standardSchemaJson(parameters));
174
+ if (owned)
175
+ return "owned";
176
+ return isCaptureEnabled(config) ? "injected" : "scrub";
177
+ };
178
+ // fastmcp's `jsonSchemaAdapter` (and any Standard JSON Schema-extension
179
+ // schema) carries the JSON Schema it was built from at
180
+ // `~standard.jsonSchema.input()` — the same object `schemaDeclaresTelemetry`
181
+ // already understands.
182
+ const standardSchemaJson = (parameters) => {
183
+ if (!isRecord(parameters))
184
+ return undefined;
185
+ const standard = parameters["~standard"];
186
+ if (!isRecord(standard))
187
+ return undefined;
188
+ const jsonSchema = standard.jsonSchema;
189
+ if (!isRecord(jsonSchema) || typeof jsonSchema.input !== "function") {
190
+ return undefined;
191
+ }
192
+ try {
193
+ return jsonSchema.input();
194
+ }
195
+ catch {
196
+ return undefined;
197
+ }
198
+ };
199
+ // ─── Tool wrapping ──────────────────────────────────────────────────────────
200
+ const wrapFastmcpTool = (tool, state, runtime, resolveExtra) => {
201
+ if (typeof tool?.execute !== "function")
202
+ return tool;
203
+ const originalExecute = tool.execute;
204
+ if (originalExecute[WRAPPED_EXECUTE])
205
+ return tool;
206
+ const toolName = tool.name;
207
+ const mode = resolveFastmcpToolMode(tool.parameters, state.config);
208
+ state.toolModes.set(toolName, mode);
209
+ const wrappedExecute = (args, context) => {
210
+ const base = defaultFastmcpResolveExtra(context);
211
+ const override = resolveExtra?.(context);
212
+ const extra = mergeRequestExtra(base, override);
213
+ const headers = extra?.requestInfo?.headers;
214
+ // Session-id ladder (falling priority):
215
+ // 1. An explicit `resolveExtra` sessionId — the user override.
216
+ // 2. The X-Armature-Session-Seed header, when headers are reachable
217
+ // through `context.session.headers` / `resolveExtra`.
218
+ // 3. `context.sessionId` — the Mcp-Session-Id fastmcp surfaces (HTTP
219
+ // transports; stateful mode mints it, stateless echoes the client's).
220
+ // 4. An `mcp-session-id` value inside reachable headers, then — only
221
+ // when NO headers are reachable and the transport is not known to be
222
+ // HTTP — the stdio process-scoped id (both rungs live in
223
+ // recorder-core's resolveSessionId).
224
+ // 5. undefined — the event ships with a null hint and ingest buckets it.
225
+ const seed = trimOrUndefined(headerValue(headers, FASTMCP_SESSION_SEED_HEADER));
226
+ const sessionId = override?.sessionId ?? seed ?? base?.sessionId;
227
+ // `{}` (not undefined) when the transport is known to be HTTP: recorder-
228
+ // core's stdio fallback keys on "no headers at all", and a long-lived HTTP
229
+ // server must not glue its anonymous sessions to one process id.
230
+ const effectiveHeaders = headers ?? (runtime.assumeHttp ? {} : undefined);
231
+ const clientInfo = clientInfoFromContext(context);
232
+ return state.core.instrumentToolCall({
233
+ name: toolName,
234
+ args,
235
+ telemetryMode: state.toolModes.get(toolName) ?? mode,
236
+ ctx: context,
237
+ ...(extra !== undefined ? { extra } : {}),
238
+ ...(sessionId !== undefined ? { sessionId } : {}),
239
+ ...(effectiveHeaders !== undefined ? { headers: effectiveHeaders } : {}),
240
+ ...(extra?.authInfo !== undefined ? { authInfo: extra.authInfo } : {}),
241
+ ...(clientInfo !== undefined ? { clientInfo } : {}),
242
+ // Deliberately NOT forwarding `context.requestId` as the event request
243
+ // id: it is client-supplied `_meta` data, and the contract (see
244
+ // TELEMETRY-CONTRACT.md, "tool_call request-id normalization") wants a
245
+ // freshly minted per-call id, not a transport-controlled seed.
246
+ },
247
+ // fastmcp calls execute(undefined, context) for tools without
248
+ // `parameters`; extractTelemetryArguments passes non-records through
249
+ // untouched, so `strippedArgs` is exactly what fastmcp supplied then.
250
+ (strippedArgs) => originalExecute(strippedArgs, context));
251
+ };
252
+ wrappedExecute[WRAPPED_EXECUTE] = true;
253
+ return { ...tool, execute: wrappedExecute };
254
+ };
255
+ export function withFastmcpAnalytics(toolOrTools, options) {
256
+ const state = recorderStateFor(options);
257
+ const runtime = {
258
+ assumeHttp: options?.transport === "httpStream",
259
+ };
260
+ if (Array.isArray(toolOrTools)) {
261
+ return toolOrTools.map((tool) => wrapFastmcpTool(tool, state, runtime, options?.resolveExtra));
262
+ }
263
+ return wrapFastmcpTool(toolOrTools, state, runtime, options?.resolveExtra);
264
+ }
265
+ // Mirrors fastmcp's own `#parseRuntimeConfig` precedence exactly:
266
+ // `start` options → `--transport` CLI arg (accepting the `http-stream` alias)
267
+ // → `FASTMCP_TRANSPORT` env → "stdio".
268
+ const sniffFastmcpTransport = (startOptions) => {
269
+ const explicit = isRecord(startOptions) ? startOptions.transportType : undefined;
270
+ if (explicit === "httpStream" || explicit === "stdio")
271
+ return explicit;
272
+ const args = typeof process !== "undefined" ? process.argv.slice(2) : [];
273
+ const index = args.findIndex((arg) => arg === "--transport");
274
+ const cliValue = index !== -1 ? args[index + 1] : undefined;
275
+ const fromCli = cliValue === "http-stream" ? "httpStream" : cliValue;
276
+ const fromEnv = typeof process !== "undefined"
277
+ ? process.env.FASTMCP_TRANSPORT
278
+ : undefined;
279
+ const resolved = fromCli || fromEnv || "stdio";
280
+ return resolved === "httpStream" ? "httpStream" : "stdio";
281
+ };
282
+ /**
283
+ * Instrument a `FastMCP` server instance-level (structurally typed — no
284
+ * import of the fastmcp package): every tool passed to `addTool`/`addTools`
285
+ * AFTER this call is wrapped with `withFastmcpAnalytics` semantics, and
286
+ * `server.start(...)` is sniffed for the real transport so httpStream
287
+ * deployments automatically opt out of the stdio session fallback.
288
+ *
289
+ * Limitation, stated rather than papered over: fastmcp keeps already-added
290
+ * tools in a private `#tools` field this function cannot reach — call it
291
+ * BEFORE `addTool`, or wrap earlier tools with `withFastmcpAnalytics`
292
+ * (pre-wrapped tools pass through here without double-recording). Returns the
293
+ * same (mutated) server; instrumenting twice is a no-op.
294
+ */
295
+ export const instrumentFastMCP = (server, options) => {
296
+ if (server === null || typeof server !== "object")
297
+ return server;
298
+ const internals = server;
299
+ if (internals[WRAPPED_SERVER])
300
+ return server;
301
+ if (typeof internals.addTool !== "function")
302
+ return server;
303
+ Object.defineProperty(internals, WRAPPED_SERVER, {
304
+ value: true,
305
+ configurable: true,
306
+ });
307
+ const state = recorderStateFor(options);
308
+ const runtime = {
309
+ assumeHttp: options?.transport === "httpStream",
310
+ };
311
+ const wrap = (tool) => isRecord(tool)
312
+ ? wrapFastmcpTool(tool, state, runtime, options?.resolveExtra)
313
+ : tool;
314
+ const originalAddTool = internals.addTool;
315
+ Object.defineProperty(internals, "addTool", {
316
+ configurable: true,
317
+ writable: true,
318
+ value: function instrumentedAddTool(...args) {
319
+ return originalAddTool.apply(this, [wrap(args[0]), ...args.slice(1)]);
320
+ },
321
+ });
322
+ // fastmcp's addTools does NOT delegate to addTool (both mutate `#tools`
323
+ // directly), so it needs its own wrap.
324
+ const originalAddTools = internals.addTools;
325
+ if (typeof originalAddTools === "function") {
326
+ Object.defineProperty(internals, "addTools", {
327
+ configurable: true,
328
+ writable: true,
329
+ value: function instrumentedAddTools(...args) {
330
+ const tools = Array.isArray(args[0]) ? args[0].map(wrap) : args[0];
331
+ return originalAddTools.apply(this, [tools, ...args.slice(1)]);
332
+ },
333
+ });
334
+ }
335
+ const originalStart = internals.start;
336
+ if (typeof originalStart === "function") {
337
+ Object.defineProperty(internals, "start", {
338
+ configurable: true,
339
+ writable: true,
340
+ value: function instrumentedStart(...args) {
341
+ // The started transport is ground truth; it overrides the
342
+ // `transport` option hint. `connect(transport)` (the in-process/test
343
+ // path) never runs this and keeps the stdio-like default.
344
+ runtime.assumeHttp = sniffFastmcpTransport(args[0]) === "httpStream";
345
+ return originalStart.apply(this, args);
346
+ },
347
+ });
348
+ }
349
+ return server;
350
+ };
351
+ export { defaultMcpAnalyticsConfig } from "./emit.js";
@@ -1,6 +1,6 @@
1
1
  import { createAnalyticsRecorder } from "./recorder.js";
2
2
  import { planToolTelemetry } from "./schema.js";
3
- import { isRecord } from "./utils.js";
3
+ import { isRecord, mergeRequestExtra } from "./utils.js";
4
4
  import { z } from "zod";
5
5
  import { isRequestCapabilityExplicit, REQUEST_CAPABILITY_ARGUMENT_DESCRIPTION, REQUEST_CAPABILITY_DESCRIPTION, REQUEST_CAPABILITY_TOOL_NAME, } from "./request-capability.js";
6
6
  const readMcpExtra = (mastraContext) => {
@@ -60,32 +60,7 @@ export const defaultMastraResolveExtra = (mastraContext) => {
60
60
  }
61
61
  return Object.keys(result).length > 0 ? result : undefined;
62
62
  };
63
- const mergeExtra = (base, override) => {
64
- if (!base)
65
- return override;
66
- if (!override)
67
- return base;
68
- return {
69
- ...base,
70
- ...override,
71
- ...(base.requestInfo || override.requestInfo
72
- ? {
73
- requestInfo: {
74
- ...(base.requestInfo ?? {}),
75
- ...(override.requestInfo ?? {}),
76
- },
77
- }
78
- : {}),
79
- ...(base.authInfo || override.authInfo
80
- ? {
81
- authInfo: {
82
- ...(base.authInfo ?? {}),
83
- ...(override.authInfo ?? {}),
84
- },
85
- }
86
- : {}),
87
- };
88
- };
63
+ const mergeExtra = mergeRequestExtra;
89
64
  const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
90
65
  if (typeof tool?.execute !== "function") {
91
66
  return tool;
@@ -0,0 +1,31 @@
1
+ import type { McpAnalyticsConfig } from "./types.js";
2
+ export type McpRouteHandler = (request: Request, ...rest: unknown[]) => Promise<Response>;
3
+ /** Drain the analytics pipeline tied to a config object (or the default config). */
4
+ export declare const flushMcpHandlerAnalytics: (config?: McpAnalyticsConfig) => Promise<void>;
5
+ /**
6
+ * Wrap the handler returned by mcp-handler's `createMcpHandler` so MCP client
7
+ * and session identity survive its stateless transport. Pass the SAME config
8
+ * object here and to the `withMcpAnalytics` call inside your initialize
9
+ * callback so both share one delivery pipeline configuration:
10
+ *
11
+ * ~~~ts
12
+ * const handler = withMcpHandlerAnalytics(
13
+ * createMcpHandler((server) => {
14
+ * withMcpAnalytics(analyticsConfig, () => {
15
+ * server.tool(...); // instrumented by the package root's patch
16
+ * return server;
17
+ * });
18
+ * }),
19
+ * analyticsConfig,
20
+ * );
21
+ * export { handler as POST };
22
+ * ~~~
23
+ *
24
+ * Serverless note: `createMcpHandler` runs the initialize callback PER
25
+ * REQUEST, so use `delivery: "await"` (or a `schedule`/`waitUntil` hook) —
26
+ * a per-request background queue may be frozen before it delivers.
27
+ */
28
+ export declare const withMcpHandlerAnalytics: <H extends McpRouteHandler>(handler: H, config?: McpAnalyticsConfig) => H;
29
+ export type { AnalyticsRecorderCore } from "./recorder-core.js";
30
+ export type { McpAnalyticsConfig, McpClientInfo } from "./types.js";
31
+ export { defaultMcpAnalyticsConfig } from "./emit.js";
@@ -0,0 +1,132 @@
1
+ import { createAnalyticsRecorderCore, } from "./recorder-core.js";
2
+ import { defaultMcpAnalyticsConfig } from "./emit.js";
3
+ import { resolveStatelessHttpSession } from "./stateless-http.js";
4
+ import { isRecord } from "./utils.js";
5
+ const SESSION_ID_HEADER = "mcp-session-id";
6
+ // Keyed on the config object so every request shares one recorder (privacy
7
+ // queue + session_init dedupe) — hoist the config, same contract as the v2
8
+ // adapter. A fresh config per call still converges at ingest (session_init
9
+ // event ids are content-addressed per (actor, session)).
10
+ const recorderStatesByConfig = new WeakMap();
11
+ let defaultRecorderState;
12
+ const recorderStateFor = (config) => {
13
+ if (config === undefined || config === defaultMcpAnalyticsConfig) {
14
+ defaultRecorderState ??= { core: createAnalyticsRecorderCore(defaultMcpAnalyticsConfig) };
15
+ return defaultRecorderState;
16
+ }
17
+ let state = recorderStatesByConfig.get(config);
18
+ if (!state) {
19
+ state = { core: createAnalyticsRecorderCore(config) };
20
+ recorderStatesByConfig.set(config, state);
21
+ }
22
+ return state;
23
+ };
24
+ /** Drain the analytics pipeline tied to a config object (or the default config). */
25
+ export const flushMcpHandlerAnalytics = (config) => {
26
+ return recorderStateFor(config).core.flush();
27
+ };
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
+ const withSessionIdHeader = (response, sessionId) => {
58
+ if (response.headers.get(SESSION_ID_HEADER))
59
+ return response;
60
+ const headers = new Headers(response.headers);
61
+ headers.set(SESSION_ID_HEADER, sessionId);
62
+ return new Response(response.body, {
63
+ status: response.status,
64
+ statusText: response.statusText,
65
+ headers,
66
+ });
67
+ };
68
+ /**
69
+ * Wrap the handler returned by mcp-handler's `createMcpHandler` so MCP client
70
+ * and session identity survive its stateless transport. Pass the SAME config
71
+ * object here and to the `withMcpAnalytics` call inside your initialize
72
+ * callback so both share one delivery pipeline configuration:
73
+ *
74
+ * ~~~ts
75
+ * const handler = withMcpHandlerAnalytics(
76
+ * createMcpHandler((server) => {
77
+ * withMcpAnalytics(analyticsConfig, () => {
78
+ * server.tool(...); // instrumented by the package root's patch
79
+ * return server;
80
+ * });
81
+ * }),
82
+ * analyticsConfig,
83
+ * );
84
+ * export { handler as POST };
85
+ * ~~~
86
+ *
87
+ * Serverless note: `createMcpHandler` runs the initialize callback PER
88
+ * REQUEST, so use `delivery: "await"` (or a `schedule`/`waitUntil` hook) —
89
+ * a per-request background queue may be frozen before it delivers.
90
+ */
91
+ export const withMcpHandlerAnalytics = (handler, config) => {
92
+ const state = recorderStateFor(config);
93
+ const wrapped = async (request, ...rest) => {
94
+ let session;
95
+ let body;
96
+ if (request.method === "POST") {
97
+ try {
98
+ const raw = await request.clone().text();
99
+ body = raw ? JSON.parse(raw) : undefined;
100
+ session = resolveStatelessHttpSession({ body, headers: request.headers });
101
+ }
102
+ catch {
103
+ session = undefined;
104
+ }
105
+ }
106
+ const response = await handler(request, ...rest);
107
+ if (session?.isInitialize && response.ok) {
108
+ try {
109
+ await state.core.recordSessionInit({
110
+ sessionId: session.sessionId,
111
+ headers: request.headers,
112
+ clientInfo: clientInfoFromInitializeBody(body),
113
+ extra: {
114
+ sessionId: session.sessionId,
115
+ requestInfo: { headers: request.headers },
116
+ },
117
+ });
118
+ }
119
+ catch {
120
+ // Recording is best-effort; never break the MCP response over it.
121
+ }
122
+ return withSessionIdHeader(response, session.sessionId);
123
+ }
124
+ // Echo an id the client is already carrying, so it keeps carrying it.
125
+ const echoed = request.headers.get(SESSION_ID_HEADER)?.trim();
126
+ if (echoed)
127
+ return withSessionIdHeader(response, echoed);
128
+ return response;
129
+ };
130
+ return wrapped;
131
+ };
132
+ export { defaultMcpAnalyticsConfig } from "./emit.js";
@@ -0,0 +1,24 @@
1
+ import type { ExtractedToolArguments, InstrumentToolCallEvent, McpAnalyticsConfig, McpClientInfo, RecordSessionInitEvent, RecordToolCallEvent, TelemetryMode, ToolCallHandler } from "./types.js";
2
+ export type RecorderCoreHooks = {
3
+ /**
4
+ * Session-scoped client identity lookup consulted when an event carries no
5
+ * explicit clientInfo. The v1 recorder wires the `_onrequest`-patch cache
6
+ * here; the v2 adapter passes clientInfo per event (per-request envelope)
7
+ * and needs no hook. The identity-bearing stateless session id parse runs
8
+ * as a built-in last resort either way.
9
+ */
10
+ clientInfoForSessionId?: (sessionId: string) => McpClientInfo | undefined;
11
+ /**
12
+ * True when the named tool owns its `telemetry` input field (mode "owned",
13
+ * TELEMETRY-CONTRACT.md): supplied telemetry must never be exported.
14
+ */
15
+ isToolTelemetryOwned?: (name: string) => boolean;
16
+ };
17
+ export type AnalyticsRecorderCore = {
18
+ extractTelemetry: (args: unknown, mode?: TelemetryMode) => ExtractedToolArguments;
19
+ recordToolCall: (event: RecordToolCallEvent) => Promise<void>;
20
+ recordSessionInit: (event: RecordSessionInitEvent) => Promise<void>;
21
+ instrumentToolCall: <T>(event: InstrumentToolCallEvent, handler: ToolCallHandler<T>) => Promise<T>;
22
+ flush: () => Promise<void>;
23
+ };
24
+ export declare const createAnalyticsRecorderCore: (config?: McpAnalyticsConfig, hooks?: RecorderCoreHooks) => AnalyticsRecorderCore;