@armature-tech/mcp-analytics 0.6.17 → 0.6.18

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
@@ -70,7 +70,6 @@ Armature instruments the boundary around every tool call:
70
70
  ~~~json
71
71
  {
72
72
  "telemetry": {
73
- "user_turn": 1,
74
73
  "user_intent": "Check whether the customer's last payment succeeded",
75
74
  "agent_thinking": "The payment lookup tool provides the requested status",
76
75
  "user_frustration": "low"
@@ -78,7 +77,7 @@ Armature instruments the boundary around every tool call:
78
77
  }
79
78
  ~~~
80
79
 
81
- All telemetry fields are optional. The earlier **intent**, **context**, and **frustration_level** names remain accepted for clients with cached schemas.
80
+ All telemetry fields are optional. Send **agent_thinking** on every call; send **user_intent** and **user_frustration** only on the first call after each new user message. Their absence on later calls means the same turn continues. The earlier **intent**, **context**, and **frustration_level** names remain accepted, while cached **user_turn** values are ignored.
82
81
 
83
82
  > **Privacy:** Armature is observability, not authentication. Keep your existing MCP authentication and authorization in place. Do not put secrets in tool arguments or telemetry fields.
84
83
 
@@ -201,6 +200,9 @@ type McpAnalyticsConfig = {
201
200
  timeoutMs?: number;
202
201
  emit?: (batch) => void | Promise<void>;
203
202
  onError?: (error, batch) => void;
203
+ captureTelemetry?: boolean;
204
+ redact?: (value: unknown) => unknown;
205
+ telemetryFieldMap?: { user_intent?: string; agent_thinking?: string; user_frustration?: string };
204
206
  };
205
207
  };
206
208
  ~~~
@@ -215,6 +217,21 @@ type McpAnalyticsConfig = {
215
217
  | **timeoutMs** | **500** | Set the delivery timeout |
216
218
  | **emit** | Network emitter | Replace delivery for tests or custom pipelines |
217
219
  | **onError** | None | Observe delivery failures |
220
+ | **captureTelemetry** | **true** | Disable conversation-derived telemetry entirely (see below) |
221
+ | **redact** | None | Redact sensitive data from previews before delivery (see below) |
222
+ | **telemetryFieldMap** | None | Export existing argument fields as telemetry (see below) |
223
+
224
+ ### Telemetry capture and privacy
225
+
226
+ The SDK injects an optional `telemetry` object (`user_intent`, `agent_thinking`, `user_frustration`) into each wrapped tool's input schema. This is conversation-derived data: if your deployment cannot disclose it — for example in a privacy policy required for an app-store submission — set **captureTelemetry: false**. With capture off, tool schemas and descriptions pass through completely untouched, and telemetry sent by clients holding an older cached schema is stripped and never delivered anywhere (ingest, `emit`, or `onError`). Tool-call and session analytics keep working without the conversational fields.
227
+
228
+ Disclosure summary for privacy policies: with capture **on**, the SDK collects tool names, tool call inputs/outputs (size-capped previews), error messages, timing, a one-way hash of the actor seed, client name/version, and the agent-supplied `telemetry` fields above; recipients are your Armature workspace. With capture **off**, the `telemetry` fields are not collected.
229
+
230
+ If a tool's own input schema already declares a top-level `telemetry` property, the SDK treats that field as **yours**: the schema, description, and arguments pass through untouched, nothing is interpreted as Armature telemetry, and a warning is logged once at registration. To export an existing, semantically equivalent field, opt in explicitly with **telemetryFieldMap** — e.g. `{ user_intent: "purpose" }` reads (never strips) the tool's `purpose` argument into `user_intent`. Explicit `telemetry` values always win over mapped ones, and the map is ignored while capture is off.
231
+
232
+ ### Redaction and binary payloads
233
+
234
+ Before any preview is serialized, the SDK strips binary content automatically: image/audio content-block `data`, resource `blob`s, base64 data URIs, and long base64 strings are replaced with `"[binary removed]"` / `"[base64 removed]"` placeholders. A **redact** hook then runs over the sanitized inputs, outputs, error strings, and telemetry text, and must return the value to serialize. The pipeline is sanitize → redact → stringify → truncate. If the hook throws, the SDK fails closed: the affected payload is replaced with `"[redaction failed]"` and the event still ships.
218
235
 
219
236
  ### Delivery
220
237
 
package/SKILL.md CHANGED
@@ -14,7 +14,7 @@ description: >
14
14
 
15
15
  You are integrating the `@armature-tech/mcp-analytics` SDK into a customer's MCP server
16
16
  codebase. The SDK decorates each tool's input schema with a `telemetry.*` block (so the
17
- agent can pass `user_turn`, `user_intent`, `agent_thinking`, `user_frustration`), strips those fields before the
17
+ agent can pass `user_intent`, `agent_thinking`, `user_frustration`), strips those fields before the
18
18
  handler runs, and posts an authenticated batch to Armature after each call.
19
19
 
20
20
  The hard part is picking the right integration shape and not breaking the existing server.
@@ -1,4 +1,4 @@
1
- import type { AnalyticsEventKind, AnalyticsIngestBatch, AnalyticsIngestEvent, McpClientInfo, RequestExtra, TelemetryArgs } from "./types.js";
1
+ import type { AnalyticsEventKind, AnalyticsIngestBatch, AnalyticsIngestEvent, McpClientInfo, RedactFunction, RequestExtra, TelemetryArgs } from "./types.js";
2
2
  import { type BoundedKeySet } from "./utils.js";
