@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.
package/README.md CHANGED
@@ -123,7 +123,10 @@ All telemetry fields are optional. Send **agent_thinking** on every call; send *
123
123
  | Existing server and tool registry | **instrumentMcpServerTools(...)** |
124
124
  | Custom registry or JSON-RPC dispatcher | **createAnalyticsRecorder(...)** |
125
125
  | Mastra tool map | **wrapMastraTools(...)** |
126
+ | fastmcp (`punkpeye/fastmcp`) server | **`@armature-tech/mcp-analytics/fastmcp`** — see [fastmcp](#fastmcp) |
127
+ | Vercel **mcp-handler** route | **`@armature-tech/mcp-analytics/mcp-handler`** — see [Vercel mcp-handler](#vercel-mcp-handler) |
126
128
  | Stateless HTTP or serverless | **resolveStatelessHttpSession(...)** |
129
+ | MCP SDK **v2** (`@modelcontextprotocol/server` 2.x) | **`@armature-tech/mcp-analytics/v2`** — see [MCP SDK v2](#mcp-sdk-v2-protocol-revision-2026-07-28) |
127
130
 
128
131
  ### Existing server and tool registry
129
132
 
@@ -178,6 +181,74 @@ const instrumentedTools = wrapMastraTools(tools, {
178
181
  });
179
182
  ~~~
180
183
 
184
+ ### fastmcp
185
+
186
+ fastmcp (npm `fastmcp`) dispatches tool calls through its own low-level `Server` request handler, so the McpServer-based integrations above never see them. The dedicated subpath wraps the tool definition objects instead:
187
+
188
+ ~~~ts
189
+ import { FastMCP } from "fastmcp";
190
+ import {
191
+ instrumentFastMCP,
192
+ withFastmcpAnalytics,
193
+ } from "@armature-tech/mcp-analytics/fastmcp";
194
+
195
+ // Hoist the options object: the recorder (delivery queue + session dedupe)
196
+ // is keyed on it.
197
+ const analyticsOptions = { armature: { apiKey: process.env.ANALYTICS_INGEST_API_KEY } };
198
+
199
+ const server = new FastMCP({ name: "my-server", version: "1.0.0" });
200
+
201
+ // Either instrument the server (wraps every later addTool/addTools call and
202
+ // sniffs the transport from server.start)…
203
+ instrumentFastMCP(server, analyticsOptions);
204
+ server.addTool({ name: "echo", parameters, execute });
205
+
206
+ // …or wrap individual tool definitions:
207
+ server.addTool(withFastmcpAnalytics({ name: "echo", parameters, execute }, analyticsOptions));
208
+
209
+ await server.start({ transportType: "httpStream", httpStream: { port: 8080 } });
210
+ ~~~
211
+
212
+ What is recorded: every tool call (timing, arguments/result previews, thrown errors **and** fastmcp `isError` results), plus one `session_init` per session with the client name/version fastmcp surfaces from the `initialize` handshake (`context.client.version`). The session id comes from `context.sessionId` (the `Mcp-Session-Id` on HTTP transports) or the process-scoped stdio id for stdio servers; `instrumentFastMCP` detects `httpStream` from `server.start` so anonymous HTTP sessions are never glued to one process id (pass `transport: "httpStream"` yourself when only using `withFastmcpAnalytics`).
213
+
214
+ Honest limitations, dictated by what fastmcp exposes to `execute`:
215
+
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
+ - **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.
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
+
221
+ `flushFastmcpAnalytics(options)` drains the pipeline before shutdown when not using `delivery: "await"`.
222
+
223
+ ### Vercel mcp-handler
224
+
225
+ Vercel's `mcp-handler` hands your initialize callback a real official-SDK `McpServer`, so the standard `withMcpAnalytics` wrapper covers its tool calls — run it inside the callback (which mcp-handler executes per request):
226
+
227
+ ~~~ts
228
+ import { createMcpHandler } from "mcp-handler";
229
+ import { withMcpAnalytics } from "@armature-tech/mcp-analytics";
230
+ import { withMcpHandlerAnalytics } from "@armature-tech/mcp-analytics/mcp-handler";
231
+
232
+ // Hoist the config; use "await" delivery (or schedule/waitUntil): the
233
+ // callback runs per request and a background queue may be frozen.
234
+ const analyticsConfig = { armature: { delivery: "await" as const } };
235
+
236
+ const handler = withMcpHandlerAnalytics(
237
+ createMcpHandler((server) => {
238
+ withMcpAnalytics(analyticsConfig, () => {
239
+ server.registerTool(/* … */);
240
+ return server;
241
+ });
242
+ }),
243
+ analyticsConfig,
244
+ );
245
+ export { handler as GET, handler as POST };
246
+ ~~~
247
+
248
+ Why the extra `withMcpHandlerAnalytics` wrapper: mcp-handler's streamable-HTTP transport is **stateless only** (its `sessionIdGenerator` config is typed `undefined`), so it never mints an `Mcp-Session-Id` and creates a throwaway `McpServer` per request — without the wrapper every tool call records with no session and an unknown client. The wrapper applies the v1 stateless pattern at the route handler: it sniffs `initialize` from the request body, mints an identity-bearing session id (`mcp_<name>_v_<version>_<uuid>`, honoring `X-Armature-Session-Seed`), records the `session_init` (client name/version/protocol/capabilities), and attaches the id as the response's `Mcp-Session-Id`. Conforming clients echo it on every later request, where tool calls pick it up and recover the client identity from the id itself — on any serverless instance, warm or cold. A client that never echoes the header still gets served; its calls simply keep a null session hint.
249
+
250
+ Module-format caveat: the MCP SDK ships separate ESM and CJS builds. Transitive coverage of mcp-handler holds because both packages resolve the **same** build in any consistent host (pure ESM or pure CJS, verified in this repo's compat tests). A build setup that loads this package in one format and mcp-handler in the other would split the two `McpServer` classes and silently bypass the instrumentation — keep both on one module format.
251
+
181
252
  ### Stateless HTTP and serverless
182
253
 
183
254
  Initialization and tool calls can land on different instances in stateless deployments. **resolveStatelessHttpSession** preserves the MCP client and session identity without a session store:
@@ -205,6 +276,74 @@ Use **delivery: "await"** in serverless and short-lived processes.
205
276
 
206
277
  Client attribution is best-effort observability, not a security boundary. Continue to gate access with real authentication.
207
278
 
279
+ ## MCP SDK v2 (protocol revision 2026-07-28)
280
+
281
+ Servers on the v2 package family (`@modelcontextprotocol/server` 2.x) use the dedicated subpath — the package root still targets the v1 SDK, so a v2-only install imports **only** `@armature-tech/mcp-analytics/v2`:
282
+
283
+ ~~~ts
284
+ import { createMcpHandler, McpServer } from "@modelcontextprotocol/server";
285
+ import {
286
+ instrumentedFactory,
287
+ wrapMcpHandler,
288
+ } from "@armature-tech/mcp-analytics/v2";
289
+
290
+ // Hoist the config: the recorder (delivery queue + session_init dedupe) is
291
+ // keyed on this object, so every per-request server shares one pipeline.
292
+ const analyticsConfig = {
293
+ armature: { apiKey: process.env.ANALYTICS_INGEST_API_KEY },
294
+ };
295
+
296
+ const handler = wrapMcpHandler(
297
+ createMcpHandler(
298
+ instrumentedFactory(() => {
299
+ const server = new McpServer(
300
+ { name: "my-server", version: "1.0.0" },
301
+ { capabilities: { tools: {} } },
302
+ );
303
+ server.registerTool(/* … */);
304
+ return server;
305
+ }, analyticsConfig),
306
+ ),
307
+ analyticsConfig,
308
+ );
309
+ ~~~
310
+
311
+ - **`withMcpAnalytics(server, config?)`** wraps one v2 `McpServer` instance (tools registered before or after the call) and returns the same instance — handy when you construct the server yourself, e.g. under `serveStdio`.
312
+ - **`instrumentedFactory(factory, config?)`** wraps a `createMcpHandler` / `serveStdio` factory. Because `createMcpHandler` runs the factory **per request**, this is the primary API: it shares one recorder across all produced servers and captures the factory's request context (headers, authInfo) as a fallback for handler contexts without an HTTP request.
313
+ - **`wrapMcpHandler(handler, config?)`** is optional but strongly recommended: v2's `createMcpHandler` serves 2025-era clients through a stateless legacy leg that mints **no `Mcp-Session-Id`** — porting to SDK v2 **without this wrapper silently kills legacy-client sessions** (every legacy conversation loses its session identity and falls into per-actor daily buckets). The wrapper mints an identity-bearing id (`mcp_<name>_v_<version>_<uuid>`, honoring `X-Armature-Session-Seed` as the uuid seed) on legacy `initialize` responses, records the session, and echoes the id afterwards. Modern-era requests pass through untouched.
314
+ - **`flushMcpAnalytics(config?)`** drains the pipeline tied to a config object; use it (or `delivery: "await"` / `schedule`) in serverless.
315
+
316
+ What the v2 adapter records per request:
317
+
318
+ - Client identity from the per-request `_meta` envelope (`io.modelcontextprotocol/clientInfo`, `protocolVersion`, `clientCapabilities`) — on `session_init` **and** on every `tool_call` (identity is per-request on 2026-07-28). `clientInfo` is optional in the final spec, so `client_name: null` on modern traffic is a legitimate steady state, not a bug.
319
+ - The raw request `_meta` (W3C trace slots `traceparent` / `tracestate` / `baggage` keep their bare names there) as `metadata.request_meta`, capped at 4KB with a `request_meta_truncated` marker.
320
+ - A session id resolved per request, in falling priority: `gen_ai.conversation.id` parsed from `_meta` baggage → `X-Armature-Session-Seed` header → legacy session identity (`ctx.sessionId`, then an echoed `Mcp-Session-Id` header) → the stdio process-scoped id when there is no HTTP context at all → none.
321
+
322
+ Differences from the v1 integration: the v2 adapter does **not** decorate tool input schemas with the `telemetry` field (v2 schemas are opaque Standard Schema objects; rebuilding them with a foreign zod risks the SDK's silent `tools/list` conversion failure). A `telemetry` argument sent by a client is still stripped from the handler's arguments and exported, and a schema that declares its own top-level `telemetry` property keeps owning it (never stripped, never exported). Multi-round `input_required` flows record one `tool_call` per handler round.
323
+
324
+ Both MCP SDK peers are optional: install `@modelcontextprotocol/sdk` (>=1.20 <2) for the package root, `@modelcontextprotocol/server` 2.x for `/v2`, or both.
325
+
326
+ ### v2 adapter options (`declareTelemetry`, `metadata`)
327
+
328
+ `withMcpAnalytics(server, config?, options?)` and `instrumentedFactory(factory, config?, options?)` accept a third argument, `V2AdapterOptions`:
329
+
330
+ ~~~ts
331
+ instrumentedFactory(buildServer, analyticsConfig, {
332
+ declareTelemetry: true,
333
+ metadata: (ctx) => ({ deployment: process.env.DEPLOY_ENV }),
334
+ });
335
+ ~~~
336
+
337
+ **`declareTelemetry: true`** restores v1 parity for telemetry schema advertisement (superseding the default no-decoration behavior described above): 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 v2 clients are told to send `telemetry.user_intent` / `telemetry.agent_thinking`. Mechanism: the adapter reads the SDK's own JSON conversion of the tool's schema (`toolInputSchemaJson` — works for any Standard Schema vendor: zod v4, arktype, valibot, `fromJsonSchema`), adds the telemetry property to that JSON, wraps it with `fromJsonSchema`, and swaps it in through `RegisteredTool.update({ paramsSchema })`. Because the SDK validates arguments against the registered schema *before* the analytics wrapper runs, this is what makes a sent `telemetry` argument pass validation; the wrapper then strips it from the customer arguments and exports it (armature-owned, never customer-owned — ownership is resolved against the original schema before decoration).
338
+
339
+ - 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.
340
+ - Tradeoff (why this is opt-in): validation then runs against the JSON Schema projection of your schema, via the SDK's Ajv validator. Zod runtime effects that don't survive that projection — `.transform()`, `.refine()`, applied `.default()` values — no longer run inside the SDK's validation step. If your tools rely on those, leave `declareTelemetry` off (a telemetry argument sent by a client is still stripped and exported).
341
+ - Tools whose schema declares its own top-level `telemetry` property stay customer-owned and untouched; tools whose schema can't be projected to a JSON object schema are left undecorated; `captureTelemetry: false` disables decoration entirely.
342
+
343
+ **`metadata(ctx)`** is a per-event metadata hook: it is called once per tool call with the handler context, and its returned keys are merged into the `tool_call` event's metadata (hook keys beat adapter-derived keys such as `protocol_era`; contract keys like `tool_name` always win). A throwing hook is ignored and never breaks the tool call.
344
+
345
+ The v2 adapter also stamps on every `tool_call`: `protocol_era` (`"modern"` when the request carried a 2026-07-28 `_meta` envelope, `"legacy"` otherwise), the per-request `capabilities` (same 4KB cap as `session_init`), and `user_agent` (also on `session_init`). The captured `request_meta` runs through the same preview sanitization + secret redaction pipeline as tool inputs/results before the 4KB cap is applied. `wrapMcpHandler` forwards the `fetch(request, { authInfo })` options into `session_init` actor resolution, so custom `actorId` / `actorIdentifier` resolvers see the same `authInfo` shape as on tool calls.
346
+
208
347
  ## Let your coding agent install it
209
348
 
210
349
  From your MCP server repository:
@@ -1,5 +1,6 @@
1
1
  import type { AnalyticsEventKind, AnalyticsIngestBatch, AnalyticsIngestEvent, McpClientInfo, RedactEventHook, RedactFunction, RequestExtra, TelemetryArgs } from "./types.js";
2
2
  import { type BoundedKeySet } from "./utils.js";
3
+ export declare const capCapabilities: (capabilities: McpClientInfo["capabilities"]) => Record<string, unknown> | null;
3
4
  export declare const buildActorId: ({ actorSeed, }: {
4
5
  actorSeed: string;
5
6
  }) => string;
@@ -28,6 +29,7 @@ export type BuildToolCallEventInput = {
28
29
  finishedAt: string;
29
30
  workflowRunId?: string;
30
31
  capabilityRequest?: boolean;
32
+ metadataExtra?: Record<string, unknown>;
31
33
  redact?: RedactFunction;
32
34
  redactSecrets?: boolean;
33
35
  };
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.normalizeStartedAt = exports.normalizeRequestId = exports.normalizeSessionId = exports.buildSessionInitBatch = exports.buildBatch = exports.buildSessionInitEvent = exports.finalizeToolCallEvent = exports.buildToolCallEvent = exports.buildActorIdentityEvent = exports.buildEventId = exports.buildActorId = void 0;
3
+ exports.normalizeStartedAt = exports.normalizeRequestId = exports.normalizeSessionId = exports.buildSessionInitBatch = exports.buildBatch = exports.buildSessionInitEvent = exports.finalizeToolCallEvent = exports.buildToolCallEvent = exports.buildActorIdentityEvent = exports.buildEventId = exports.buildActorId = exports.capCapabilities = void 0;
4
4
  const node_crypto_1 = require("node:crypto");
5
5
  const schema_js_1 = require("./schema.js");
6
6
  const sanitize_js_1 = require("./sanitize.js");
@@ -12,6 +12,10 @@ const trimOrUndefined = (value) => {
12
12
  const trimmed = value.trim();
13
13
  return trimmed.length > 0 ? trimmed : undefined;
14
14
  };
15
+ // Drops a client-capabilities object that would blow past the metadata byte
16
+ // cap (returns null) instead of truncating it into invalid JSON. Exported for
17
+ // the v2 adapter, which stamps per-request capabilities on tool_call events
18
+ // with the same cap as session_init.
15
19
  const capCapabilities = (capabilities) => {
16
20
  if (!(0, utils_js_1.isRecord)(capabilities))
17
21
  return null;
@@ -24,6 +28,7 @@ const capCapabilities = (capabilities) => {
24
28
  }
25
29
  return capabilities;
26
30
  };
31
+ exports.capCapabilities = capCapabilities;
27
32
  const buildActorId = ({ actorSeed, }) => {
28
33
  return (0, utils_js_1.sha256Hex)(actorSeed);
29
34
  };
@@ -150,6 +155,7 @@ const assembleToolCallEvent = (candidate, input) => {
150
155
  ok: candidate.status === "ok",
151
156
  error: candidate.errorMessage ?? null,
152
157
  metadata: {
158
+ ...(input.metadataExtra ?? {}),
153
159
  tool_name: candidate.toolName,
154
160
  user_intent: t?.user_intent ?? null,
155
161
  agent_thinking: t?.agent_thinking ?? null,
@@ -222,7 +228,7 @@ const buildSessionInitEvent = ({ actorId, sessionId, startedAt, extra, clientInf
222
228
  ?? null,
223
229
  client_version: trimOrUndefined(clientInfo?.version) ?? null,
224
230
  protocol_version: trimOrUndefined(clientInfo?.protocolVersion) ?? null,
225
- capabilities: capCapabilities(clientInfo?.capabilities),
231
+ capabilities: (0, exports.capCapabilities)(clientInfo?.capabilities),
226
232
  user_agent: (0, utils_js_1.headerValue)(extra?.requestInfo?.headers, "user-agent"),
227
233
  },
228
234
  script_source: null,
@@ -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";