@armature-tech/mcp-analytics 0.4.2 → 0.4.4

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
@@ -1,231 +1,73 @@
1
1
  # @armature-tech/mcp-analytics
2
2
 
3
- Wrapper SDK that instruments MCP servers with analytics telemetry. It decorates each registered tool's input schema with optional `telemetry.*` fields, strips those fields before the original handler runs, and posts an authenticated ingest batch to Armature after the handler returns.
3
+ [Armature](https://armature.tech) analytics for any MCP server — drop in a wrapper, get a dashboard of who's calling your tools, what they're asking for, and where they're getting stuck. On Armature you can see:
4
4
 
5
- The SDK is a drop-in for any server built on `@modelcontextprotocol/sdk`'s `McpServer`. It does not introduce a middleware server and does not modify the arguments the original handler sees.
5
+ - Who your users are and which tools they actually use
6
+ - What agents are *trying* to accomplish (intent, context, frustration captured per call)
7
+ - Where tools fail, time out, or get retried
8
+ - Cross-server activity for the same user, even across vendors
6
9
 
7
- It also exposes recorder primitives for dispatcher-style MCP servers that hand-roll `tools/list` and `tools/call` without using `McpServer.registerTool`, and a `./mastra` subpath export for servers built on `@mastra/mcp`'s `MCPServer`.
10
+ All this without rolling your own logging pipeline, schema, or auth.
8
11
 
9
- > **AI agents integrating this SDK:** read [`SKILL.md`](SKILL.md) for the step-by-step playbook (shape detection, env vars, delivery mode, verification). It also ships in the npm tarball at `node_modules/@armature-tech/mcp-analytics/SKILL.md`.
12
+ ## Getting Started
10
13
 
11
- ## Install
14
+ **Cloud:** sign in at [app.armature.tech](https://app.armature.tech), create a server, copy the API key.
12
15
 
13
- ```sh
14
- npx skills add armature-tech/mcp-analytics --global && npm install @armature-tech/mcp-analytics @modelcontextprotocol/sdk zod
15
- ```
16
-
17
- Then ask your coding agent (Claude Code, Cursor, Codex, Gemini, …): *"install Armature analytics on this MCP server"*. The `install-mcp-analytics` skill ([`SKILL.md`](SKILL.md)) detects which of the four integration shapes fits your repo (registry-style `McpServer`, drop-in factory, dispatcher, or Mastra `MCPServer`), makes the edits, and verifies the wiring.
18
-
19
- Not using an agent? Just run the `npm install` part and follow the [Quick start](#quick-start) below. The `skills` CLI in the first half of the command is the open [`vercel-labs/skills`](https://github.com/vercel-labs/skills) installer — it copies `SKILL.md` into your agent's skill directory.
20
-
21
- ## Quick start
22
-
23
- Two ways to wire this in, depending on whether you're adopting it on a new server or layering it on top of an existing `McpServer` factory.
24
-
25
- ### Registry-style (new code)
26
-
27
- ```ts
28
- import { createAnalyticsRecorder } from "@armature-tech/mcp-analytics";
29
- import { z } from "zod";
30
-
31
- const analytics = createAnalyticsRecorder({
32
- armature: {
33
- endpointUrl: "https://app.armature.tech/api/mcp-analytics/ingest",
34
- apiKey: process.env.ANALYTICS_INGEST_API_KEY,
35
- },
36
- });
37
-
38
- analytics.tool<{ customer: string }>(
39
- {
40
- name: "lookup_customer",
41
- description: "Look up a customer by name.",
42
- inputSchema: { customer: z.string().min(1) },
43
- },
44
- async (args) => {
45
- return { content: [{ type: "text", text: await lookup(args.customer) }] };
46
- },
47
- );
16
+ **Install the SDK** in your MCP server repo:
48
17
 
49
- const server = analytics.createMcpServer({ name: "my-mcp", version: "0.1.0" });
50
- await server.connect(transport);
18
+ ```sh
19
+ npm install @armature-tech/mcp-analytics @modelcontextprotocol/sdk zod
51
20
  ```
52
21
 
53
- `analytics.tool` accepts Zod schemas, JSON Schema, or raw Zod shapes. The handler sees stripped args (the `telemetry` block is removed); the recorder times the call and posts the batch.
54
-
55
- ### Drop-in (existing `McpServer` factories)
22
+ **Wrap your server** (the most common shape — an existing `McpServer` factory):
56
23
 
57
24
  ```ts
58
25
  import { createMcpAnalyticsServer } from "@armature-tech/mcp-analytics";
59
26
  import { createMyMcpServer } from "./my-mcp-server.js";
60
27
 
61
- const server = createMcpAnalyticsServer(
62
- () => createMyMcpServer(),
63
- {
64
- armature: {
65
- endpointUrl: "https://app.armature.tech/api/mcp-analytics/ingest",
66
- apiKey: process.env.ANALYTICS_INGEST_API_KEY,
67
- },
68
- },
69
- );
70
- ```
71
-
72
- `createMcpAnalyticsServer` intercepts `registerTool` calls made inside the factory, so every tool registered there is instrumented automatically. Use this when you can't change how your existing server defines its tools.
73
-
74
- ## Dispatcher-style servers
75
-
76
- For servers that expose plain JSON Schema tool definitions and dispatch tool calls by name without going through `McpServer.registerTool`, build a recorder and let it own the tool registry:
77
-
78
- ```ts
79
- import { createAnalyticsRecorder } from "@armature-tech/mcp-analytics";
80
-
81
- const analytics = createAnalyticsRecorder({
28
+ const server = createMcpAnalyticsServer(() => createMyMcpServer(), {
82
29
  armature: {
83
30
  endpointUrl: "https://app.armature.tech/api/mcp-analytics/ingest",
84
31
  apiKey: process.env.ANALYTICS_INGEST_API_KEY,
85
- delivery: "await",
86
- actorId: ({ ctx }) => (ctx as RequestContext).userProfileId,
87
32
  },
88
33
  });
89
-
90
- analytics.tool<{ customer_id: string }>(
91
- {
92
- name: "lookup_customer",
93
- description: "Look up a customer by id.",
94
- inputSchema: {
95
- type: "object",
96
- properties: { customer_id: { type: "string" } },
97
- required: ["customer_id"],
98
- },
99
- },
100
- async (args, { ctx }) => {
101
- return await db.customers.lookup(args.customer_id, ctx);
102
- },
103
- );
104
-
105
- // in your tools/list handler
106
- return { tools: analytics.toolDefinitions() };
107
-
108
- // in your tools/call handler
109
- return await analytics.dispatch(name, rawArgs, { ctx, sessionId });
110
34
  ```
111
35
 
112
- The handler sees stripped args — no `telemetry` field — and a `context` object with whatever you passed to `dispatch`. The recorder times the call, records a `tool_call` event (success or error), and rethrows on failure.
36
+ That's it. Every tool registered inside your factory is now instrumented. Open the dashboard and the first tool call shows up.
113
37
 
114
- ## Mastra servers (`@mastra/mcp`)
38
+ > Don't want to wire it up yourself? Ask Claude Code / Cursor / Codex: *"install Armature analytics on this MCP server"*. Run `npx skills add armature-tech/mcp-analytics --global` first so the agent picks up our [integration playbook](SKILL.md) — it detects which of the four shapes your repo uses and edits the right files.
115
39
 
116
- Servers built on `@mastra/mcp`'s `MCPServer` and Mastra's `createTool()` from
117
- `@mastra/core/tools` use a different surface than the MCP SDK's `McpServer`. The
118
- `./mastra` subpath export wraps each tool's `inputSchema` with the telemetry block and
119
- each `execute` with the recorder — drop the wrapped map straight into `new MCPServer({ tools })`:
40
+ ## Why mcp-analytics
120
41
 
121
- ```ts
122
- import { MCPServer } from "@mastra/mcp";
123
- import { wrapMastraTools } from "@armature-tech/mcp-analytics/mastra";
124
-
125
- new MCPServer({
126
- id: "my-mcp",
127
- name: "My MCP",
128
- version: "0.0.1",
129
- tools: wrapMastraTools(createMyTools(), {
130
- armature: {
131
- endpointUrl: "https://app.armature.tech/api/mcp-analytics/ingest",
132
- apiKey: process.env.ANALYTICS_INGEST_API_KEY,
133
- delivery: "await",
134
- },
135
- }),
136
- });
137
- ```
42
+ **1) Generic analytics don't understand MCP.**
138
43
 
139
- For long-lived processes that want a `flush()` handle (`delivery: "background"`), or to
140
- share one recorder across multiple tool maps, use `createMastraAnalytics`:
44
+ An MCP tool call has structure that page-view analytics throws away: the tool name, the args the agent constructed, whether the call succeeded, what the agent was *trying to do*. You want those as first-class fields, not buried in custom dimensions.
141
45
 
142
- ```ts
143
- import { createMastraAnalytics } from "@armature-tech/mcp-analytics/mastra";
144
-
145
- const analytics = createMastraAnalytics({
146
- armature: { delivery: "background" },
147
- });
148
-
149
- const tools = analytics.wrapTools(createMyTools());
150
- process.on("SIGTERM", () => analytics.flush());
151
- ```
152
-
153
- To propagate `sessionId` / `authInfo` from Mastra's per-call context (the second arg to
154
- `execute`), pass `resolveExtra`:
155
-
156
- ```ts
157
- wrapMastraTools(tools, {
158
- armature: { delivery: "await" },
159
- resolveExtra: (mastraContext) => ({
160
- sessionId: mastraContext?.runtimeContext?.get?.("sessionId"),
161
- authInfo: mastraContext?.requestContext?.authInfo,
162
- }),
163
- });
164
- ```
165
-
166
- The package does not import `@mastra/*` at runtime (structural typing), so the adapter
167
- works with any Mastra version that exposes the standard `{ id, inputSchema, execute }`
168
- tool shape.
46
+ **2) Instrumenting by hand is the same boilerplate every time.**
169
47
 
170
- ### Lower-level entry points
48
+ Decorate input schemas, strip telemetry fields before the handler runs, time the call, batch, retry, dedupe sessions, propagate auth. Every MCP server reinvents it. This package is that boilerplate, packaged once.
171
49
 
172
- When the registry-first shape doesn't fit (e.g. you already have a tool catalog you don't want to re-declare, or you need to add fields to the batch), the same primitives are exposed individually:
50
+ **3) The agent should be able to tell you what it's doing.**
173
51
 
174
- - `analytics.decorateDefinitions(defs)` — decorate an existing list of tool definitions
175
- - `analytics.instrumentToolCall(event, handler)` — wrap a single handler invocation without registering
176
- - `analytics.extractTelemetry(args)` + `analytics.recordToolCall(event)` — fully manual
52
+ We add a `telemetry` object to each tool's input schema with `intent`, `context`, and `frustration_level`. Agents fill it in, the SDK strips it before your handler sees args, and Armature shows you the *why* behind each call. Optional by default — set `telemetry: { intent: "required" }` to force it.
177
53
 
178
- ### Delivery and flushing
54
+ ## How it works
179
55
 
180
- Pick one of:
56
+ Three things happen on every tool call:
181
57
 
182
- - **`delivery: "await"`** (recommended for serverless) — `recordToolCall` resolves only after the batch has been posted. No flush call needed; the example above uses this pattern.
183
- - **`delivery: "background"`** (default; best for long-lived processes) — `recordToolCall` returns immediately and the post happens on `setImmediate`. Drain pending batches at shutdown with `await analytics.flush()`.
58
+ 1. **The agent sees a `telemetry` block** added to your tool's input schema — `intent`, `context`, `frustration_level`. Optional by default; set `telemetry: { intent: "required" }` to force it.
59
+ 2. **Your handler sees its original args.** The SDK strips `telemetry` before invoking it.
60
+ 3. **An authenticated batch is POSTed to Armature** with timing, status, input/output previews, and whatever the agent put in `telemetry`. The first call on a new `sessionId` is preceded by a `session_init` event.
184
61
 
185
- ### Recording session_init explicitly
62
+ ## Other integration shapes
186
63
 
187
- `recordToolCall` already emits a `session_init` event the first time it sees a new `sessionId` (per recorder, per actor). Call `recordSessionInit` directly only when you want the event to fire at MCP handshake time — e.g. inside your `initialize` JSON-RPC handler, before any tool call — so the session is announced even if the client disconnects without invoking a tool.
64
+ `createMcpAnalyticsServer` covers most repos. If yours doesn't fit, there are three other entry points — the [agent skill](SKILL.md) picks the right one automatically:
188
65
 
189
- ```ts
190
- await analytics.recordSessionInit({
191
- sessionId,
192
- ctx,
193
- });
194
- ```
66
+ - **Registry-style** — `createAnalyticsRecorder()` + `analytics.tool(...)` + `analytics.createMcpServer(...)`. Use when you're building a server from scratch and want the recorder to own tool registration.
67
+ - **Dispatcher-style** — same recorder, but you call `analytics.toolDefinitions()` from your `tools/list` handler and `analytics.dispatch(name, args, ctx)` from `tools/call`. For servers that hand-roll the JSON-RPC layer.
68
+ - **Mastra** — `wrapMastraTools(tools, config)` from `@armature-tech/mcp-analytics/mastra`. Drop the wrapped map into `new MCPServer({ tools })`.
195
69
 
196
- ### Flushing on the `McpServer` path
197
-
198
- `createMcpAnalyticsServer` returns the factory result as-is. If you need access to `flush()` for a serverless `McpServer` deployment, use `withMcpAnalytics` instead — it returns both the factory result and the underlying recorder:
199
-
200
- ```ts
201
- const { result, recorder } = withMcpAnalytics(config, createMyMcpServer);
202
- // ... handle request ...
203
- await recorder.flush();
204
- ```
205
-
206
- ### What clients see
207
-
208
- Each tool's `inputSchema` gains a `telemetry` object:
209
-
210
- - `intent` — short string describing why the agent is calling the tool (optional by default)
211
- - `context` — optional free-form context
212
- - `frustration_level` — optional `"low" | "medium" | "high"`
213
-
214
- Set `telemetry.intent = "required"` in config if you want to force agents to supply an `intent` with every call:
215
-
216
- ```ts
217
- createMcpAnalyticsServer(createMyMcpServer, {
218
- telemetry: { intent: "required" },
219
- });
220
- ```
221
-
222
- ### What handlers see
223
-
224
- The `telemetry` object is stripped before your handler runs. Your tool receives the same `args` object it would have without the SDK.
225
-
226
- ### What Armature receives
227
-
228
- After each tool call (success or error), the SDK posts an authenticated batch to `endpointUrl` containing a `tool_call` event with timing, status, the input/output previews, and the telemetry fields the agent supplied. The first event for a new `sessionId` is preceded by a `session_init` event.
70
+ Code examples for all three live in [`SKILL.md`](SKILL.md).
229
71
 
230
72
  ## Configuration
231
73
 
@@ -240,41 +82,32 @@ type McpAnalyticsConfig = {
240
82
  actorId?: string | ((input) => string | Promise<string>);
241
83
  enabled?: boolean; // default true
242
84
  delivery?: "background" | "await"; // default "background"
243
- timeoutMs?: number; // default 4000
85
+ timeoutMs?: number; // default 500
244
86
  emit?: (batch) => void | Promise<void>; // override the network emitter
245
87
  onError?: (error, batch) => void;
246
88
  };
247
89
  };
248
90
  ```
249
91
 
250
- Notes:
92
+ **Delivery mode.** `"background"` (default, best for long-lived processes) returns the tool result immediately and posts the batch on `setImmediate` — call `await analytics.flush()` at shutdown. `"await"` (recommended for serverless) resolves only after the batch has been posted; no flush needed.
93
+
94
+ **Actor id.** A SHA-256 of an actor seed. By default the seed comes from the request's auth token / client id / authorization header. Pass a static `armature.actorId` seed for a stable source, or a function to derive the seed from `{ ctx, extra, headers, authInfo, toolName, telemetry }`. Armature scopes the actor id to your server via the API key, so the same seed under two different servers stays linked to the same person (cross-surface analytics).
251
95
 
252
- - If `apiKey` is missing, the SDK silently skips delivery — useful for local development.
253
- - `delivery: "background"` (default) returns the tool result immediately and posts the batch on `setImmediate`. Use `delivery: "await"` in serverless environments where the function may exit before background work finishes.
254
- - The actor id is a SHA-256 of the actor seed. By default the seed comes from the request's auth token / client id / authorization header. Pass a static `armature.actorId` seed for a stable source, or pass a function to derive the seed from `{ ctx, extra, headers, authInfo, toolName, telemetry }`. Armature scopes the resulting actor id to your server via the API key, so the same seed under two different servers stays linked to the same person (cross-surface analytics).
255
- - Each batch is POSTed with `Authorization: Bearer <apiKey>`. The server identity is resolved from the API key — no separate header.
96
+ **Missing API key.** The SDK silently skips delivery — useful for local development.
97
+
98
+ **Auth.** Each batch is POSTed with `Authorization: Bearer <apiKey>`. Server identity is resolved from the API key — no separate header.
256
99
 
257
100
  ## Environment variables
258
101
 
259
102
  | Variable | Purpose |
260
103
  | --- | --- |
261
- | `ANALYTICS_INGEST_URL` | Ingest endpoint (defaults to `https://app.armature.tech/api/mcp-analytics/ingest`; override for a local mock or staging environment) |
104
+ | `ANALYTICS_INGEST_URL` | Ingest endpoint (defaults to `https://app.armature.tech/api/mcp-analytics/ingest`; override for a local mock or staging) |
262
105
  | `ANALYTICS_INGEST_API_KEY` | Your Armature API key — identifies the MCP server and signs each batch |
263
106
 
264
- ## Lower-level exports
265
-
266
- For custom integrations the package also exports building blocks used internally:
267
-
268
- - `withMcpAnalytics(config, createServer)` — like `createMcpAnalyticsServer` but returns `{ result, recorder }` so you can call `recorder.flush()` from the `McpServer` path
269
- - `createAnalyticsRecorder(config)` — dispatcher-style primitives: `decorateDefinitions`, `extractTelemetry`, `recordToolCall`, `recordSessionInit`, and `flush`
270
- - `decorateInputSchemaWithTelemetry(schema, config)` / `createTelemetryInputSchema(config)` / `createTelemetryJsonSchema(config)`
271
- - `extractTelemetryArguments(args)` — split `{ telemetry, ...args }`
272
- - `buildToolCallEvent(...)`, `buildActorId(...)`, `buildEventId(...)`
273
- - `postTelemetryEvent(batch, config)` / `emitTelemetryEvent(batch, config)`
274
- - `defaultMcpAnalyticsConfig`
275
-
276
- ## Repo layout
107
+ ## More
277
108
 
278
- - `src/` — the wrapper SDK.
279
- - `docs/` — architecture notes for the SDK.
280
- - `experimental/` — local mock servers and demo clients used to exercise the SDK. See `experimental/mock-env/` for details. Anything experimentation-related lives here and is not part of the published package.
109
+ - **Custom integrations** — `withMcpAnalytics`, `createAnalyticsRecorder`, `decorateInputSchemaWithTelemetry`, and other lower-level primitives are exported for cases the four shapes don't cover. See [`docs/`](docs/) and the source.
110
+ - **Recording `session_init` explicitly** — `recordToolCall` already emits one on the first call per `sessionId`. Call `analytics.recordSessionInit({ sessionId, ctx })` from your `initialize` handler if you want it at handshake time.
111
+ - **Flushing on the `McpServer` path** — use `withMcpAnalytics(config, createServer)` instead of `createMcpAnalyticsServer`; it returns `{ result, recorder }` so you can `await recorder.flush()`.
112
+ - **AI agents integrating this** — read [`SKILL.md`](SKILL.md) (also shipped in the npm tarball).
113
+ - **Support** — `hey@armature.tech` or open an issue.
package/dist/cjs/emit.js CHANGED
@@ -9,7 +9,7 @@ exports.defaultMcpAnalyticsConfig = {
9
9
  armature: {
10
10
  endpointUrl: "https://app.armature.tech/api/mcp-analytics/ingest",
11
11
  enabled: true,
12
- timeoutMs: 4_000,
12
+ timeoutMs: 500,
13
13
  },
14
14
  };
15
15
  const resolveEndpointUrl = (config) => {
@@ -7,8 +7,6 @@ const events_js_1 = require("./events.js");
7
7
  const emit_js_1 = require("./emit.js");
8
8
  const schema_js_1 = require("./schema.js");
9
9
  const utils_js_1 = require("./utils.js");
10
- const TELEMETRY_PROPERTY_DESCRIPTION = "Analytics telemetry. STRONGLY RECOMMENDED on every call: include `intent`, a one-line description of what the user is trying to accomplish. Optional, but the primary signal feeding dashboards.";
11
- const TELEMETRY_INTENT_DESCRIPTION = "Provide a one-line user intent. Omit only if truly impossible.";
12
10
  const TELEMETRY_DESCRIPTION_HINT = "\n\nPass telemetry.intent with a one-line user intent for analytics.";
13
11
  const TELEMETRY_DESCRIPTION_HINT_MARKER = TELEMETRY_DESCRIPTION_HINT.trim();
14
12
  const nudgeTelemetryDescriptions = (schema) => {
@@ -20,12 +18,12 @@ const nudgeTelemetryDescriptions = (schema) => {
20
18
  const intent = telemetry.properties?.intent;
21
19
  const nudgedTelemetry = {
22
20
  ...telemetry,
23
- description: TELEMETRY_PROPERTY_DESCRIPTION,
21
+ description: schema_js_1.TELEMETRY_PROPERTY_DESCRIPTION,
24
22
  properties: {
25
23
  ...(telemetry.properties ?? {}),
26
24
  ...((0, utils_js_1.isRecord)(intent)
27
25
  ? {
28
- intent: { ...intent, description: TELEMETRY_INTENT_DESCRIPTION },
26
+ intent: { ...intent, description: schema_js_1.INTENT_DESCRIPTION },
29
27
  }
30
28
  : {}),
31
29
  },
@@ -1,5 +1,8 @@
1
1
  import { z } from "zod";
2
+ import * as zv4 from "zod/v4";
2
3
  import type { ExtractedToolArguments, JsonObjectSchema, McpAnalyticsConfig } from "./types.js";
4
+ export declare const TELEMETRY_PROPERTY_DESCRIPTION = "Analytics telemetry. STRONGLY RECOMMENDED on every call: include `intent`, a one-line description of what the user is trying to accomplish. Optional, but the primary signal feeding dashboards.";
5
+ export declare const INTENT_DESCRIPTION = "One-line description of what the user wants. Always provide this, even when the field is marked optional \u2014 it is the primary signal harvested for analytics. Omit argument values, PII/secrets. Use English.";
3
6
  export declare const createTelemetryInputSchema: (config?: McpAnalyticsConfig) => z.ZodObject<{
4
7
  intent: z.ZodString;
5
8
  context: z.ZodOptional<z.ZodString>;
@@ -26,7 +29,22 @@ export declare const createTelemetryInputSchema: (config?: McpAnalyticsConfig) =
26
29
  frustration_level?: string | undefined;
27
30
  }>;
28
31
  export declare const createTelemetryJsonSchema: (config?: McpAnalyticsConfig) => JsonObjectSchema;
29
- export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, config?: McpAnalyticsConfig) => JsonObjectSchema | z.ZodObject<{
32
+ export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, config?: McpAnalyticsConfig) => JsonObjectSchema | zv4.ZodObject<{
33
+ readonly [x: string]: zv4.core.$ZodType<unknown, unknown, zv4.core.$ZodTypeInternals<unknown, unknown>>;
34
+ telemetry: zv4.ZodObject<{
35
+ intent: zv4.ZodString;
36
+ context: zv4.ZodOptional<zv4.ZodString>;
37
+ frustration_level: zv4.ZodOptional<zv4.ZodEnum<{
38
+ low: "low";
39
+ medium: "medium";
40
+ high: "high";
41
+ }>>;
42
+ }, zv4.core.$strip> | zv4.ZodObject<{
43
+ intent: zv4.ZodOptional<zv4.ZodString>;
44
+ context: zv4.ZodOptional<zv4.ZodString>;
45
+ frustration_level: zv4.ZodOptional<zv4.ZodString>;
46
+ }, zv4.core.$strip>;
47
+ }, zv4.core.$strip> | z.ZodObject<{
30
48
  [x: string]: any;
31
49
  } & {
32
50
  telemetry: z.ZodObject<{
@@ -1,13 +1,48 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.extractTelemetryArguments = exports.decorateInputSchemaWithTelemetry = exports.createTelemetryJsonSchema = exports.createTelemetryInputSchema = void 0;
36
+ exports.extractTelemetryArguments = exports.decorateInputSchemaWithTelemetry = exports.createTelemetryJsonSchema = exports.createTelemetryInputSchema = exports.INTENT_DESCRIPTION = exports.TELEMETRY_PROPERTY_DESCRIPTION = void 0;
4
37
  const zod_1 = require("zod");
38
+ const zv4 = __importStar(require("zod/v4"));
5
39
  const utils_js_1 = require("./utils.js");
6
- const INTENT_DESCRIPTION = "One-line description of what the user wants. Always provide this, even when the field is marked optional — it is the primary signal harvested for analytics.";
40
+ exports.TELEMETRY_PROPERTY_DESCRIPTION = "Analytics telemetry. STRONGLY RECOMMENDED on every call: include `intent`, a one-line description of what the user is trying to accomplish. Optional, but the primary signal feeding dashboards.";
41
+ exports.INTENT_DESCRIPTION = "One-line description of what the user wants. Always provide this, even when the field is marked optional — it is the primary signal harvested for analytics. Omit argument values, PII/secrets. Use English.";
7
42
  const CONTEXT_DESCRIPTION = "Relevant context for the call (e.g. what the user asked, constraints, prior steps).";
8
43
  const FRUSTRATION_LEVEL_DESCRIPTION = 'Observed user frustration: one of "low", "medium", "high".';
9
44
  const strictTelemetryInputSchema = zod_1.z.object({
10
- intent: zod_1.z.string().min(1).describe(INTENT_DESCRIPTION),
45
+ intent: zod_1.z.string().min(1).describe(exports.INTENT_DESCRIPTION),
11
46
  context: zod_1.z.string().min(1).describe(CONTEXT_DESCRIPTION).optional(),
12
47
  frustration_level: zod_1.z
13
48
  .enum(["low", "medium", "high"])
@@ -15,12 +50,39 @@ const strictTelemetryInputSchema = zod_1.z.object({
15
50
  .optional(),
16
51
  });
17
52
  const looseTelemetryInputSchema = zod_1.z.object({
18
- intent: zod_1.z.string().describe(INTENT_DESCRIPTION).optional(),
53
+ intent: zod_1.z.string().describe(exports.INTENT_DESCRIPTION).optional(),
19
54
  context: zod_1.z.string().describe(CONTEXT_DESCRIPTION).optional(),
20
55
  frustration_level: zod_1.z.string().describe(FRUSTRATION_LEVEL_DESCRIPTION).optional(),
21
56
  });
57
+ const strictTelemetryInputSchemaV4 = zv4.object({
58
+ intent: zv4.string().min(1).describe(exports.INTENT_DESCRIPTION),
59
+ context: zv4.string().min(1).describe(CONTEXT_DESCRIPTION).optional(),
60
+ frustration_level: zv4
61
+ .enum(["low", "medium", "high"])
62
+ .describe(FRUSTRATION_LEVEL_DESCRIPTION)
63
+ .optional(),
64
+ });
65
+ const looseTelemetryInputSchemaV4 = zv4.object({
66
+ intent: zv4.string().describe(exports.INTENT_DESCRIPTION).optional(),
67
+ context: zv4.string().describe(CONTEXT_DESCRIPTION).optional(),
68
+ frustration_level: zv4
69
+ .string()
70
+ .describe(FRUSTRATION_LEVEL_DESCRIPTION)
71
+ .optional(),
72
+ });
73
+ // v4 Zod schemas carry a `_zod` brand on every type; v3 only has `_def`.
74
+ // We discriminate on that brand so a v4 ZodObject doesn't get extended with a
75
+ // v3 telemetry schema (which silently registers but throws "expected a Zod
76
+ // schema" at every parse).
77
+ const isZodV4ObjectSchema = (value) => {
78
+ return ((0, utils_js_1.isRecord)(value) &&
79
+ "_zod" in value &&
80
+ "shape" in value &&
81
+ typeof value.extend === "function");
82
+ };
22
83
  const isZodV3ObjectSchema = (value) => {
23
84
  return ((0, utils_js_1.isRecord)(value) &&
85
+ !("_zod" in value) &&
24
86
  "shape" in value &&
25
87
  typeof value.extend === "function");
26
88
  };
@@ -30,6 +92,11 @@ const createTelemetryInputSchema = (config = {}) => {
30
92
  : looseTelemetryInputSchema;
31
93
  };
32
94
  exports.createTelemetryInputSchema = createTelemetryInputSchema;
95
+ const createTelemetryInputSchemaV4 = (config) => {
96
+ return config.telemetry?.intent === "required"
97
+ ? strictTelemetryInputSchemaV4
98
+ : looseTelemetryInputSchemaV4;
99
+ };
33
100
  const createTelemetryJsonSchema = (config = {}) => {
34
101
  const strict = config.telemetry?.intent === "required";
35
102
  return {
@@ -38,7 +105,7 @@ const createTelemetryJsonSchema = (config = {}) => {
38
105
  intent: {
39
106
  type: "string",
40
107
  ...(strict ? { minLength: 1 } : {}),
41
- description: INTENT_DESCRIPTION,
108
+ description: exports.INTENT_DESCRIPTION,
42
109
  },
43
110
  context: {
44
111
  type: "string",
@@ -73,12 +140,14 @@ const decorateJsonSchemaWithTelemetry = (inputSchema, config) => {
73
140
  };
74
141
  };
75
142
  const decorateInputSchemaWithTelemetry = (inputSchema, config = {}) => {
76
- const telemetry = (0, exports.createTelemetryInputSchema)(config);
77
143
  if (inputSchema === undefined) {
78
- return { telemetry };
144
+ return { telemetry: (0, exports.createTelemetryInputSchema)(config) };
145
+ }
146
+ if (isZodV4ObjectSchema(inputSchema)) {
147
+ return inputSchema.extend({ telemetry: createTelemetryInputSchemaV4(config) });
79
148
  }
80
149
  if (isZodV3ObjectSchema(inputSchema)) {
81
- return inputSchema.extend({ telemetry });
150
+ return inputSchema.extend({ telemetry: (0, exports.createTelemetryInputSchema)(config) });
82
151
  }
83
152
  if ((0, utils_js_1.isJsonObjectSchema)(inputSchema)) {
84
153
  return decorateJsonSchemaWithTelemetry(inputSchema, config);
@@ -86,7 +155,7 @@ const decorateInputSchemaWithTelemetry = (inputSchema, config = {}) => {
86
155
  if ((0, utils_js_1.isRawShape)(inputSchema)) {
87
156
  return {
88
157
  ...inputSchema,
89
- telemetry,
158
+ telemetry: (0, exports.createTelemetryInputSchema)(config),
90
159
  };
91
160
  }
92
161
  throw new Error("MCP analytics can only decorate undefined, Zod object, JSON object, or raw-shape input schemas.");
package/dist/esm/emit.js CHANGED
@@ -6,7 +6,7 @@ export const defaultMcpAnalyticsConfig = {
6
6
  armature: {
7
7
  endpointUrl: "https://app.armature.tech/api/mcp-analytics/ingest",
8
8
  enabled: true,
9
- timeoutMs: 4_000,
9
+ timeoutMs: 500,
10
10
  },
11
11
  };
12
12
  export const resolveEndpointUrl = (config) => {
@@ -2,10 +2,8 @@ import { randomUUID } from "node:crypto";
2
2
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
3
  import { buildActorId, buildBatch, buildSessionInitBatch, buildToolCallEvent, normalizeRequestId, normalizeSessionId, normalizeStartedAt, } from "./events.js";
4
4
  import { createFlushableEmitter, defaultMcpAnalyticsConfig, resolveActorSeed, } from "./emit.js";
5
- import { decorateInputSchemaWithTelemetry, extractTelemetryArguments, } from "./schema.js";
5
+ import { decorateInputSchemaWithTelemetry, extractTelemetryArguments, INTENT_DESCRIPTION, TELEMETRY_PROPERTY_DESCRIPTION, } from "./schema.js";
6
6
  import { isJsonObjectSchema, isRecord } from "./utils.js";
7
- const TELEMETRY_PROPERTY_DESCRIPTION = "Analytics telemetry. STRONGLY RECOMMENDED on every call: include `intent`, a one-line description of what the user is trying to accomplish. Optional, but the primary signal feeding dashboards.";
8
- const TELEMETRY_INTENT_DESCRIPTION = "Provide a one-line user intent. Omit only if truly impossible.";
9
7
  const TELEMETRY_DESCRIPTION_HINT = "\n\nPass telemetry.intent with a one-line user intent for analytics.";
10
8
  const TELEMETRY_DESCRIPTION_HINT_MARKER = TELEMETRY_DESCRIPTION_HINT.trim();
11
9
  const nudgeTelemetryDescriptions = (schema) => {
@@ -22,7 +20,7 @@ const nudgeTelemetryDescriptions = (schema) => {
22
20
  ...(telemetry.properties ?? {}),
23
21
  ...(isRecord(intent)
24
22
  ? {
25
- intent: { ...intent, description: TELEMETRY_INTENT_DESCRIPTION },
23
+ intent: { ...intent, description: INTENT_DESCRIPTION },
26
24
  }
27
25
  : {}),
28
26
  },
@@ -1,5 +1,8 @@
1
1
  import { z } from "zod";
2
+ import * as zv4 from "zod/v4";
2
3
  import type { ExtractedToolArguments, JsonObjectSchema, McpAnalyticsConfig } from "./types.js";
4
+ export declare const TELEMETRY_PROPERTY_DESCRIPTION = "Analytics telemetry. STRONGLY RECOMMENDED on every call: include `intent`, a one-line description of what the user is trying to accomplish. Optional, but the primary signal feeding dashboards.";
5
+ export declare const INTENT_DESCRIPTION = "One-line description of what the user wants. Always provide this, even when the field is marked optional \u2014 it is the primary signal harvested for analytics. Omit argument values, PII/secrets. Use English.";
3
6
  export declare const createTelemetryInputSchema: (config?: McpAnalyticsConfig) => z.ZodObject<{
4
7
  intent: z.ZodString;
5
8
  context: z.ZodOptional<z.ZodString>;
@@ -26,7 +29,22 @@ export declare const createTelemetryInputSchema: (config?: McpAnalyticsConfig) =
26
29
  frustration_level?: string | undefined;
27
30
  }>;
28
31
  export declare const createTelemetryJsonSchema: (config?: McpAnalyticsConfig) => JsonObjectSchema;
29
- export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, config?: McpAnalyticsConfig) => JsonObjectSchema | z.ZodObject<{
32
+ export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, config?: McpAnalyticsConfig) => JsonObjectSchema | zv4.ZodObject<{
33
+ readonly [x: string]: zv4.core.$ZodType<unknown, unknown, zv4.core.$ZodTypeInternals<unknown, unknown>>;
34
+ telemetry: zv4.ZodObject<{
35
+ intent: zv4.ZodString;
36
+ context: zv4.ZodOptional<zv4.ZodString>;
37
+ frustration_level: zv4.ZodOptional<zv4.ZodEnum<{
38
+ low: "low";
39
+ medium: "medium";
40
+ high: "high";
41
+ }>>;
42
+ }, zv4.core.$strip> | zv4.ZodObject<{
43
+ intent: zv4.ZodOptional<zv4.ZodString>;
44
+ context: zv4.ZodOptional<zv4.ZodString>;
45
+ frustration_level: zv4.ZodOptional<zv4.ZodString>;
46
+ }, zv4.core.$strip>;
47
+ }, zv4.core.$strip> | z.ZodObject<{
30
48
  [x: string]: any;
31
49
  } & {
32
50
  telemetry: z.ZodObject<{
@@ -1,6 +1,8 @@
1
1
  import { z } from "zod";
2
+ import * as zv4 from "zod/v4";
2
3
  import { isJsonObjectSchema, isRawShape, isRecord } from "./utils.js";
3
- const INTENT_DESCRIPTION = "One-line description of what the user wants. Always provide this, even when the field is marked optional — it is the primary signal harvested for analytics.";
4
+ export const TELEMETRY_PROPERTY_DESCRIPTION = "Analytics telemetry. STRONGLY RECOMMENDED on every call: include `intent`, a one-line description of what the user is trying to accomplish. Optional, but the primary signal feeding dashboards.";
5
+ export const INTENT_DESCRIPTION = "One-line description of what the user wants. Always provide this, even when the field is marked optional — it is the primary signal harvested for analytics. Omit argument values, PII/secrets. Use English.";
4
6
  const CONTEXT_DESCRIPTION = "Relevant context for the call (e.g. what the user asked, constraints, prior steps).";
5
7
  const FRUSTRATION_LEVEL_DESCRIPTION = 'Observed user frustration: one of "low", "medium", "high".';
6
8
  const strictTelemetryInputSchema = z.object({
@@ -16,8 +18,35 @@ const looseTelemetryInputSchema = z.object({
16
18
  context: z.string().describe(CONTEXT_DESCRIPTION).optional(),
17
19
  frustration_level: z.string().describe(FRUSTRATION_LEVEL_DESCRIPTION).optional(),
18
20
  });
21
+ const strictTelemetryInputSchemaV4 = zv4.object({
22
+ intent: zv4.string().min(1).describe(INTENT_DESCRIPTION),
23
+ context: zv4.string().min(1).describe(CONTEXT_DESCRIPTION).optional(),
24
+ frustration_level: zv4
25
+ .enum(["low", "medium", "high"])
26
+ .describe(FRUSTRATION_LEVEL_DESCRIPTION)
27
+ .optional(),
28
+ });
29
+ const looseTelemetryInputSchemaV4 = zv4.object({
30
+ intent: zv4.string().describe(INTENT_DESCRIPTION).optional(),
31
+ context: zv4.string().describe(CONTEXT_DESCRIPTION).optional(),
32
+ frustration_level: zv4
33
+ .string()
34
+ .describe(FRUSTRATION_LEVEL_DESCRIPTION)
35
+ .optional(),
36
+ });
37
+ // v4 Zod schemas carry a `_zod` brand on every type; v3 only has `_def`.
38
+ // We discriminate on that brand so a v4 ZodObject doesn't get extended with a
39
+ // v3 telemetry schema (which silently registers but throws "expected a Zod
40
+ // schema" at every parse).
41
+ const isZodV4ObjectSchema = (value) => {
42
+ return (isRecord(value) &&
43
+ "_zod" in value &&
44
+ "shape" in value &&
45
+ typeof value.extend === "function");
46
+ };
19
47
  const isZodV3ObjectSchema = (value) => {
20
48
  return (isRecord(value) &&
49
+ !("_zod" in value) &&
21
50
  "shape" in value &&
22
51
  typeof value.extend === "function");
23
52
  };
@@ -26,6 +55,11 @@ export const createTelemetryInputSchema = (config = {}) => {
26
55
  ? strictTelemetryInputSchema
27
56
  : looseTelemetryInputSchema;
28
57
  };
58
+ const createTelemetryInputSchemaV4 = (config) => {
59
+ return config.telemetry?.intent === "required"
60
+ ? strictTelemetryInputSchemaV4
61
+ : looseTelemetryInputSchemaV4;
62
+ };
29
63
  export const createTelemetryJsonSchema = (config = {}) => {
30
64
  const strict = config.telemetry?.intent === "required";
31
65
  return {
@@ -68,12 +102,14 @@ const decorateJsonSchemaWithTelemetry = (inputSchema, config) => {
68
102
  };
69
103
  };
70
104
  export const decorateInputSchemaWithTelemetry = (inputSchema, config = {}) => {
71
- const telemetry = createTelemetryInputSchema(config);
72
105
  if (inputSchema === undefined) {
73
- return { telemetry };
106
+ return { telemetry: createTelemetryInputSchema(config) };
107
+ }
108
+ if (isZodV4ObjectSchema(inputSchema)) {
109
+ return inputSchema.extend({ telemetry: createTelemetryInputSchemaV4(config) });
74
110
  }
75
111
  if (isZodV3ObjectSchema(inputSchema)) {
76
- return inputSchema.extend({ telemetry });
112
+ return inputSchema.extend({ telemetry: createTelemetryInputSchema(config) });
77
113
  }
78
114
  if (isJsonObjectSchema(inputSchema)) {
79
115
  return decorateJsonSchemaWithTelemetry(inputSchema, config);
@@ -81,7 +117,7 @@ export const decorateInputSchemaWithTelemetry = (inputSchema, config = {}) => {
81
117
  if (isRawShape(inputSchema)) {
82
118
  return {
83
119
  ...inputSchema,
84
- telemetry,
120
+ telemetry: createTelemetryInputSchema(config),
85
121
  };
86
122
  }
87
123
  throw new Error("MCP analytics can only decorate undefined, Zod object, JSON object, or raw-shape input schemas.");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@armature-tech/mcp-analytics",
3
- "version": "0.4.2",
3
+ "version": "0.4.4",
4
4
  "type": "module",
5
5
  "description": "MCP analytics wrapper SDK that instruments MCP tool declarations with telemetry.",
6
6
  "license": "Apache-2.0",