@armature-tech/mcp-analytics 0.4.3 → 0.5.1

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
@@ -49,13 +49,13 @@ Decorate input schemas, strip telemetry fields before the handler runs, time the
49
49
 
50
50
  **3) The agent should be able to tell you what it's doing.**
51
51
 
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.
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. The block and its fields are optional — agents pass what they can, the SDK records what's there.
53
53
 
54
54
  ## How it works
55
55
 
56
56
  Three things happen on every tool call:
57
57
 
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.
58
+ 1. **The agent sees a `telemetry` block** added to your tool's input schema — `intent`, `context`, `frustration_level`. The block is optional; the SDK never rejects a call for omitting it.
59
59
  2. **Your handler sees its original args.** The SDK strips `telemetry` before invoking it.
60
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.
61
61
 
@@ -73,22 +73,21 @@ Code examples for all three live in [`SKILL.md`](SKILL.md).
73
73
 
74
74
  ```ts
75
75
  type McpAnalyticsConfig = {
76
- telemetry?: {
77
- intent?: "required" | "optional"; // default "optional"
78
- };
79
76
  armature?: {
80
77
  endpointUrl?: string; // default reads ANALYTICS_INGEST_URL
81
78
  apiKey?: string; // default reads ANALYTICS_INGEST_API_KEY
82
79
  actorId?: string | ((input) => string | Promise<string>);
83
80
  enabled?: boolean; // default true
84
81
  delivery?: "background" | "await"; // default "background"
85
- timeoutMs?: number; // default 4000
82
+ timeoutMs?: number; // default 500
86
83
  emit?: (batch) => void | Promise<void>; // override the network emitter
87
84
  onError?: (error, batch) => void;
88
85
  };
89
86
  };
90
87
  ```
91
88
 
89
+ The shape of the `telemetry` block on each tool's input schema is Armature-owned and not customer-configurable. Customers only set operational config (delivery, actor id, transport).
90
+
92
91
  **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
92
 
94
93
  **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).
@@ -0,0 +1,8 @@
1
+ import type { McpClientInfo } from "./types.js";
2
+ export declare const installClientInfoCapture: () => void;
3
+ export declare const getClientInfoForSessionId: (sessionId: string | undefined) => McpClientInfo | undefined;
4
+ export declare const __setClientInfoForSessionId: (sessionId: string, info: McpClientInfo) => void;
5
+ export declare const __clearClientInfoCache: () => void;
6
+ export declare const __isInitializePatchInstalled: () => boolean;
7
+ export declare const __getClientInfoCacheSize: () => number;
8
+ export declare const __getMaxClientInfoCacheEntries: () => number;
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.__getMaxClientInfoCacheEntries = exports.__getClientInfoCacheSize = exports.__isInitializePatchInstalled = exports.__clearClientInfoCache = exports.__setClientInfoForSessionId = exports.getClientInfoForSessionId = exports.installClientInfoCapture = void 0;
4
+ const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
5
+ // In-process map keyed by transport sessionId. Populated by the patched
6
+ // `Server.prototype._oninitialize` and read by the recorder at tool-call time.
7
+ // Same instance the customer constructs, because `@modelcontextprotocol/sdk`
8
+ // is a peer dependency.
9
+ //
10
+ // Bounded by `MAX_CACHE_ENTRIES` with FIFO eviction (Map iteration order is
11
+ // insertion order in JS, so the first key is the oldest). MCP `initialize`
12
+ // never fires a corresponding "session-closed" signal we can hook reliably —
13
+ // short-lived sessions on a long-running server would otherwise leak forever.
14
+ // 10k entries × ~200 bytes ≈ 2MB upper bound, well below anything operators
15
+ // would notice; the cap is far above any plausible concurrent-session count.
16
+ const MAX_CACHE_ENTRIES = 10_000;
17
+ const clientInfoBySessionId = new Map();
18
+ const setCachedClientInfo = (sessionId, info) => {
19
+ if (clientInfoBySessionId.has(sessionId)) {
20
+ clientInfoBySessionId.delete(sessionId);
21
+ }
22
+ else if (clientInfoBySessionId.size >= MAX_CACHE_ENTRIES) {
23
+ const oldest = clientInfoBySessionId.keys().next().value;
24
+ if (oldest !== undefined)
25
+ clientInfoBySessionId.delete(oldest);
26
+ }
27
+ clientInfoBySessionId.set(sessionId, info);
28
+ };
29
+ let initializePatchInstalled = false;
30
+ const extractInitializeParams = (request) => {
31
+ if (typeof request !== "object" || request === null)
32
+ return {};
33
+ const params = request.params;
34
+ return typeof params === "object" && params !== null
35
+ ? params
36
+ : {};
37
+ };
38
+ // `Server.prototype._oninitialize` is a private method that runs on every
39
+ // `initialize` request, right before the handshake response is sent. Wrapping
40
+ // it lets us snapshot `clientInfo` and key it by `transport.sessionId` so the
41
+ // tool-call path can recover the client name even when the framework around
42
+ // the SDK (e.g. Mastra's `MCPServer`) never surfaces the underlying `Server`
43
+ // instance to the tool handler.
44
+ //
45
+ // Defensive: if the SDK ever renames the method, the patch is a no-op and the
46
+ // dashboard regresses to today's behaviour rather than breaking the server.
47
+ const installClientInfoCapture = () => {
48
+ if (initializePatchInstalled)
49
+ return;
50
+ const proto = index_js_1.Server.prototype;
51
+ if (typeof proto._oninitialize !== "function")
52
+ return;
53
+ initializePatchInstalled = true;
54
+ const original = proto._oninitialize;
55
+ proto._oninitialize = async function patchedOnInitialize(request) {
56
+ const result = await original.call(this, request);
57
+ try {
58
+ const params = extractInitializeParams(request);
59
+ const sessionId = this.transport?.sessionId ?? params._meta?.sessionId ?? undefined;
60
+ const info = params.clientInfo;
61
+ const name = typeof info?.name === "string" ? info.name.trim() : "";
62
+ if (sessionId && name.length > 0) {
63
+ setCachedClientInfo(sessionId, {
64
+ name,
65
+ version: typeof info?.version === "string" ? info.version : undefined,
66
+ protocolVersion: typeof params.protocolVersion === "string"
67
+ ? params.protocolVersion
68
+ : undefined,
69
+ capabilities: typeof params.capabilities === "object" && params.capabilities !== null
70
+ ? params.capabilities
71
+ : null,
72
+ });
73
+ }
74
+ }
75
+ catch {
76
+ // Capture is best-effort; never break the handshake.
77
+ }
78
+ return result;
79
+ };
80
+ };
81
+ exports.installClientInfoCapture = installClientInfoCapture;
82
+ const getClientInfoForSessionId = (sessionId) => {
83
+ if (!sessionId)
84
+ return undefined;
85
+ return clientInfoBySessionId.get(sessionId);
86
+ };
87
+ exports.getClientInfoForSessionId = getClientInfoForSessionId;
88
+ // INTERNAL. Not part of the public API and may change or disappear in any
89
+ // release. These exports exist so the test suite can seed/clear shared module
90
+ // state without standing up a full MCP handshake. Downstream callers cannot
91
+ // reach them through the package name: `package.json#exports` only publishes
92
+ // `.` and `./mastra`, so Node refuses deep imports under either ESM `import`
93
+ // or CJS `require`.
94
+ const __setClientInfoForSessionId = (sessionId, info) => {
95
+ setCachedClientInfo(sessionId, info);
96
+ };
97
+ exports.__setClientInfoForSessionId = __setClientInfoForSessionId;
98
+ const __clearClientInfoCache = () => {
99
+ clientInfoBySessionId.clear();
100
+ };
101
+ exports.__clearClientInfoCache = __clearClientInfoCache;
102
+ const __isInitializePatchInstalled = () => initializePatchInstalled;
103
+ exports.__isInitializePatchInstalled = __isInitializePatchInstalled;
104
+ const __getClientInfoCacheSize = () => clientInfoBySessionId.size;
105
+ exports.__getClientInfoCacheSize = __getClientInfoCacheSize;
106
+ const __getMaxClientInfoCacheEntries = () => MAX_CACHE_ENTRIES;
107
+ exports.__getMaxClientInfoCacheEntries = __getMaxClientInfoCacheEntries;
@@ -1,8 +1,5 @@
1
1
  import type { ActorIdResolverInput, AnalyticsIngestBatch, McpAnalyticsConfig } from "./types.js";