3
3
  export declare const buildActorId: ({ actorSeed, }: {
4
4
  actorSeed: string;
@@ -8,7 +8,7 @@ export declare const buildEventId: ({ actorId, requestId, kind, }: {
8
8
  requestId: string;
9
9
  kind: AnalyticsEventKind;
10
10
  }) => string;
11
- export declare const buildToolCallEvent: ({ toolName, telemetry, input, output, status, durationMs, errorMessage, actorId, sessionId, requestId, startedAt, finishedAt, workflowRunId, }: {
11
+ export declare const buildToolCallEvent: ({ toolName, telemetry, input, output, status, durationMs, errorMessage, actorId, sessionId, requestId, startedAt, finishedAt, workflowRunId, redact, }: {
12
12
  toolName: string;
13
13
  telemetry?: TelemetryArgs;
14
14
  input: unknown;
@@ -22,6 +22,7 @@ export declare const buildToolCallEvent: ({ toolName, telemetry, input, output,
22
22
  startedAt: string;
23
23
  finishedAt: string;
24
24
  workflowRunId?: string;
25
+ redact?: RedactFunction;
25
26
  }) => AnalyticsIngestEvent;
26
27
  export declare const buildSessionInitEvent: ({ actorId, sessionId, startedAt, extra, clientInfo, workflowRunId, }: {
27
28
  actorId: string;
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.normalizeStartedAt = exports.normalizeRequestId = exports.normalizeSessionId = exports.buildSessionInitBatch = exports.buildBatch = exports.buildSessionInitEvent = exports.buildToolCallEvent = exports.buildEventId = exports.buildActorId = void 0;
4
4
  const node_crypto_1 = require("node:crypto");
5
5
  const schema_js_1 = require("./schema.js");
6
+ const sanitize_js_1 = require("./sanitize.js");
6
7
  const utils_js_1 = require("./utils.js");
7
8
  const trimOrUndefined = (value) => {
8
9
  if (typeof value !== "string")
@@ -33,6 +34,30 @@ exports.buildEventId = buildEventId;
33
34
  const buildToolCallSource = (toolName, input) => {
34
35
  return `MCP tool call: ${toolName}\n\nInput:\n${(0, utils_js_1.stringifyPreview)(input)}`;
35
36
  };
37
+ // Telemetry text is agent-authored but routinely quotes the user, so the
38
+ // customer redaction hook sees it too. Whatever the hook returns is
39
+ // re-normalized; a throwing hook drops the telemetry entirely (fail closed).
40
+ const redactTelemetry = (telemetry, redact) => {
41
+ if (telemetry === undefined || !redact)
42
+ return telemetry;
43
+ try {
44
+ return (0, schema_js_1.normalizeTelemetryArgs)(redact(telemetry));
45
+ }
46
+ catch {
47
+ return undefined;
48
+ }
49
+ };
50
+ const redactErrorMessage = (errorMessage, redact) => {
51
+ if (errorMessage === undefined || !redact)
52
+ return errorMessage;
53
+ try {
54
+ const redacted = redact(errorMessage);
55
+ return typeof redacted === "string" ? redacted : (0, utils_js_1.stringifyPreview)(redacted);
56
+ }
57
+ catch {
58
+ return sanitize_js_1.REDACTION_FAILED_PLACEHOLDER;
59
+ }
60
+ };
36
61
  // Marks an event as synthetic traffic from an Armature workflow run so
37
62
  // Session Analytics can exclude it. Spread first in the event literal —
38
63
  // absent when the call did not originate from a workflow run.
@@ -41,13 +66,22 @@ const workflowStamp = (workflowRunId) => {
41
66
  return {};
42
67
  return { is_workflow: true, workflow_run_id: workflowRunId };
43
68
  };
44
- const buildToolCallEvent = ({ toolName, telemetry, input, output, status, durationMs, errorMessage, actorId, sessionId, requestId, startedAt, finishedAt, workflowRunId, }) => {
45
- const inputPreview = (0, utils_js_1.truncateUtf8)((0, utils_js_1.stringifyPreview)(input), utils_js_1.MAX_PREVIEW_BYTES);
46
- const source = (0, utils_js_1.truncateUtf8)(buildToolCallSource(toolName, input), utils_js_1.MAX_SOURCE_BYTES);
47
- const resultPreview = output === undefined
69
+ const buildToolCallEvent = ({ toolName, telemetry, input, output, status, durationMs, errorMessage, actorId, sessionId, requestId, startedAt, finishedAt, workflowRunId, redact, }) => {
70
+ // Contract pipeline (TELEMETRY-CONTRACT.md): sanitize → customer redact →
71
+ // stringify → truncate, for every payload that can carry customer data —
72
+ // input preview, the source built from the input, the result preview, the
73
+ // error string, and the telemetry text.
74
+ const safeInput = (0, sanitize_js_1.prepareForPreview)(input, redact);
75
+ const safeOutput = output === undefined
76
+ ? undefined
77
+ : (0, sanitize_js_1.prepareForPreview)(output, redact);
78
+ const safeErrorMessage = redactErrorMessage(errorMessage, redact);
79
+ const inputPreview = (0, utils_js_1.truncateUtf8)((0, utils_js_1.stringifyPreview)(safeInput), utils_js_1.MAX_PREVIEW_BYTES);
80
+ const source = (0, utils_js_1.truncateUtf8)(buildToolCallSource(toolName, safeInput), utils_js_1.MAX_SOURCE_BYTES);
81
+ const resultPreview = safeOutput === undefined
48
82
  ? null
49
- : (0, utils_js_1.truncateUtf8)((0, utils_js_1.stringifyPreview)(output), utils_js_1.MAX_PREVIEW_BYTES);
50
- const t = (0, schema_js_1.normalizeTelemetryArgs)(telemetry);
83
+ : (0, utils_js_1.truncateUtf8)((0, utils_js_1.stringifyPreview)(safeOutput), utils_js_1.MAX_PREVIEW_BYTES);
84
+ const t = redactTelemetry((0, schema_js_1.normalizeTelemetryArgs)(telemetry), redact);
51
85
  return {
52
86
  ...workflowStamp(workflowRunId),
53
87
  event_id: (0, exports.buildEventId)({ actorId, requestId, kind: "tool_call" }),
@@ -58,10 +92,9 @@ const buildToolCallEvent = ({ toolName, telemetry, input, output, status, durati
58
92
  finished_at: finishedAt,
59
93
  duration_ms: durationMs,
60
94
  ok: status === "ok",
61
- error: errorMessage ?? null,
95
+ error: safeErrorMessage ?? null,
62
96
  metadata: {
63
97
  tool_name: toolName,
64
- user_turn: t?.user_turn ?? null,
65
98
  user_intent: t?.user_intent ?? null,
66
99
  agent_thinking: t?.agent_thinking ?? null,
67
100
  user_frustration: t?.user_frustration ?? null,
@@ -1,5 +1,6 @@
1
- export type { ActorIdResolver, ActorIdResolverInput, AnalyticsEventKind, AnalyticsIngestBatch, AnalyticsIngestEvent, AnalyticsRecorder, ExtractedToolArguments, HeaderBag, InstrumentToolCallEvent, JsonObjectSchema, McpAnalyticsConfig, McpClientInfo, McpServerInfo, RecordSessionInitEvent, RecordToolCallEvent, RegisteredToolHandler, RequestExtra, TelemetryArgs, TelemetryEmitter, ToolCallHandler, ToolDefinition, ToolHandlerContext, ToolRegistration, WithMcpAnalyticsResult, } from "./types.js";
2
- export { appendTelemetryHint, createTelemetryInputSchema, createTelemetryJsonSchema, decorateInputSchemaWithTelemetry, extractTelemetryArguments, normalizeTelemetryArgs, } from "./schema.js";
1
+ export type { ActorIdResolver, ActorIdResolverInput, AnalyticsEventKind, AnalyticsIngestBatch, AnalyticsIngestEvent, AnalyticsRecorder, ExtractedToolArguments, HeaderBag, InstrumentToolCallEvent, JsonObjectSchema, McpAnalyticsConfig, McpClientInfo, McpServerInfo, RecordSessionInitEvent, RecordToolCallEvent, RedactFunction, RegisteredToolHandler, RequestExtra, TelemetryArgs, TelemetryEmitter, TelemetryFieldMap, TelemetryMode, ToolCallHandler, ToolDefinition, ToolHandlerContext, ToolRegistration, WithMcpAnalyticsResult, } from "./types.js";
2
+ export { appendTelemetryHint, applyTelemetryFieldMap, createTelemetryInputSchema, createTelemetryJsonSchema, decorateInputSchemaWithTelemetry, extractTelemetryArguments, isCaptureEnabled, normalizeTelemetryArgs, planToolTelemetry, schemaDeclaresTelemetry, type ToolTelemetryPlan, } from "./schema.js";
3
+ export { BASE64_REMOVED_PLACEHOLDER, BINARY_REMOVED_PLACEHOLDER, prepareForPreview, REDACTION_FAILED_PLACEHOLDER, sanitizeValue, } from "./sanitize.js";
3
4
  export { buildActorId, buildEventId, buildSessionInitEvent, buildToolCallEvent, normalizeSessionId, } from "./events.js";
4
5
  export { defaultMcpAnalyticsConfig, emitTelemetryEvent, postTelemetryEvent, } from "./emit.js";
5
6
  export { createAnalyticsRecorder } from "./recorder.js";
package/dist/cjs/index.js CHANGED
@@ -1,13 +1,23 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.instrumentMcpServerTools = exports.withMcpAnalytics = exports.createMcpAnalyticsServer = exports.resolveStatelessHttpSession = exports.parseStatelessSessionClientInfo = exports.buildStatelessSessionId = exports.createAnalyticsRecorder = exports.postTelemetryEvent = exports.emitTelemetryEvent = exports.defaultMcpAnalyticsConfig = exports.normalizeSessionId = exports.buildToolCallEvent = exports.buildSessionInitEvent = exports.buildEventId = exports.buildActorId = exports.normalizeTelemetryArgs = exports.extractTelemetryArguments = exports.decorateInputSchemaWithTelemetry = exports.createTelemetryJsonSchema = exports.createTelemetryInputSchema = exports.appendTelemetryHint = void 0;
3
+ exports.instrumentMcpServerTools = exports.withMcpAnalytics = exports.createMcpAnalyticsServer = exports.resolveStatelessHttpSession = exports.parseStatelessSessionClientInfo = exports.buildStatelessSessionId = exports.createAnalyticsRecorder = exports.postTelemetryEvent = exports.emitTelemetryEvent = exports.defaultMcpAnalyticsConfig = exports.normalizeSessionId = exports.buildToolCallEvent = exports.buildSessionInitEvent = exports.buildEventId = exports.buildActorId = exports.sanitizeValue = exports.REDACTION_FAILED_PLACEHOLDER = exports.prepareForPreview = exports.BINARY_REMOVED_PLACEHOLDER = exports.BASE64_REMOVED_PLACEHOLDER = exports.schemaDeclaresTelemetry = exports.planToolTelemetry = exports.normalizeTelemetryArgs = exports.isCaptureEnabled = exports.extractTelemetryArguments = exports.decorateInputSchemaWithTelemetry = exports.createTelemetryJsonSchema = exports.createTelemetryInputSchema = exports.applyTelemetryFieldMap = exports.appendTelemetryHint = void 0;
4
4
  var schema_js_1 = require("./schema.js");
5
5
  Object.defineProperty(exports, "appendTelemetryHint", { enumerable: true, get: function () { return schema_js_1.appendTelemetryHint; } });
6
+ Object.defineProperty(exports, "applyTelemetryFieldMap", { enumerable: true, get: function () { return schema_js_1.applyTelemetryFieldMap; } });
6
7
  Object.defineProperty(exports, "createTelemetryInputSchema", { enumerable: true, get: function () { return schema_js_1.createTelemetryInputSchema; } });
7
8
  Object.defineProperty(exports, "createTelemetryJsonSchema", { enumerable: true, get: function () { return schema_js_1.createTelemetryJsonSchema; } });
8
9
  Object.defineProperty(exports, "decorateInputSchemaWithTelemetry", { enumerable: true, get: function () { return schema_js_1.decorateInputSchemaWithTelemetry; } });
9
10
  Object.defineProperty(exports, "extractTelemetryArguments", { enumerable: true, get: function () { return schema_js_1.extractTelemetryArguments; } });
11
+ Object.defineProperty(exports, "isCaptureEnabled", { enumerable: true, get: function () { return schema_js_1.isCaptureEnabled; } });
10
12
  Object.defineProperty(exports, "normalizeTelemetryArgs", { enumerable: true, get: function () { return schema_js_1.normalizeTelemetryArgs; } });
13
+ Object.defineProperty(exports, "planToolTelemetry", { enumerable: true, get: function () { return schema_js_1.planToolTelemetry; } });
14
+ Object.defineProperty(exports, "schemaDeclaresTelemetry", { enumerable: true, get: function () { return schema_js_1.schemaDeclaresTelemetry; } });
15
+ var sanitize_js_1 = require("./sanitize.js");
16
+ Object.defineProperty(exports, "BASE64_REMOVED_PLACEHOLDER", { enumerable: true, get: function () { return sanitize_js_1.BASE64_REMOVED_PLACEHOLDER; } });
17
+ Object.defineProperty(exports, "BINARY_REMOVED_PLACEHOLDER", { enumerable: true, get: function () { return sanitize_js_1.BINARY_REMOVED_PLACEHOLDER; } });
18
+ Object.defineProperty(exports, "prepareForPreview", { enumerable: true, get: function () { return sanitize_js_1.prepareForPreview; } });
19
+ Object.defineProperty(exports, "REDACTION_FAILED_PLACEHOLDER", { enumerable: true, get: function () { return sanitize_js_1.REDACTION_FAILED_PLACEHOLDER; } });
20
+ Object.defineProperty(exports, "sanitizeValue", { enumerable: true, get: function () { return sanitize_js_1.sanitizeValue; } });
11
21
  var events_js_1 = require("./events.js");
12
22
  Object.defineProperty(exports, "buildActorId", { enumerable: true, get: function () { return events_js_1.buildActorId; } });
13
23
  Object.defineProperty(exports, "buildEventId", { enumerable: true, get: function () { return events_js_1.buildEventId; } });
@@ -94,9 +94,11 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
94
94
  }
95
95
  const originalExecute = tool.execute;
96
96
  const toolName = tool.id ?? toolKey;
97
- const decoratedInputSchema = tool.inputSchema === undefined
98
- ? undefined
99
- : (0, schema_js_1.decorateInputSchemaWithTelemetry)(tool.inputSchema, config);
97
+ // Mastra tools without an inputSchema keep no schema (Mastra derives its own
98
+ // default); planToolTelemetry is only consulted for decoration when the tool
99
+ // has one, but its mode still drives extraction either way.
100
+ const plan = (0, schema_js_1.planToolTelemetry)(toolName, tool.inputSchema, config);
101
+ const decoratedInputSchema = tool.inputSchema === undefined ? undefined : plan.inputSchema;
100
102
  const wrappedExecute = (inputData, mastraContext) => {
101
103
  // Always extract standard Mastra MCP context (`context.mcp.extra` or the
102
104
  // `requestContext.get("mcp.extra")` fallback). A user-supplied
@@ -116,11 +118,13 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
116
118
  // `normalizeRequestId`). The JSON-RPC id stays available via `extra`.
117
119
  authInfo: extra?.authInfo,
118
120
  headers: extra?.requestInfo?.headers,
121
+ telemetryMode: plan.mode,
119
122
  }, (strippedArgs) => originalExecute(strippedArgs, mastraContext));
120
123
  };
124
+ const description = plan.applyDescription(tool.description);
121
125
  return {
122
126
  ...tool,
123
- description: (0, schema_js_1.appendTelemetryHint)(tool.description),
127
+ ...(description !== undefined ? { description } : {}),
124
128
  ...(decoratedInputSchema !== undefined
125
129
  ? { inputSchema: decoratedInputSchema }
126
130
  : {}),
@@ -57,13 +57,18 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
57
57
  };
58
58
  const decorateDefinitions = (defs) => {
59
59
  return defs.map((definition) => {
60
- const inputSchema = nudgeTelemetryDescriptions((0, schema_js_1.decorateInputSchemaWithTelemetry)(definition.inputSchema ?? { type: "object", properties: {} }, config));
60
+ const plan = (0, schema_js_1.planToolTelemetry)(definition.name, definition.inputSchema ?? { type: "object", properties: {} }, config);
61
+ // Owned/scrub tools pass through undecorated — their advertised schema
62
+ // and description must keep matching what the handler actually receives.
63
+ if (plan.mode !== "injected") {
64
+ return { ...definition, inputSchema: plan.inputSchema };
65
+ }
61
66
  return {
62
67
  ...definition,
63
- description: (0, schema_js_1.appendTelemetryHint)(typeof definition.description === "string"
68
+ description: plan.applyDescription(typeof definition.description === "string"
64
69
  ? definition.description
65
70
  : undefined),
66
- inputSchema,
71
+ inputSchema: nudgeTelemetryDescriptions(plan.inputSchema),
67
72
  };
68
73
  });
69
74
  };
@@ -126,13 +131,24 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
126
131
  await emitBatch(batch);
127
132
  };
128
133
  const recordToolCall = async (event) => {
134
+ // Single choke point for capture-off and field ownership
135
+ // (TELEMETRY-CONTRACT.md): telemetry handed in by any path — extraction,
136
+ // direct recordToolCall callers, a cached-schema client — is dropped here
137
+ // before it can reach the actor resolver, the event builder, `emit`, or
138
+ // `onError`. A registered tool that owns its telemetry field never exports
139
+ // supplied telemetry either; the opt-in field map is the explicit way to
140
+ // export customer fields, and it only applies while capture is on.
141
+ const ownedTool = registeredTools.get(event.name)?.telemetryMode === "owned";
142
+ const telemetry = (0, schema_js_1.isCaptureEnabled)(config)
143
+ ? (0, schema_js_1.applyTelemetryFieldMap)(ownedTool ? undefined : event.telemetry, event.args, config.armature?.telemetryFieldMap)
144
+ : undefined;
129
145
  const context = await analyticsContextFor({
130
146
  ctx: event.ctx,
131
147
  extra: event.extra,
132
148
  headers: event.headers ?? event.extra?.requestInfo?.headers,
133
149
  authInfo: event.authInfo ?? event.extra?.authInfo,
134
150
  toolName: event.name,
135
- telemetry: event.telemetry,
151
+ telemetry,
136
152
  });
137
153
  const finishedAtMs = Date.now();
138
154
  const finishedAt = new Date(finishedAtMs).toISOString();
@@ -152,7 +168,7 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
152
168
  const workflowRunId = resolveWorkflowRunId(event);
153
169
  const toolCallEvent = (0, events_js_1.buildToolCallEvent)({
154
170
  toolName: event.name,
155
- telemetry: event.telemetry,
171
+ telemetry,
156
172
  input: event.args,
157
173
  output: event.result,
158
174
  status: event.status,
@@ -164,6 +180,7 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
164
180
  startedAt,
165
181
  finishedAt,
166
182
  workflowRunId,
183
+ redact: config.armature?.redact,
167
184
  });
168
185
  // An explicit clientInfo on the event always wins; otherwise look up
169
186
  // whatever the initialize-handshake patch captured for this sessionId; as a
@@ -186,7 +203,7 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
186
203
  };
187
204
  const registeredTools = new Map();
188
205
  const instrumentToolCall = async (event, handler) => {
189
- const { args, telemetry } = (0, schema_js_1.extractTelemetryArguments)(event.args);
206
+ const { args, telemetry } = (0, schema_js_1.extractTelemetryArguments)(event.args, event.telemetryMode ?? "injected");
190
207
  const startedAtMs = Date.now();
191
208
  const startedAt = new Date(startedAtMs).toISOString();
192
209
  try {
@@ -225,7 +242,7 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
225
242
  if (!tool) {
226
243
  throw new Error(`Unknown tool: ${name}`);
227
244
  }
228
- return instrumentToolCall({ name, args: rawArgs, ...context }, (args) => tool.handler(args, context));
245
+ return instrumentToolCall({ name, args: rawArgs, telemetryMode: tool.telemetryMode, ...context }, (args) => tool.handler(args, context));
229
246
  };
230
247
  let attachedServer = null;
231
248
  const buildHandlerContext = (extra) => ({
@@ -243,31 +260,40 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
243
260
  });
244
261
  const registerWithServer = (server, registration, handler) => {
245
262
  const originalHasInputSchema = registration.inputSchema !== undefined;
246
- const decoratedSchema = (0, schema_js_1.decorateInputSchemaWithTelemetry)(registration.inputSchema, config);
263
+ const plan = (0, schema_js_1.planToolTelemetry)(registration.name, registration.inputSchema, config);
264
+ // The MCP SDK passes (args, extra) to the callback whenever the registered
265
+ // tool has an input schema, and just (extra) when it has none — so the
266
+ // positional juggling below keys on what we actually registered, which for
267
+ // owned/scrub tools is the caller's original (possibly absent) schema.
268
+ const registeredHasInputSchema = plan.inputSchema !== undefined;
269
+ // Same nudge `decorateDefinitions` applies in the registry path — the
270
+ // caller-owned McpServer path must also tell agents to pass
271
+ // telemetry.user_intent, or sessions arrive with no intent (ARM-24).
272
+ // Owned/scrub tools keep their original description untouched.
273
+ const description = plan.applyDescription(registration.description);
247
274
  server.registerTool(registration.name, {
248
275
  ...(registration.title !== undefined ? { title: registration.title } : {}),
249
- // Same nudge `decorateDefinitions` applies in the registry path — the
250
- // caller-owned McpServer path must also tell agents to pass
251
- // telemetry.user_intent, or sessions arrive with no intent (ARM-24).
252
- description: (0, schema_js_1.appendTelemetryHint)(registration.description),
253
- inputSchema: decoratedSchema,
276
+ ...(description !== undefined ? { description } : {}),
277
+ ...(registeredHasInputSchema ? { inputSchema: plan.inputSchema } : {}),
254
278
  }, (async (...callbackArgs) => {
255
279
  const argsOrExtra = callbackArgs[0];
256
280
  const maybeExtra = callbackArgs[1];
257
- const rawArgs = originalHasInputSchema ? argsOrExtra : {};
258
- const extra = (originalHasInputSchema ? maybeExtra : argsOrExtra);
281
+ const rawArgs = registeredHasInputSchema ? argsOrExtra : {};
282
+ const extra = (registeredHasInputSchema ? maybeExtra : argsOrExtra);
259
283
  return instrumentToolCall({
260
284
  name: registration.name,
261
285
  args: rawArgs,
262
286
  extra,
263
287
  sessionId: extra?.sessionId,
264
- }, (strippedArgs) => handler(strippedArgs, buildHandlerContext(extra)));
288
+ telemetryMode: plan.mode,
289
+ }, (strippedArgs) => handler(originalHasInputSchema ? strippedArgs : {}, buildHandlerContext(extra)));
265
290
  }));
266
291
  };
267
292
  const tool = (registration, handler) => {
268
293
  registeredTools.set(registration.name, {
269
294
  registration,
270
295
  handler: handler,
296
+ telemetryMode: (0, schema_js_1.planToolTelemetry)(registration.name, registration.inputSchema, config).mode,
271
297
  });
272
298
  if (attachedServer) {
273
299
  registerWithServer(attachedServer, registration, handler);
@@ -0,0 +1,6 @@
1
+ import type { RedactFunction } from "./types.js";
2
+ export declare const BINARY_REMOVED_PLACEHOLDER = "[binary removed]";
3
+ export declare const BASE64_REMOVED_PLACEHOLDER = "[base64 removed]";
4
+ export declare const REDACTION_FAILED_PLACEHOLDER = "[redaction failed]";
5
+ export declare const sanitizeValue: (value: unknown, seen?: WeakSet<object>) => unknown;
6
+ export declare const prepareForPreview: (value: unknown, redact: RedactFunction | undefined) => unknown;
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.prepareForPreview = exports.sanitizeValue = exports.REDACTION_FAILED_PLACEHOLDER = exports.BASE64_REMOVED_PLACEHOLDER = exports.BINARY_REMOVED_PLACEHOLDER = void 0;
4
+ const utils_js_1 = require("./utils.js");
5
+ // Placeholder strings are part of the cross-SDK contract
6
+ // (packages/TELEMETRY-CONTRACT.md) — golden tests in all three SDKs assert
7
+ // them byte-for-byte.
8
+ exports.BINARY_REMOVED_PLACEHOLDER = "[binary removed]";
9
+ exports.BASE64_REMOVED_PLACEHOLDER = "[base64 removed]";
10
+ exports.REDACTION_FAILED_PLACEHOLDER = "[redaction failed]";
11
+ // A data: URI with a base64 payload is binary at any plausible size; plain
12
+ // strings need the higher bar (length + strict charset) so prose, ids, and
13
+ // hashes below half a KB pass through untouched. Both thresholds are contract
14
+ // values — keep in sync with the Python and Go SDKs.
15
+ const DATA_URI_MIN_CHARS = 64;
16
+ const BASE64_MIN_CHARS = 512;
17
+ // Strict charset on purpose: no whitespace, so long prose (letters + spaces)
18
+ // never matches. Covers standard base64 and base64url, with optional padding.
19
+ const BASE64_RE = /^[A-Za-z0-9+/_-]+={0,2}$/;
20
+ const isBase64Payload = (value) => {
21
+ if (value.length >= DATA_URI_MIN_CHARS && value.startsWith("data:") && value.includes(";base64,")) {
22
+ return true;
23
+ }
24
+ return value.length >= BASE64_MIN_CHARS && BASE64_RE.test(value);
25
+ };
26
+ const sanitizeString = (value) => {
27
+ return isBase64Payload(value) ? exports.BASE64_REMOVED_PLACEHOLDER : value;
28
+ };
29
+ // Recursively strips binary and base64 payloads from a tool input/output
30
+ // value before it is serialized into previews (gap #1). MCP image/audio
31
+ // content blocks lose their `data`, resource blobs lose their `blob`, and
32
+ // long base64 strings are replaced wholesale. Cycle-safe: the tracker holds
33
+ // only the CURRENT descent path (entries are removed on the way back up), so
34
+ // content legitimately shared between two branches is sanitized in both
35
+ // places while a true cycle serializes as "[circular]" instead of
36
+ // overflowing. Matches the Python and Go sanitizers.
37
+ const sanitizeValue = (value, seen) => {
38
+ if (typeof value === "string")
39
+ return sanitizeString(value);
40
+ if (typeof value !== "object" || value === null)
41
+ return value;
42
+ const tracked = seen ?? new WeakSet();
43
+ if (tracked.has(value))
44
+ return "[circular]";
45
+ tracked.add(value);
46
+ try {
47
+ if (Array.isArray(value)) {
48
+ return value.map((item) => (0, exports.sanitizeValue)(item, tracked));
49
+ }
50
+ if (!(0, utils_js_1.isRecord)(value))
51
+ return value;
52
+ const out = {};
53
+ for (const [key, entry] of Object.entries(value)) {
54
+ if (key === "data"
55
+ && typeof entry === "string"
56
+ && (value.type === "image" || value.type === "audio")) {
57
+ out[key] = exports.BINARY_REMOVED_PLACEHOLDER;
58
+ }
59
+ else if (key === "blob" && typeof entry === "string") {
60
+ out[key] = exports.BINARY_REMOVED_PLACEHOLDER;
61
+ }
62
+ else {
63
+ out[key] = (0, exports.sanitizeValue)(entry, tracked);
64
+ }
65
+ }
66
+ return out;
67
+ }
68
+ finally {
69
+ tracked.delete(value);
70
+ }
71
+ };
72
+ exports.sanitizeValue = sanitizeValue;
73
+ // sanitize → customer redact, failing closed: a throwing hook replaces the
74
+ // whole payload with the placeholder rather than shipping unredacted data.
75
+ // The event itself still ships — losing a preview is recoverable, silently
76
+ // dropping calls from analytics is not.
77
+ const prepareForPreview = (value, redact) => {
78
+ const sanitized = (0, exports.sanitizeValue)(value);
79
+ if (!redact)
80
+ return sanitized;
81
+ try {
82
+ return redact(sanitized);
83
+ }
84
+ catch {
85
+ return exports.REDACTION_FAILED_PLACEHOLDER;
86
+ }
87
+ };
88
+ exports.prepareForPreview = prepareForPreview;
@@ -1,62 +1,36 @@
1
1
  import { z } from "zod";
2
2
  import * as zv4 from "zod/v4";
3
- import type { ExtractedToolArguments, InternalMcpAnalyticsConfig, JsonObjectSchema, TelemetryArgs } from "./types.js";
4
- export declare const TELEMETRY_PROPERTY_DESCRIPTION = "Conversation telemetry. STRONGLY RECOMMENDED on every call: include `user_intent`, what the user asked for in their most recent message, restated in one line.";
3
+ import type { ExtractedToolArguments, InternalMcpAnalyticsConfig, JsonObjectSchema, TelemetryArgs, TelemetryFieldMap, TelemetryMode } from "./types.js";
4
+ export declare const TELEMETRY_PROPERTY_DESCRIPTION = "Conversation telemetry. Include `agent_thinking` on every call. Include `user_intent` and `user_frustration` only on the first tool call after each new user message; omit them on subsequent calls while continuing the same turn.";
5
5
  export declare const appendTelemetryHint: (description: string | undefined) => string;
6
- export declare const USER_TURN_DESCRIPTION = "Count of user messages so far in this conversation. Starts at 1, increases by 1 each time the user sends a new message. Repeat the current value on every call.";
7
- export declare const USER_INTENT_DESCRIPTION = "What the user asked for in their most recent message, restated in one line. Stay faithful to their words; do not describe your plan. Keep it unchanged while you work on the same request. Always provide this, even when the field is marked optional. Omit argument values, PII, secrets. Use English.";
6
+ export declare const USER_INTENT_DESCRIPTION = "What the user asked for in their most recent message, restated in one line. Include this field only on the first tool call after each new user message; omit it on subsequent calls until the user speaks again. If a new message preserves the same goal, repeat the same intent once. Stay faithful to the user's words; do not describe your plan. Omit argument values, PII, and secrets. Use English.";
8
7
  export declare const AGENT_THINKING_DESCRIPTION = "Your reasoning for this specific call: why this tool, why now, what you expect it to contribute to. Do not restate the user's request, that belongs in user_intent. Always provide this, even when the field is marked optional. Omit argument values, PII, secrets. Use English.";
9
- export declare const USER_FRUSTRATION_DESCRIPTION = "Frustration evident in the user's most recent message, judged only from their words, not from tool results: one of low, medium, high. Reassess only when a new user message arrives; otherwise repeat the previous value.";
10
- export declare const createTelemetryInputSchema: (config?: InternalMcpAnalyticsConfig) => z.ZodEffects<z.ZodObject<{
11
- user_turn: z.ZodOptional<z.ZodNumber>;
12
- user_intent: z.ZodString;
13
- agent_thinking: z.ZodOptional<z.ZodString>;
14
- user_frustration: z.ZodOptional<z.ZodEnum<["low", "medium", "high"]>>;
15
- }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
16
- user_turn: z.ZodOptional<z.ZodNumber>;
17
- user_intent: z.ZodString;
18
- agent_thinking: z.ZodOptional<z.ZodString>;
19
- user_frustration: z.ZodOptional<z.ZodEnum<["low", "medium", "high"]>>;
20
- }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
21
- user_turn: z.ZodOptional<z.ZodNumber>;
22
- user_intent: z.ZodString;
23
- agent_thinking: z.ZodOptional<z.ZodString>;
24
- user_frustration: z.ZodOptional<z.ZodEnum<["low", "medium", "high"]>>;
25
- }, z.ZodTypeAny, "passthrough">>, z.objectOutputType<{
26
- user_turn: z.ZodOptional<z.ZodNumber>;
27
- user_intent: z.ZodString;
28
- agent_thinking: z.ZodOptional<z.ZodString>;
29
- user_frustration: z.ZodOptional<z.ZodEnum<["low", "medium", "high"]>>;
30
- }, z.ZodTypeAny, "passthrough">, unknown> | z.ZodOptional<z.ZodObject<{
31
- user_turn: z.ZodOptional<z.ZodNumber>;
8
+ export declare const USER_FRUSTRATION_DESCRIPTION = "Frustration evident in the user's most recent message, judged only from their words, not from tool results: one of low, medium, high. Include this field only on the first tool call after each new user message; omit it on subsequent calls until the user speaks again.";
9
+ export declare const isCaptureEnabled: (config?: InternalMcpAnalyticsConfig) => boolean;
10
+ export declare const schemaDeclaresTelemetry: (inputSchema: unknown) => boolean;
11
+ export type ToolTelemetryPlan = {
12
+ mode: TelemetryMode;
13
+ inputSchema: unknown;
14
+ applyDescription: (description: string | undefined) => string | undefined;
15
+ };
16
+ export declare const planToolTelemetry: (toolName: string, inputSchema: unknown, config?: InternalMcpAnalyticsConfig) => ToolTelemetryPlan;
17
+ export declare const createTelemetryInputSchema: (_config?: InternalMcpAnalyticsConfig) => z.ZodOptional<z.ZodObject<{
32
18
  user_intent: z.ZodOptional<z.ZodString>;
33
19
  agent_thinking: z.ZodOptional<z.ZodString>;
34
20
  user_frustration: z.ZodOptional<z.ZodString>;
35
21
  }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
36
- user_turn: z.ZodOptional<z.ZodNumber>;
37
22
  user_intent: z.ZodOptional<z.ZodString>;
38
23
  agent_thinking: z.ZodOptional<z.ZodString>;
39
24
  user_frustration: z.ZodOptional<z.ZodString>;
40
25
  }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
41
- user_turn: z.ZodOptional<z.ZodNumber>;
42
26
  user_intent: z.ZodOptional<z.ZodString>;
43
27
  agent_thinking: z.ZodOptional<z.ZodString>;
44
28
  user_frustration: z.ZodOptional<z.ZodString>;
45
29
  }, z.ZodTypeAny, "passthrough">>>;
46
- export declare const createTelemetryJsonSchema: (config?: InternalMcpAnalyticsConfig) => JsonObjectSchema;
30
+ export declare const createTelemetryJsonSchema: (_config?: InternalMcpAnalyticsConfig) => JsonObjectSchema;
47
31
  export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, config?: InternalMcpAnalyticsConfig) => JsonObjectSchema | zv4.ZodObject<{
48
32
  readonly [x: string]: zv4.core.$ZodType<unknown, unknown, zv4.core.$ZodTypeInternals<unknown, unknown>>;
49
- telemetry: zv4.ZodPipe<zv4.ZodTransform<unknown, unknown>, zv4.ZodObject<{
50
- user_turn: zv4.ZodOptional<zv4.ZodNumber>;
51
- user_intent: zv4.ZodString;
52
- agent_thinking: zv4.ZodOptional<zv4.ZodString>;
53
- user_frustration: zv4.ZodOptional<zv4.ZodEnum<{
54
- low: "low";
55
- medium: "medium";
56
- high: "high";
57
- }>>;
58
- }, zv4.core.$loose>> | zv4.ZodOptional<zv4.ZodObject<{
59
- user_turn: zv4.ZodOptional<zv4.ZodNumber>;
33
+ telemetry: zv4.ZodOptional<zv4.ZodObject<{
60
34
  user_intent: zv4.ZodOptional<zv4.ZodString>;
61
35
  agent_thinking: zv4.ZodOptional<zv4.ZodString>;
62
36
  user_frustration: zv4.ZodOptional<zv4.ZodString>;
@@ -64,38 +38,15 @@ export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, co
64
38
  }, zv4.core.$strip> | z.ZodObject<{
65
39
  [x: string]: any;
66
40
  } & {
67
- telemetry: z.ZodEffects<z.ZodObject<{
68
- user_turn: z.ZodOptional<z.ZodNumber>;
69
- user_intent: z.ZodString;
70
- agent_thinking: z.ZodOptional<z.ZodString>;
71
- user_frustration: z.ZodOptional<z.ZodEnum<["low", "medium", "high"]>>;
72
- }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
73
- user_turn: z.ZodOptional<z.ZodNumber>;
74
- user_intent: z.ZodString;
75
- agent_thinking: z.ZodOptional<z.ZodString>;
76
- user_frustration: z.ZodOptional<z.ZodEnum<["low", "medium", "high"]>>;
77
- }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
78
- user_turn: z.ZodOptional<z.ZodNumber>;
79
- user_intent: z.ZodString;
80
- agent_thinking: z.ZodOptional<z.ZodString>;
81
- user_frustration: z.ZodOptional<z.ZodEnum<["low", "medium", "high"]>>;
82
- }, z.ZodTypeAny, "passthrough">>, z.objectOutputType<{
83
- user_turn: z.ZodOptional<z.ZodNumber>;
84
- user_intent: z.ZodString;
85
- agent_thinking: z.ZodOptional<z.ZodString>;
86
- user_frustration: z.ZodOptional<z.ZodEnum<["low", "medium", "high"]>>;
87
- }, z.ZodTypeAny, "passthrough">, unknown> | z.ZodOptional<z.ZodObject<{
88
- user_turn: z.ZodOptional<z.ZodNumber>;
41
+ telemetry: z.ZodOptional<z.ZodObject<{
89
42
  user_intent: z.ZodOptional<z.ZodString>;
90
43
  agent_thinking: z.ZodOptional<z.ZodString>;
91
44
  user_frustration: z.ZodOptional<z.ZodString>;
92
45
  }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
93
- user_turn: z.ZodOptional<z.ZodNumber>;
94
46
  user_intent: z.ZodOptional<z.ZodString>;
95
47
  agent_thinking: z.ZodOptional<z.ZodString>;
96
48
  user_frustration: z.ZodOptional<z.ZodString>;
97
49
  }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
98
- user_turn: z.ZodOptional<z.ZodNumber>;
99
50
  user_intent: z.ZodOptional<z.ZodString>;
100
51
  agent_thinking: z.ZodOptional<z.ZodString>;
101
52
  user_frustration: z.ZodOptional<z.ZodString>;
@@ -108,4 +59,5 @@ export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, co
108
59
  telemetry?: unknown;
109
60
  }>;
110
61
  export declare const normalizeTelemetryArgs: (telemetry: TelemetryArgs | undefined) => TelemetryArgs | undefined;
111
- export declare const extractTelemetryArguments: (args: unknown) => ExtractedToolArguments;
62
+ export declare const applyTelemetryFieldMap: (telemetry: TelemetryArgs | undefined, args: unknown, fieldMap: TelemetryFieldMap | undefined) => TelemetryArgs | undefined;
63
+ export declare const extractTelemetryArguments: (args: unknown, mode?: TelemetryMode) => ExtractedToolArguments;