2
2
  export declare const defaultMcpAnalyticsConfig: {
3
- telemetry: {
4
- intent: "optional";
5
- };
6
3
  armature: {
7
4
  endpointUrl: string;
8
5
  enabled: true;
package/dist/cjs/emit.js CHANGED
@@ -3,13 +3,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createFlushableEmitter = exports.emitTelemetryEvent = exports.postTelemetryEvent = exports.resolveActorSeed = exports.resolveApiKey = exports.resolveEndpointUrl = exports.defaultMcpAnalyticsConfig = void 0;
4
4
  const utils_js_1 = require("./utils.js");
5
5
  exports.defaultMcpAnalyticsConfig = {
6
- telemetry: {
7
- intent: "optional",
8
- },
9
6
  armature: {
10
7
  endpointUrl: "https://app.armature.tech/api/mcp-analytics/ingest",
11
8
  enabled: true,
12
- timeoutMs: 4_000,
9
+ timeoutMs: 500,
13
10
  },
14
11
  };
15
12
  const resolveEndpointUrl = (config) => {
@@ -79,6 +79,7 @@ const buildSessionInitEvent = ({ actorId, sessionId, requestId, startedAt, extra
79
79
  metadata: {
80
80
  client_name: trimOrUndefined(clientInfo?.name)
81
81
  ?? trimOrUndefined(extra?.authInfo?.clientId)
82
+ ?? trimOrUndefined((0, utils_js_1.headerValue)(extra?.requestInfo?.headers, "x-mcp-client"))
82
83
  ?? null,
83
84
  client_version: trimOrUndefined(clientInfo?.version) ?? null,
84
85
  protocol_version: trimOrUndefined(clientInfo?.protocolVersion) ?? null,
@@ -1,4 +1,4 @@
1
- import type { AnalyticsRecorder, McpAnalyticsConfig, RequestExtra } from "./types.js";
1
+ import type { AnalyticsRecorder, InternalMcpAnalyticsConfig, McpAnalyticsConfig, RequestExtra } from "./types.js";
2
2
  export type MastraToolExecute = (inputData: any, context?: any) => unknown | Promise<unknown>;
3
3
  export type MastraTool = {
4
4
  id?: string;
@@ -12,7 +12,7 @@ export type MastraToolMap = Record<string, MastraTool>;
12
12
  export type MastraAdapterOptions = McpAnalyticsConfig & {
13
13
  resolveExtra?: (mastraContext: unknown) => RequestExtra | undefined;
14
14
  };
15
- export declare const wrapMastraToolsWithRecorder: (tools: MastraToolMap, recorder: AnalyticsRecorder, config?: McpAnalyticsConfig, options?: {
15
+ export declare const wrapMastraToolsWithRecorder: (tools: MastraToolMap, recorder: AnalyticsRecorder, config?: InternalMcpAnalyticsConfig, options?: {
16
16
  resolveExtra?: MastraAdapterOptions["resolveExtra"];
17
17
  }) => MastraToolMap;
18
18
  export declare const wrapMastraTools: (tools: MastraToolMap, options?: MastraAdapterOptions) => MastraToolMap;
@@ -7,8 +7,7 @@ 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.";
10
+ const client_info_cache_js_1 = require("./client-info-cache.js");
12
11
  const TELEMETRY_DESCRIPTION_HINT = "\n\nPass telemetry.intent with a one-line user intent for analytics.";
13
12
  const TELEMETRY_DESCRIPTION_HINT_MARKER = TELEMETRY_DESCRIPTION_HINT.trim();
14
13
  const nudgeTelemetryDescriptions = (schema) => {
@@ -20,12 +19,12 @@ const nudgeTelemetryDescriptions = (schema) => {
20
19
  const intent = telemetry.properties?.intent;
21
20
  const nudgedTelemetry = {
22
21
  ...telemetry,
23
- description: TELEMETRY_PROPERTY_DESCRIPTION,
22
+ description: schema_js_1.TELEMETRY_PROPERTY_DESCRIPTION,
24
23
  properties: {
25
24
  ...(telemetry.properties ?? {}),
26
25
  ...((0, utils_js_1.isRecord)(intent)
27
26
  ? {
28
- intent: { ...intent, description: TELEMETRY_INTENT_DESCRIPTION },
27
+ intent: { ...intent, description: schema_js_1.INTENT_DESCRIPTION },
29
28
  }
30
29
  : {}),
31
30
  },
@@ -51,6 +50,12 @@ const createAnalyticsContext = async (config, input) => {
51
50
  const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) => {
52
51
  const { emitBatch, flush } = (0, emit_js_1.createFlushableEmitter)(config);
53
52
  const sessionInitKeys = new Set();
53
+ // Patch the SDK's Server.prototype the first time any recorder is created
54
+ // so that the very next `initialize` handshake feeds the per-session client
55
+ // info cache. Without this the dashboard's "Client" column would stay at
56
+ // "Unknown" for Mastra-wrapped tool calls, which can't reach the underlying
57
+ // SDK Server from inside `tool.execute`.
58
+ (0, client_info_cache_js_1.installClientInfoCapture)();
54
59
  const analyticsContextFor = async (input) => {
55
60
  return createAnalyticsContext(config, input);
56
61
  };
@@ -88,7 +93,7 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
88
93
  startedAt,
89
94
  extra: event.extra,
90
95
  sessionInitKeys,
91
- clientInfo: event.clientInfo,
96
+ clientInfo: event.clientInfo ?? (0, client_info_cache_js_1.getClientInfoForSessionId)(sessionId),
92
97
  });
93
98
  if (batch)
94
99
  await emitBatch(batch);
@@ -131,6 +136,9 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
131
136
  startedAt,
132
137
  finishedAt,
133
138
  });
139
+ // An explicit clientInfo on the event always wins; otherwise look up
140
+ // whatever the initialize-handshake patch captured for this sessionId.
141
+ const effectiveClientInfo = event.clientInfo ?? (0, client_info_cache_js_1.getClientInfoForSessionId)(sessionId);
134
142
  await emitBatch((0, events_js_1.buildBatch)({
135
143
  event: toolCallEvent,
136
144
  extra: {
@@ -140,7 +148,7 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
140
148
  actorId: context.actorId,
141
149
  startedAt,
142
150
  sessionInitKeys,
143
- clientInfo: event.clientInfo,
151
+ clientInfo: effectiveClientInfo,
144
152
  }));
145
153
  };
146
154
  const registeredTools = new Map();
@@ -1,7 +1,9 @@
1
1
  import { z } from "zod";
2
2
  import * as zv4 from "zod/v4";
3
- import type { ExtractedToolArguments, JsonObjectSchema, McpAnalyticsConfig } from "./types.js";
4
- export declare const createTelemetryInputSchema: (config?: McpAnalyticsConfig) => z.ZodObject<{
3
+ import type { ExtractedToolArguments, InternalMcpAnalyticsConfig, JsonObjectSchema } 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.";
6
+ export declare const createTelemetryInputSchema: (config?: InternalMcpAnalyticsConfig) => z.ZodObject<{
5
7
  intent: z.ZodString;
6
8
  context: z.ZodOptional<z.ZodString>;
7
9
  frustration_level: z.ZodOptional<z.ZodEnum<["low", "medium", "high"]>>;
@@ -13,7 +15,7 @@ export declare const createTelemetryInputSchema: (config?: McpAnalyticsConfig) =
13
15
  intent: string;
14
16
  context?: string | undefined;
15
17
  frustration_level?: "low" | "medium" | "high" | undefined;
16
- }> | z.ZodObject<{
18
+ }> | z.ZodOptional<z.ZodObject<{
17
19
  intent: z.ZodOptional<z.ZodString>;
18
20
  context: z.ZodOptional<z.ZodString>;
19
21
  frustration_level: z.ZodOptional<z.ZodString>;
@@ -25,9 +27,9 @@ export declare const createTelemetryInputSchema: (config?: McpAnalyticsConfig) =
25
27
  intent?: string | undefined;
26
28
  context?: string | undefined;
27
29
  frustration_level?: string | undefined;
28
- }>;
29
- export declare const createTelemetryJsonSchema: (config?: McpAnalyticsConfig) => JsonObjectSchema;
30
- export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, config?: McpAnalyticsConfig) => JsonObjectSchema | zv4.ZodObject<{
30
+ }>>;
31
+ export declare const createTelemetryJsonSchema: (config?: InternalMcpAnalyticsConfig) => JsonObjectSchema;
32
+ export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, config?: InternalMcpAnalyticsConfig) => JsonObjectSchema | zv4.ZodObject<{
31
33
  readonly [x: string]: zv4.core.$ZodType<unknown, unknown, zv4.core.$ZodTypeInternals<unknown, unknown>>;
32
34
  telemetry: zv4.ZodObject<{
33
35
  intent: zv4.ZodString;
@@ -37,11 +39,11 @@ export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, co
37
39
  medium: "medium";
38
40
  high: "high";
39
41
  }>>;
40
- }, zv4.core.$strip> | zv4.ZodObject<{
42
+ }, zv4.core.$strip> | zv4.ZodOptional<zv4.ZodObject<{
41
43
  intent: zv4.ZodOptional<zv4.ZodString>;
42
44
  context: zv4.ZodOptional<zv4.ZodString>;
43
45
  frustration_level: zv4.ZodOptional<zv4.ZodString>;
44
- }, zv4.core.$strip>;
46
+ }, zv4.core.$strip>>;
45
47
  }, zv4.core.$strip> | z.ZodObject<{
46
48
  [x: string]: any;
47
49
  } & {
@@ -57,7 +59,7 @@ export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, co
57
59
  intent: string;
58
60
  context?: string | undefined;
59
61
  frustration_level?: "low" | "medium" | "high" | undefined;
60
- }> | z.ZodObject<{
62
+ }> | z.ZodOptional<z.ZodObject<{
61
63
  intent: z.ZodOptional<z.ZodString>;
62
64
  context: z.ZodOptional<z.ZodString>;
63
65
  frustration_level: z.ZodOptional<z.ZodString>;
@@ -69,7 +71,7 @@ export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, co
69
71
  intent?: string | undefined;
70
72
  context?: string | undefined;
71
73
  frustration_level?: string | undefined;
72
- }>;
74
+ }>>;
73
75
  }, any, any, {
74
76
  [x: string]: any;
75
77
  telemetry?: unknown;
@@ -33,15 +33,16 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- 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;
37
37
  const zod_1 = require("zod");
38
38
  const zv4 = __importStar(require("zod/v4"));
39
39
  const utils_js_1 = require("./utils.js");
40
- 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.";
41
42
  const CONTEXT_DESCRIPTION = "Relevant context for the call (e.g. what the user asked, constraints, prior steps).";
42
43
  const FRUSTRATION_LEVEL_DESCRIPTION = 'Observed user frustration: one of "low", "medium", "high".';
43
44
  const strictTelemetryInputSchema = zod_1.z.object({
44
- intent: zod_1.z.string().min(1).describe(INTENT_DESCRIPTION),
45
+ intent: zod_1.z.string().min(1).describe(exports.INTENT_DESCRIPTION),
45
46
  context: zod_1.z.string().min(1).describe(CONTEXT_DESCRIPTION).optional(),
46
47
  frustration_level: zod_1.z
47
48
  .enum(["low", "medium", "high"])
@@ -49,12 +50,12 @@ const strictTelemetryInputSchema = zod_1.z.object({
49
50
  .optional(),
50
51
  });
51
52
  const looseTelemetryInputSchema = zod_1.z.object({
52
- intent: zod_1.z.string().describe(INTENT_DESCRIPTION).optional(),
53
+ intent: zod_1.z.string().describe(exports.INTENT_DESCRIPTION).optional(),
53
54
  context: zod_1.z.string().describe(CONTEXT_DESCRIPTION).optional(),
54
55
  frustration_level: zod_1.z.string().describe(FRUSTRATION_LEVEL_DESCRIPTION).optional(),
55
56
  });
56
57
  const strictTelemetryInputSchemaV4 = zv4.object({
57
- intent: zv4.string().min(1).describe(INTENT_DESCRIPTION),
58
+ intent: zv4.string().min(1).describe(exports.INTENT_DESCRIPTION),
58
59
  context: zv4.string().min(1).describe(CONTEXT_DESCRIPTION).optional(),
59
60
  frustration_level: zv4
60
61
  .enum(["low", "medium", "high"])
@@ -62,7 +63,7 @@ const strictTelemetryInputSchemaV4 = zv4.object({
62
63
  .optional(),
63
64
  });
64
65
  const looseTelemetryInputSchemaV4 = zv4.object({
65
- intent: zv4.string().describe(INTENT_DESCRIPTION).optional(),
66
+ intent: zv4.string().describe(exports.INTENT_DESCRIPTION).optional(),
66
67
  context: zv4.string().describe(CONTEXT_DESCRIPTION).optional(),
67
68
  frustration_level: zv4
68
69
  .string()
@@ -85,16 +86,19 @@ const isZodV3ObjectSchema = (value) => {
85
86
  "shape" in value &&
86
87
  typeof value.extend === "function");
87
88
  };
89
+ // Loose mode wraps the telemetry object with `.optional()` so callers that omit
90
+ // the `telemetry` key entirely still parse. Strict mode keeps the object itself
91
+ // required (and `intent` required inside).
88
92
  const createTelemetryInputSchema = (config = {}) => {
89
93
  return config.telemetry?.intent === "required"
90
94
  ? strictTelemetryInputSchema
91
- : looseTelemetryInputSchema;
95
+ : looseTelemetryInputSchema.optional();
92
96
  };
93
97
  exports.createTelemetryInputSchema = createTelemetryInputSchema;
94
98
  const createTelemetryInputSchemaV4 = (config) => {
95
99
  return config.telemetry?.intent === "required"
96
100
  ? strictTelemetryInputSchemaV4
97
- : looseTelemetryInputSchemaV4;
101
+ : looseTelemetryInputSchemaV4.optional();
98
102
  };
99
103
  const createTelemetryJsonSchema = (config = {}) => {
100
104
  const strict = config.telemetry?.intent === "required";
@@ -104,7 +108,7 @@ const createTelemetryJsonSchema = (config = {}) => {
104
108
  intent: {
105
109
  type: "string",
106
110
  ...(strict ? { minLength: 1 } : {}),
107
- description: INTENT_DESCRIPTION,
111
+ description: exports.INTENT_DESCRIPTION,
108
112
  },
109
113
  context: {
110
114
  type: "string",
@@ -7,65 +7,134 @@ const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
7
7
  const recorder_js_1 = require("./recorder.js");
8
8
  const schema_js_1 = require("./schema.js");
9
9
  const emit_js_1 = require("./emit.js");
10
+ const utils_js_1 = require("./utils.js");
10
11
  const withAnalyticsStorage = new node_async_hooks_1.AsyncLocalStorage();
11
12
  let prototypePatchInstalled = false;
13
+ // Mirrors the SDK's `isZodTypeLike`/`isZodRawShapeCompat` checks closely enough
14
+ // to disambiguate the overloads of `server.tool(...)`: a raw shape is a plain
15
+ // object whose values include at least one Zod schema, while a Zod schema
16
+ // instance carries `_def` (v3) or `_zod` (v4).
17
+ const isZodSchemaLike = (value) => {
18
+ if (!(0, utils_js_1.isRecord)(value))
19
+ return false;
20
+ return "_def" in value || "_zod" in value;
21
+ };
22
+ const isZodRawShapeLike = (value) => {
23
+ if (!(0, utils_js_1.isRecord)(value))
24
+ return false;
25
+ if (isZodSchemaLike(value))
26
+ return false;
27
+ if (Object.keys(value).length === 0)
28
+ return true;
29
+ return Object.values(value).some(isZodSchemaLike);
30
+ };
31
+ // Mirrors @modelcontextprotocol/sdk/server/mcp.js `tool(name, ...rest)` argument
32
+ // parsing so we can normalise every overload through our patched `registerTool`.
33
+ const parseDeprecatedToolArgs = (rest) => {
34
+ const args = [...rest];
35
+ let description;
36
+ let inputSchema;
37
+ let annotations;
38
+ if (typeof args[0] === "string") {
39
+ description = args.shift();
40
+ }
41
+ if (args.length > 1) {
42
+ const firstArg = args[0];
43
+ if (isZodRawShapeLike(firstArg)) {
44
+ inputSchema = args.shift();
45
+ if (args.length > 1 &&
46
+ (0, utils_js_1.isRecord)(args[0]) &&
47
+ !isZodRawShapeLike(args[0])) {
48
+ annotations = args.shift();
49
+ }
50
+ }
51
+ else if ((0, utils_js_1.isRecord)(firstArg)) {
52
+ annotations = args.shift();
53
+ }
54
+ }
55
+ const callback = args[0];
56
+ return { description, inputSchema, annotations, callback };
57
+ };
58
+ const wrapCallbackWithAnalytics = (name, cb, originalHasInputSchema, ctx) => {
59
+ const { recorder } = ctx;
60
+ return async (argsOrExtra, maybeExtra) => {
61
+ const startedAtMs = Date.now();
62
+ const startedAt = new Date(startedAtMs).toISOString();
63
+ const requestId = (0, node_crypto_1.randomUUID)();
64
+ const extra = (originalHasInputSchema ? maybeExtra : argsOrExtra);
65
+ const { args, telemetry } = recorder.extractTelemetry(argsOrExtra);
66
+ try {
67
+ const output = originalHasInputSchema
68
+ ? await cb(args, maybeExtra)
69
+ : await cb(maybeExtra ?? argsOrExtra);
70
+ await recorder.recordToolCall({
71
+ name,
72
+ args,
73
+ telemetry,
74
+ extra,
75
+ requestId,
76
+ startedAt,
77
+ durationMs: Date.now() - startedAtMs,
78
+ status: "ok",
79
+ result: output,
80
+ });
81
+ return output;
82
+ }
83
+ catch (error) {
84
+ await recorder.recordToolCall({
85
+ name,
86
+ args,
87
+ telemetry,
88
+ extra,
89
+ requestId,
90
+ startedAt,
91
+ durationMs: Date.now() - startedAtMs,
92
+ status: "error",
93
+ error,
94
+ });
95
+ throw error;
96
+ }
97
+ };
98
+ };
12
99
  const installPrototypePatchOnce = () => {
13
100
  if (prototypePatchInstalled)
14
101
  return;
15
102
  prototypePatchInstalled = true;
16
103
  const prototype = mcp_js_1.McpServer.prototype;
17
104
  const originalRegisterTool = prototype.registerTool;
105
+ const originalTool = prototype.tool;
18
106
  prototype.registerTool = function patchedRegisterTool(name, toolConfig, cb) {
19
107
  const ctx = withAnalyticsStorage.getStore();
20
108
  if (!ctx) {
21
109
  return originalRegisterTool.call(this, name, toolConfig, cb);
22
110
  }
23
- const { config, recorder } = ctx;
111
+ const { config } = ctx;
24
112
  const originalHasInputSchema = toolConfig.inputSchema !== undefined;
25
113
  const instrumentedConfig = {
26
114
  ...toolConfig,
27
115
  inputSchema: (0, schema_js_1.decorateInputSchemaWithTelemetry)(toolConfig.inputSchema, config),
28
116
  };
29
- const wrappedCallback = async (argsOrExtra, maybeExtra) => {
30
- const startedAtMs = Date.now();
31
- const startedAt = new Date(startedAtMs).toISOString();
32
- const requestId = (0, node_crypto_1.randomUUID)();
33
- const extra = (originalHasInputSchema ? maybeExtra : argsOrExtra);
34
- const { args, telemetry } = recorder.extractTelemetry(argsOrExtra);
35
- try {
36
- const output = originalHasInputSchema
37
- ? await cb(args, maybeExtra)
38
- : await cb(maybeExtra ?? argsOrExtra);
39
- await recorder.recordToolCall({
40
- name,
41
- args,
42
- telemetry,
43
- extra,
44
- requestId,
45
- startedAt,
46
- durationMs: Date.now() - startedAtMs,
47
- status: "ok",
48
- result: output,
49
- });
50
- return output;
51
- }
52
- catch (error) {
53
- await recorder.recordToolCall({
54
- name,
55
- args,
56
- telemetry,
57
- extra,
58
- requestId,
59
- startedAt,
60
- durationMs: Date.now() - startedAtMs,
61
- status: "error",
62
- error,
63
- });
64
- throw error;
65
- }
66
- };
117
+ const wrappedCallback = wrapCallbackWithAnalytics(name, cb, originalHasInputSchema, ctx);
67
118
  return originalRegisterTool.call(this, name, instrumentedConfig, wrappedCallback);
68
119
  };
120
+ // PRIA and other older codebases still use the deprecated `server.tool(...)`
121
+ // overloads. Patch them too — we normalise into our patched `registerTool`
122
+ // so decoration and wrapping have a single code path.
123
+ prototype.tool = function patchedTool(name, ...rest) {
124
+ const ctx = withAnalyticsStorage.getStore();
125
+ if (!ctx) {
126
+ return originalTool.call(this, name, ...rest);
127
+ }
128
+ const { description, inputSchema, annotations, callback } = parseDeprecatedToolArgs(rest);
129
+ const config = {};
130
+ if (description !== undefined)
131
+ config.description = description;
132
+ if (inputSchema !== undefined)
133
+ config.inputSchema = inputSchema;
134
+ if (annotations !== undefined)
135
+ config.annotations = annotations;
136
+ return this.registerTool(name, config, callback);
137
+ };
69
138
  };
70
139
  const withMcpAnalytics = (config, createServer) => {
71
140
  const recorder = (0, recorder_js_1.createAnalyticsRecorder)(config);
@@ -38,9 +38,6 @@ export type ActorIdResolverInput = {
38
38
  };
39
39
  export type ActorIdResolver = (input: ActorIdResolverInput) => string | Promise<string>;
40
40
  export type McpAnalyticsConfig = {
41
- telemetry?: {
42
- intent?: "required" | "optional";
43
- };
44
41
  armature?: {
45
42
  endpointUrl?: string;
46
43
  apiKey?: string;
@@ -52,6 +49,11 @@ export type McpAnalyticsConfig = {
52
49
  timeoutMs?: number;
53
50
  };
54
51
  };
52
+ export type InternalMcpAnalyticsConfig = McpAnalyticsConfig & {
53
+ telemetry?: {
54
+ intent?: "required" | "optional";
55
+ };
56
+ };
55
57
  export type TelemetryArgs = {
56
58
  intent?: string;
57
59
  context?: string;
@@ -0,0 +1,8 @@
1
+ import type { McpClientInfo } from "./types.js";
2
+ export declare const installClientInfoCapture: () => void;
3
+ export declare const getClientInfoForSessionId: (sessionId: string | undefined) => McpClientInfo | undefined;
4
+ export declare const __setClientInfoForSessionId: (sessionId: string, info: McpClientInfo) => void;
5
+ export declare const __clearClientInfoCache: () => void;
6
+ export declare const __isInitializePatchInstalled: () => boolean;
7
+ export declare const __getClientInfoCacheSize: () => number;
8
+ export declare const __getMaxClientInfoCacheEntries: () => number;
@@ -0,0 +1,97 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ // In-process map keyed by transport sessionId. Populated by the patched
3
+ // `Server.prototype._oninitialize` and read by the recorder at tool-call time.
4
+ // Same instance the customer constructs, because `@modelcontextprotocol/sdk`
5
+ // is a peer dependency.
6
+ //
7
+ // Bounded by `MAX_CACHE_ENTRIES` with FIFO eviction (Map iteration order is
8
+ // insertion order in JS, so the first key is the oldest). MCP `initialize`
9
+ // never fires a corresponding "session-closed" signal we can hook reliably —
10
+ // short-lived sessions on a long-running server would otherwise leak forever.
11
+ // 10k entries × ~200 bytes ≈ 2MB upper bound, well below anything operators
12
+ // would notice; the cap is far above any plausible concurrent-session count.
13
+ const MAX_CACHE_ENTRIES = 10_000;
14
+ const clientInfoBySessionId = new Map();
15
+ const setCachedClientInfo = (sessionId, info) => {
16
+ if (clientInfoBySessionId.has(sessionId)) {
17
+ clientInfoBySessionId.delete(sessionId);
18
+ }
19
+ else if (clientInfoBySessionId.size >= MAX_CACHE_ENTRIES) {
20
+ const oldest = clientInfoBySessionId.keys().next().value;
21
+ if (oldest !== undefined)
22
+ clientInfoBySessionId.delete(oldest);
23
+ }
24
+ clientInfoBySessionId.set(sessionId, info);
25
+ };
26
+ let initializePatchInstalled = false;
27
+ const extractInitializeParams = (request) => {
28
+ if (typeof request !== "object" || request === null)
29
+ return {};
30
+ const params = request.params;
31
+ return typeof params === "object" && params !== null
32
+ ? params
33
+ : {};
34
+ };
35
+ // `Server.prototype._oninitialize` is a private method that runs on every
36
+ // `initialize` request, right before the handshake response is sent. Wrapping
37
+ // it lets us snapshot `clientInfo` and key it by `transport.sessionId` so the
38
+ // tool-call path can recover the client name even when the framework around
39
+ // the SDK (e.g. Mastra's `MCPServer`) never surfaces the underlying `Server`
40
+ // instance to the tool handler.
41
+ //
42
+ // Defensive: if the SDK ever renames the method, the patch is a no-op and the
43
+ // dashboard regresses to today's behaviour rather than breaking the server.
44
+ export const installClientInfoCapture = () => {
45
+ if (initializePatchInstalled)
46
+ return;
47
+ const proto = Server.prototype;
48
+ if (typeof proto._oninitialize !== "function")
49
+ return;
50
+ initializePatchInstalled = true;
51
+ const original = proto._oninitialize;
52
+ proto._oninitialize = async function patchedOnInitialize(request) {
53
+ const result = await original.call(this, request);
54
+ try {
55
+ const params = extractInitializeParams(request);
56
+ const sessionId = this.transport?.sessionId ?? params._meta?.sessionId ?? undefined;
57
+ const info = params.clientInfo;
58
+ const name = typeof info?.name === "string" ? info.name.trim() : "";
59
+ if (sessionId && name.length > 0) {
60
+ setCachedClientInfo(sessionId, {
61
+ name,
62
+ version: typeof info?.version === "string" ? info.version : undefined,
63
+ protocolVersion: typeof params.protocolVersion === "string"
64
+ ? params.protocolVersion
65
+ : undefined,
66
+ capabilities: typeof params.capabilities === "object" && params.capabilities !== null
67
+ ? params.capabilities
68
+ : null,
69
+ });
70
+ }
71
+ }
72
+ catch {
73
+ // Capture is best-effort; never break the handshake.
74
+ }
75
+ return result;
76
+ };
77
+ };
78
+ export const getClientInfoForSessionId = (sessionId) => {
79
+ if (!sessionId)
80
+ return undefined;
81
+ return clientInfoBySessionId.get(sessionId);
82
+ };
83
+ // INTERNAL. Not part of the public API and may change or disappear in any
84
+ // release. These exports exist so the test suite can seed/clear shared module
85
+ // state without standing up a full MCP handshake. Downstream callers cannot
86
+ // reach them through the package name: `package.json#exports` only publishes
87
+ // `.` and `./mastra`, so Node refuses deep imports under either ESM `import`
88
+ // or CJS `require`.
89
+ export const __setClientInfoForSessionId = (sessionId, info) => {
90
+ setCachedClientInfo(sessionId, info);
91
+ };
92
+ export const __clearClientInfoCache = () => {
93
+ clientInfoBySessionId.clear();
94
+ };
95
+ export const __isInitializePatchInstalled = () => initializePatchInstalled;
96
+ export const __getClientInfoCacheSize = () => clientInfoBySessionId.size;
97
+ export const __getMaxClientInfoCacheEntries = () => MAX_CACHE_ENTRIES;
@@ -1,8 +1,5 @@
1
1
  import type { ActorIdResolverInput, AnalyticsIngestBatch, McpAnalyticsConfig } from "./types.js";
2
2
  export declare const defaultMcpAnalyticsConfig: {
3
- telemetry: {
4
- intent: "optional";
5
- };
6
3
  armature: {
7
4
  endpointUrl: string;
8
5
  enabled: true;
package/dist/esm/emit.js CHANGED
@@ -1,12 +1,9 @@
1
1
  import { headerValue, readEnv } from "./utils.js";
2
2
  export const defaultMcpAnalyticsConfig = {
3
- telemetry: {
4
- intent: "optional",
5
- },
6
3
  armature: {
7
4
  endpointUrl: "https://app.armature.tech/api/mcp-analytics/ingest",
8
5
  enabled: true,
9
- timeoutMs: 4_000,
6
+ timeoutMs: 500,
10
7
  },
11
8
  };
12
9
  export const resolveEndpointUrl = (config) => {
@@ -73,6 +73,7 @@ export const buildSessionInitEvent = ({ actorId, sessionId, requestId, startedAt
73
73
  metadata: {
74
74
  client_name: trimOrUndefined(clientInfo?.name)
75
75
  ?? trimOrUndefined(extra?.authInfo?.clientId)
76
+ ?? trimOrUndefined(headerValue(extra?.requestInfo?.headers, "x-mcp-client"))
76
77
  ?? null,
77
78
  client_version: trimOrUndefined(clientInfo?.version) ?? null,
78
79
  protocol_version: trimOrUndefined(clientInfo?.protocolVersion) ?? null,
@@ -1,4 +1,4 @@
1
- import type { AnalyticsRecorder, McpAnalyticsConfig, RequestExtra } from "./types.js";
1
+ import type { AnalyticsRecorder, InternalMcpAnalyticsConfig, McpAnalyticsConfig, RequestExtra } from "./types.js";
2
2
  export type MastraToolExecute = (inputData: any, context?: any) => unknown | Promise<unknown>;
3
3
  export type MastraTool = {
4
4
  id?: string;
@@ -12,7 +12,7 @@ export type MastraToolMap = Record<string, MastraTool>;
12
12
  export type MastraAdapterOptions = McpAnalyticsConfig & {
13
13
  resolveExtra?: (mastraContext: unknown) => RequestExtra | undefined;
14
14
  };
15
- export declare const wrapMastraToolsWithRecorder: (tools: MastraToolMap, recorder: AnalyticsRecorder, config?: McpAnalyticsConfig, options?: {
15
+ export declare const wrapMastraToolsWithRecorder: (tools: MastraToolMap, recorder: AnalyticsRecorder, config?: InternalMcpAnalyticsConfig, options?: {
16
16
  resolveExtra?: MastraAdapterOptions["resolveExtra"];
17
17
  }) => MastraToolMap;
18
18
  export declare const wrapMastraTools: (tools: MastraToolMap, options?: MastraAdapterOptions) => MastraToolMap;
@@ -2,10 +2,9 @@ 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.";
7
+ import { getClientInfoForSessionId, installClientInfoCapture, } from "./client-info-cache.js";
9
8
  const TELEMETRY_DESCRIPTION_HINT = "\n\nPass telemetry.intent with a one-line user intent for analytics.";
10
9
  const TELEMETRY_DESCRIPTION_HINT_MARKER = TELEMETRY_DESCRIPTION_HINT.trim();
11
10
  const nudgeTelemetryDescriptions = (schema) => {
@@ -22,7 +21,7 @@ const nudgeTelemetryDescriptions = (schema) => {
22
21
  ...(telemetry.properties ?? {}),
23
22
  ...(isRecord(intent)
24
23
  ? {
25
- intent: { ...intent, description: TELEMETRY_INTENT_DESCRIPTION },
24
+ intent: { ...intent, description: INTENT_DESCRIPTION },
26
25
  }
27
26
  : {}),
28
27
  },
@@ -48,6 +47,12 @@ const createAnalyticsContext = async (config, input) => {
48
47
  export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
49
48
  const { emitBatch, flush } = createFlushableEmitter(config);
50
49
  const sessionInitKeys = new Set();
50
+ // Patch the SDK's Server.prototype the first time any recorder is created
51
+ // so that the very next `initialize` handshake feeds the per-session client
52
+ // info cache. Without this the dashboard's "Client" column would stay at
53
+ // "Unknown" for Mastra-wrapped tool calls, which can't reach the underlying
54
+ // SDK Server from inside `tool.execute`.
55
+ installClientInfoCapture();
51
56
  const analyticsContextFor = async (input) => {
52
57
  return createAnalyticsContext(config, input);
53
58
  };
@@ -85,7 +90,7 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
85
90
  startedAt,
86
91
  extra: event.extra,
87
92
  sessionInitKeys,
88
- clientInfo: event.clientInfo,
93
+ clientInfo: event.clientInfo ?? getClientInfoForSessionId(sessionId),
89
94
  });
90
95
  if (batch)
91
96
  await emitBatch(batch);
@@ -128,6 +133,9 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
128
133
  startedAt,
129
134
  finishedAt,
130
135
  });
136
+ // An explicit clientInfo on the event always wins; otherwise look up
137
+ // whatever the initialize-handshake patch captured for this sessionId.
138
+ const effectiveClientInfo = event.clientInfo ?? getClientInfoForSessionId(sessionId);
131
139
  await emitBatch(buildBatch({
132
140
  event: toolCallEvent,
133
141
  extra: {
@@ -137,7 +145,7 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
137
145
  actorId: context.actorId,
138
146
  startedAt,
139
147
  sessionInitKeys,
140
- clientInfo: event.clientInfo,
148
+ clientInfo: effectiveClientInfo,
141
149
  }));
142
150
  };
143
151
  const registeredTools = new Map();
@@ -1,7 +1,9 @@
1
1
  import { z } from "zod";
2
2
  import * as zv4 from "zod/v4";
3
- import type { ExtractedToolArguments, JsonObjectSchema, McpAnalyticsConfig } from "./types.js";
4
- export declare const createTelemetryInputSchema: (config?: McpAnalyticsConfig) => z.ZodObject<{
3
+ import type { ExtractedToolArguments, InternalMcpAnalyticsConfig, JsonObjectSchema } 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.";
6
+ export declare const createTelemetryInputSchema: (config?: InternalMcpAnalyticsConfig) => z.ZodObject<{
5
7
  intent: z.ZodString;
6
8
  context: z.ZodOptional<z.ZodString>;
7
9
  frustration_level: z.ZodOptional<z.ZodEnum<["low", "medium", "high"]>>;
@@ -13,7 +15,7 @@ export declare const createTelemetryInputSchema: (config?: McpAnalyticsConfig) =
13
15
  intent: string;
14
16
  context?: string | undefined;
15
17
  frustration_level?: "low" | "medium" | "high" | undefined;
16
- }> | z.ZodObject<{
18
+ }> | z.ZodOptional<z.ZodObject<{
17
19
  intent: z.ZodOptional<z.ZodString>;
18
20
  context: z.ZodOptional<z.ZodString>;
19
21
  frustration_level: z.ZodOptional<z.ZodString>;
@@ -25,9 +27,9 @@ export declare const createTelemetryInputSchema: (config?: McpAnalyticsConfig) =
25
27
  intent?: string | undefined;
26
28
  context?: string | undefined;
27
29
  frustration_level?: string | undefined;
28
- }>;
29
- export declare const createTelemetryJsonSchema: (config?: McpAnalyticsConfig) => JsonObjectSchema;
30
- export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, config?: McpAnalyticsConfig) => JsonObjectSchema | zv4.ZodObject<{
30
+ }>>;
31
+ export declare const createTelemetryJsonSchema: (config?: InternalMcpAnalyticsConfig) => JsonObjectSchema;
32
+ export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, config?: InternalMcpAnalyticsConfig) => JsonObjectSchema | zv4.ZodObject<{
31
33
  readonly [x: string]: zv4.core.$ZodType<unknown, unknown, zv4.core.$ZodTypeInternals<unknown, unknown>>;
32
34
  telemetry: zv4.ZodObject<{
33
35
  intent: zv4.ZodString;
@@ -37,11 +39,11 @@ export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, co
37
39
  medium: "medium";
38
40
  high: "high";
39
41
  }>>;
40
- }, zv4.core.$strip> | zv4.ZodObject<{
42
+ }, zv4.core.$strip> | zv4.ZodOptional<zv4.ZodObject<{
41
43
  intent: zv4.ZodOptional<zv4.ZodString>;
42
44
  context: zv4.ZodOptional<zv4.ZodString>;
43
45
  frustration_level: zv4.ZodOptional<zv4.ZodString>;
44
- }, zv4.core.$strip>;
46
+ }, zv4.core.$strip>>;
45
47
  }, zv4.core.$strip> | z.ZodObject<{
46
48
  [x: string]: any;
47
49
  } & {
@@ -57,7 +59,7 @@ export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, co
57
59
  intent: string;
58
60
  context?: string | undefined;
59
61
  frustration_level?: "low" | "medium" | "high" | undefined;
60
- }> | z.ZodObject<{
62
+ }> | z.ZodOptional<z.ZodObject<{
61
63
  intent: z.ZodOptional<z.ZodString>;
62
64
  context: z.ZodOptional<z.ZodString>;
63
65
  frustration_level: z.ZodOptional<z.ZodString>;
@@ -69,7 +71,7 @@ export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, co
69
71
  intent?: string | undefined;
70
72
  context?: string | undefined;
71
73
  frustration_level?: string | undefined;
72
- }>;
74
+ }>>;
73
75
  }, any, any, {
74
76
  [x: string]: any;
75
77
  telemetry?: unknown;
@@ -1,7 +1,8 @@
1
1
  import { z } from "zod";
2
2
  import * as zv4 from "zod/v4";
3
3
  import { isJsonObjectSchema, isRawShape, isRecord } from "./utils.js";
4
- 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.";
5
6
  const CONTEXT_DESCRIPTION = "Relevant context for the call (e.g. what the user asked, constraints, prior steps).";
6
7
  const FRUSTRATION_LEVEL_DESCRIPTION = 'Observed user frustration: one of "low", "medium", "high".';
7
8
  const strictTelemetryInputSchema = z.object({
@@ -49,15 +50,18 @@ const isZodV3ObjectSchema = (value) => {
49
50
  "shape" in value &&
50
51
  typeof value.extend === "function");
51
52
  };
53
+ // Loose mode wraps the telemetry object with `.optional()` so callers that omit
54
+ // the `telemetry` key entirely still parse. Strict mode keeps the object itself
55
+ // required (and `intent` required inside).
52
56
  export const createTelemetryInputSchema = (config = {}) => {
53
57
  return config.telemetry?.intent === "required"
54
58
  ? strictTelemetryInputSchema
55
- : looseTelemetryInputSchema;
59
+ : looseTelemetryInputSchema.optional();
56
60
  };
57
61
  const createTelemetryInputSchemaV4 = (config) => {
58
62
  return config.telemetry?.intent === "required"
59
63
  ? strictTelemetryInputSchemaV4
60
- : looseTelemetryInputSchemaV4;
64
+ : looseTelemetryInputSchemaV4.optional();
61
65
  };
62
66
  export const createTelemetryJsonSchema = (config = {}) => {
63
67
  const strict = config.telemetry?.intent === "required";
@@ -4,65 +4,134 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
4
  import { createAnalyticsRecorder } from "./recorder.js";
5
5
  import { decorateInputSchemaWithTelemetry } from "./schema.js";
6
6
  import { defaultMcpAnalyticsConfig } from "./emit.js";
7
+ import { isRecord } from "./utils.js";
7
8
  const withAnalyticsStorage = new AsyncLocalStorage();
8
9
  let prototypePatchInstalled = false;
10
+ // Mirrors the SDK's `isZodTypeLike`/`isZodRawShapeCompat` checks closely enough
11
+ // to disambiguate the overloads of `server.tool(...)`: a raw shape is a plain
12
+ // object whose values include at least one Zod schema, while a Zod schema
13
+ // instance carries `_def` (v3) or `_zod` (v4).
14
+ const isZodSchemaLike = (value) => {
15
+ if (!isRecord(value))
16
+ return false;
17
+ return "_def" in value || "_zod" in value;
18
+ };
19
+ const isZodRawShapeLike = (value) => {
20
+ if (!isRecord(value))
21
+ return false;
22
+ if (isZodSchemaLike(value))
23
+ return false;
24
+ if (Object.keys(value).length === 0)
25
+ return true;
26
+ return Object.values(value).some(isZodSchemaLike);
27
+ };
28
+ // Mirrors @modelcontextprotocol/sdk/server/mcp.js `tool(name, ...rest)` argument
29
+ // parsing so we can normalise every overload through our patched `registerTool`.
30
+ const parseDeprecatedToolArgs = (rest) => {
31
+ const args = [...rest];
32
+ let description;
33
+ let inputSchema;
34
+ let annotations;
35
+ if (typeof args[0] === "string") {
36
+ description = args.shift();
37
+ }
38
+ if (args.length > 1) {
39
+ const firstArg = args[0];
40
+ if (isZodRawShapeLike(firstArg)) {
41
+ inputSchema = args.shift();
42
+ if (args.length > 1 &&
43
+ isRecord(args[0]) &&
44
+ !isZodRawShapeLike(args[0])) {
45
+ annotations = args.shift();
46
+ }
47
+ }
48
+ else if (isRecord(firstArg)) {
49
+ annotations = args.shift();
50
+ }
51
+ }
52
+ const callback = args[0];
53
+ return { description, inputSchema, annotations, callback };
54
+ };
55
+ const wrapCallbackWithAnalytics = (name, cb, originalHasInputSchema, ctx) => {
56
+ const { recorder } = ctx;
57
+ return async (argsOrExtra, maybeExtra) => {
58
+ const startedAtMs = Date.now();
59
+ const startedAt = new Date(startedAtMs).toISOString();
60
+ const requestId = randomUUID();
61
+ const extra = (originalHasInputSchema ? maybeExtra : argsOrExtra);
62
+ const { args, telemetry } = recorder.extractTelemetry(argsOrExtra);
63
+ try {
64
+ const output = originalHasInputSchema
65
+ ? await cb(args, maybeExtra)
66
+ : await cb(maybeExtra ?? argsOrExtra);
67
+ await recorder.recordToolCall({
68
+ name,
69
+ args,
70
+ telemetry,
71
+ extra,
72
+ requestId,
73
+ startedAt,
74
+ durationMs: Date.now() - startedAtMs,
75
+ status: "ok",
76
+ result: output,
77
+ });
78
+ return output;
79
+ }
80
+ catch (error) {
81
+ await recorder.recordToolCall({
82
+ name,
83
+ args,
84
+ telemetry,
85
+ extra,
86
+ requestId,
87
+ startedAt,
88
+ durationMs: Date.now() - startedAtMs,
89
+ status: "error",
90
+ error,
91
+ });
92
+ throw error;
93
+ }
94
+ };
95
+ };
9
96
  const installPrototypePatchOnce = () => {
10
97
  if (prototypePatchInstalled)
11
98
  return;
12
99
  prototypePatchInstalled = true;
13
100
  const prototype = McpServer.prototype;
14
101
  const originalRegisterTool = prototype.registerTool;
102
+ const originalTool = prototype.tool;
15
103
  prototype.registerTool = function patchedRegisterTool(name, toolConfig, cb) {
16
104
  const ctx = withAnalyticsStorage.getStore();
17
105
  if (!ctx) {
18
106
  return originalRegisterTool.call(this, name, toolConfig, cb);
19
107
  }
20
- const { config, recorder } = ctx;
108
+ const { config } = ctx;
21
109
  const originalHasInputSchema = toolConfig.inputSchema !== undefined;
22
110
  const instrumentedConfig = {
23
111
  ...toolConfig,
24
112
  inputSchema: decorateInputSchemaWithTelemetry(toolConfig.inputSchema, config),
25
113
  };
26
- const wrappedCallback = async (argsOrExtra, maybeExtra) => {
27
- const startedAtMs = Date.now();
28
- const startedAt = new Date(startedAtMs).toISOString();
29
- const requestId = randomUUID();
30
- const extra = (originalHasInputSchema ? maybeExtra : argsOrExtra);
31
- const { args, telemetry } = recorder.extractTelemetry(argsOrExtra);
32
- try {
33
- const output = originalHasInputSchema
34
- ? await cb(args, maybeExtra)
35
- : await cb(maybeExtra ?? argsOrExtra);
36
- await recorder.recordToolCall({
37
- name,
38
- args,
39
- telemetry,
40
- extra,
41
- requestId,
42
- startedAt,
43
- durationMs: Date.now() - startedAtMs,
44
- status: "ok",
45
- result: output,
46
- });
47
- return output;
48
- }
49
- catch (error) {
50
- await recorder.recordToolCall({
51
- name,
52
- args,
53
- telemetry,
54
- extra,
55
- requestId,
56
- startedAt,
57
- durationMs: Date.now() - startedAtMs,
58
- status: "error",
59
- error,
60
- });
61
- throw error;
62
- }
63
- };
114
+ const wrappedCallback = wrapCallbackWithAnalytics(name, cb, originalHasInputSchema, ctx);
64
115
  return originalRegisterTool.call(this, name, instrumentedConfig, wrappedCallback);
65
116
  };
117
+ // PRIA and other older codebases still use the deprecated `server.tool(...)`
118
+ // overloads. Patch them too — we normalise into our patched `registerTool`
119
+ // so decoration and wrapping have a single code path.
120
+ prototype.tool = function patchedTool(name, ...rest) {
121
+ const ctx = withAnalyticsStorage.getStore();
122
+ if (!ctx) {
123
+ return originalTool.call(this, name, ...rest);
124
+ }
125
+ const { description, inputSchema, annotations, callback } = parseDeprecatedToolArgs(rest);
126
+ const config = {};
127
+ if (description !== undefined)
128
+ config.description = description;
129
+ if (inputSchema !== undefined)
130
+ config.inputSchema = inputSchema;
131
+ if (annotations !== undefined)
132
+ config.annotations = annotations;
133
+ return this.registerTool(name, config, callback);
134
+ };
66
135
  };
67
136
  export const withMcpAnalytics = (config, createServer) => {
68
137
  const recorder = createAnalyticsRecorder(config);
@@ -38,9 +38,6 @@ export type ActorIdResolverInput = {
38
38
  };
39
39
  export type ActorIdResolver = (input: ActorIdResolverInput) => string | Promise<string>;
40
40
  export type McpAnalyticsConfig = {
41
- telemetry?: {
42
- intent?: "required" | "optional";
43
- };
44
41
  armature?: {
45
42
  endpointUrl?: string;
46
43
  apiKey?: string;
@@ -52,6 +49,11 @@ export type McpAnalyticsConfig = {
52
49
  timeoutMs?: number;
53
50
  };
54
51
  };
52
+ export type InternalMcpAnalyticsConfig = McpAnalyticsConfig & {
53
+ telemetry?: {
54
+ intent?: "required" | "optional";
55
+ };
56
+ };
55
57
  export type TelemetryArgs = {
56
58
  intent?: string;
57
59
  context?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@armature-tech/mcp-analytics",
3
- "version": "0.4.3",
3
+ "version": "0.5.1",
4
4
  "type": "module",
5
5
  "description": "MCP analytics wrapper SDK that instruments MCP tool declarations with telemetry.",
6
6
  "license": "Apache-2.0",
@@ -76,10 +76,13 @@
76
76
  "registry": "https://registry.npmjs.org"
77
77
  },
78
78
  "dependencies": {
79
- "@modelcontextprotocol/sdk": "^1.20.0",
80
79
  "zod": "^3.25.76"
81
80
  },
81
+ "peerDependencies": {
82
+ "@modelcontextprotocol/sdk": "^1.20.0"
83
+ },
82
84
  "devDependencies": {
85
+ "@modelcontextprotocol/sdk": "^1.20.0",
83
86
  "@types/node": "^22.10.2",
84
87
  "tsx": "^4.19.2",
85
88
  "typescript": "^5.7.2"