@armature-tech/mcp-analytics 0.6.16 → 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.
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.extractTelemetryArguments = exports.normalizeTelemetryArgs = exports.decorateInputSchemaWithTelemetry = exports.createTelemetryJsonSchema = exports.createTelemetryInputSchema = exports.USER_FRUSTRATION_DESCRIPTION = exports.AGENT_THINKING_DESCRIPTION = exports.USER_INTENT_DESCRIPTION = exports.USER_TURN_DESCRIPTION = exports.appendTelemetryHint = exports.TELEMETRY_PROPERTY_DESCRIPTION = void 0;
36
+ exports.extractTelemetryArguments = exports.applyTelemetryFieldMap = exports.normalizeTelemetryArgs = exports.decorateInputSchemaWithTelemetry = exports.createTelemetryJsonSchema = exports.createTelemetryInputSchema = exports.planToolTelemetry = exports.schemaDeclaresTelemetry = exports.isCaptureEnabled = exports.USER_FRUSTRATION_DESCRIPTION = exports.AGENT_THINKING_DESCRIPTION = exports.USER_INTENT_DESCRIPTION = exports.appendTelemetryHint = 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");
@@ -41,13 +41,13 @@ const utils_js_1 = require("./utils.js");
41
41
  // Python SDK (packages/mcp-analytics-python/src/armature_mcp_analytics/schema.py)
42
42
  // must carry byte-identical copies so agents see the same tool statements
43
43
  // regardless of the server's implementation language.
44
- exports.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.";
45
- const TELEMETRY_DESCRIPTION_HINT = "\n\nPass telemetry.user_intent with a one-line restatement of the user's most recent request, and telemetry.agent_thinking with your reasoning for making this specific call.";
44
+ exports.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.";
45
+ const TELEMETRY_DESCRIPTION_HINT = "\n\nOn every call, pass telemetry.agent_thinking with your reasoning for this specific call. Pass telemetry.user_intent only on the first tool call after a new user message.";
46
46
  const TELEMETRY_DESCRIPTION_HINT_MARKER = TELEMETRY_DESCRIPTION_HINT.trim();
47
- // Earlier-V1 hint (user_intent only, before agent_thinking was added) and the
48
- // pre-V1 `intent` hint, both recognized (never emitted) so a description that
49
- // reached us through an older wrapper doesn't accumulate a second,
50
- // mixed-generation nudge. Same markers in the Python and Go SDKs.
47
+ // Older hints are recognized (never emitted) so a description that reached us
48
+ // through an earlier wrapper doesn't accumulate a second, mixed-generation
49
+ // nudge. Same markers in the Python and Go SDKs.
50
+ const TELEMETRY_DESCRIPTION_HINT_REPEAT_INTENT_MARKER = "Pass telemetry.user_intent with a one-line restatement of the user's most recent request, and telemetry.agent_thinking with your reasoning for making this specific call.";
51
51
  const TELEMETRY_DESCRIPTION_HINT_V1_MARKER = "Pass telemetry.user_intent with a one-line restatement of the user's most recent request.";
52
52
  const TELEMETRY_DESCRIPTION_HINT_LEGACY_MARKER = "Pass telemetry.intent with a one-line user intent for analytics.";
53
53
  // Appends the telemetry.user_intent nudge to a tool description (idempotently —
@@ -59,6 +59,7 @@ const appendTelemetryHint = (description) => {
59
59
  return TELEMETRY_DESCRIPTION_HINT.trimStart();
60
60
  }
61
61
  if (description.includes(TELEMETRY_DESCRIPTION_HINT_MARKER)
62
+ || description.includes(TELEMETRY_DESCRIPTION_HINT_REPEAT_INTENT_MARKER)
62
63
  || description.includes(TELEMETRY_DESCRIPTION_HINT_V1_MARKER)
63
64
  || description.includes(TELEMETRY_DESCRIPTION_HINT_LEGACY_MARKER)) {
64
65
  return description;
@@ -66,10 +67,9 @@ const appendTelemetryHint = (description) => {
66
67
  return `${description}${TELEMETRY_DESCRIPTION_HINT}`;
67
68
  };
68
69
  exports.appendTelemetryHint = appendTelemetryHint;
69
- exports.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.";
70
- exports.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.";
70
+ exports.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.";
71
71
  exports.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.";
72
- exports.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.";
72
+ exports.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.";
73
73
  // Each telemetry object schema carries the object-level description via
74
74
  // `.describe(...)` so it survives zod→JSON-schema conversion in every
75
75
  // integration shape — including caller-owned McpServer registration, where no
@@ -80,40 +80,8 @@ exports.USER_FRUSTRATION_DESCRIPTION = "Frustration evident in the user's most r
80
80
  // them here would silently drop its telemetry before normalizeTelemetryArgs
81
81
  // can translate the legacy spelling.
82
82
  //
83
- // Strict mode additionally preprocesses the legacy `intent` spelling onto
84
- // `user_intent` BEFORE the required-field check runs: a cached pre-V1 client
85
- // sends only `intent`, and rejecting its calls at the input boundary would
86
- // turn an SDK upgrade into an outage for that client. The advertised contract
87
- // (user_intent required) is unchanged — preprocess only affects validation.
88
- const acceptLegacyIntent = (value) => {
89
- if ((0, utils_js_1.isRecord)(value)
90
- && typeof value.user_intent !== "string"
91
- && typeof value.intent === "string") {
92
- return { ...value, user_intent: value.intent };
93
- }
94
- return value;
95
- };
96
- const strictTelemetryInputSchema = zod_1.z
97
- .preprocess(acceptLegacyIntent, zod_1.z
98
- .object({
99
- user_turn: zod_1.z.number().int().min(1).describe(exports.USER_TURN_DESCRIPTION).optional(),
100
- user_intent: zod_1.z.string().min(1).describe(exports.USER_INTENT_DESCRIPTION),
101
- agent_thinking: zod_1.z
102
- .string()
103
- .min(1)
104
- .describe(exports.AGENT_THINKING_DESCRIPTION)
105
- .optional(),
106
- user_frustration: zod_1.z
107
- .enum(["low", "medium", "high"])
108
- .describe(exports.USER_FRUSTRATION_DESCRIPTION)
109
- .optional(),
110
- })
111
- .passthrough()
112
- .describe(exports.TELEMETRY_PROPERTY_DESCRIPTION))
113
- .describe(exports.TELEMETRY_PROPERTY_DESCRIPTION);
114
83
  const looseTelemetryInputSchema = zod_1.z
115
84
  .object({
116
- user_turn: zod_1.z.number().describe(exports.USER_TURN_DESCRIPTION).optional(),
117
85
  user_intent: zod_1.z.string().describe(exports.USER_INTENT_DESCRIPTION).optional(),
118
86
  agent_thinking: zod_1.z.string().describe(exports.AGENT_THINKING_DESCRIPTION).optional(),
119
87
  user_frustration: zod_1.z
@@ -123,26 +91,8 @@ const looseTelemetryInputSchema = zod_1.z
123
91
  })
124
92
  .passthrough()
125
93
  .describe(exports.TELEMETRY_PROPERTY_DESCRIPTION);
126
- const strictTelemetryInputSchemaV4 = zv4
127
- .preprocess(acceptLegacyIntent, zv4
128
- .looseObject({
129
- user_turn: zv4.number().int().min(1).describe(exports.USER_TURN_DESCRIPTION).optional(),
130
- user_intent: zv4.string().min(1).describe(exports.USER_INTENT_DESCRIPTION),
131
- agent_thinking: zv4
132
- .string()
133
- .min(1)
134
- .describe(exports.AGENT_THINKING_DESCRIPTION)
135
- .optional(),
136
- user_frustration: zv4
137
- .enum(["low", "medium", "high"])
138
- .describe(exports.USER_FRUSTRATION_DESCRIPTION)
139
- .optional(),
140
- })
141
- .describe(exports.TELEMETRY_PROPERTY_DESCRIPTION))
142
- .describe(exports.TELEMETRY_PROPERTY_DESCRIPTION);
143
94
  const looseTelemetryInputSchemaV4 = zv4
144
95
  .looseObject({
145
- user_turn: zv4.number().describe(exports.USER_TURN_DESCRIPTION).optional(),
146
96
  user_intent: zv4.string().describe(exports.USER_INTENT_DESCRIPTION).optional(),
147
97
  agent_thinking: zv4
148
98
  .string()
@@ -181,59 +131,95 @@ const isZodV3ObjectSchema = (value) => {
181
131
  const rawShapeUsesZodV4 = (shape) => {
182
132
  return Object.values(shape).some((value) => (0, utils_js_1.isRecord)(value) && "_zod" in value);
183
133
  };
184
- // Strict mode is keyed on `user_intent` (V1 name); the pre-V1 `intent` config
185
- // key is still honored so internal callers don't break mid-migration.
186
- const isStrict = (config = {}) => {
187
- return (config.telemetry?.user_intent === "required"
188
- || config.telemetry?.intent === "required");
134
+ const isCaptureEnabled = (config = {}) => {
135
+ return config.armature?.captureTelemetry !== false;
136
+ };
137
+ exports.isCaptureEnabled = isCaptureEnabled;
138
+ // True when the tool's own input schema declares a top-level `telemetry`
139
+ // property — the customer owns that field and the SDK must not inject, strip,
140
+ // or interpret it (see TELEMETRY-CONTRACT.md, mode "owned").
141
+ const schemaDeclaresTelemetry = (inputSchema) => {
142
+ if (inputSchema === undefined)
143
+ return false;
144
+ if (isZodV4ObjectSchema(inputSchema) || isZodV3ObjectSchema(inputSchema)) {
145
+ const shape = inputSchema.shape;
146
+ return (0, utils_js_1.isRecord)(shape) && "telemetry" in shape;
147
+ }
148
+ if ((0, utils_js_1.isJsonObjectSchema)(inputSchema)) {
149
+ return (0, utils_js_1.isRecord)(inputSchema.properties) && "telemetry" in inputSchema.properties;
150
+ }
151
+ if ((0, utils_js_1.isRawShape)(inputSchema)) {
152
+ return "telemetry" in inputSchema;
153
+ }
154
+ return false;
155
+ };
156
+ exports.schemaDeclaresTelemetry = schemaDeclaresTelemetry;
157
+ // One warning per tool name per process: registration re-runs on serverless
158
+ // factory paths, and repeating the warning on every cold start's every tool
159
+ // would drown real logs. Bounded implicitly — tool names are finite.
160
+ const warnedCollisions = new Set();
161
+ const warnTelemetryCollision = (toolName) => {
162
+ if (warnedCollisions.has(toolName))
163
+ return;
164
+ warnedCollisions.add(toolName);
165
+ // eslint-disable-next-line no-console
166
+ console.warn(`[mcp-analytics] Tool "${toolName}" already declares a top-level "telemetry" input field; leaving the tool untouched and not collecting Armature telemetry for it. Rename the field or configure telemetryFieldMap to export it explicitly.`);
167
+ };
168
+ // Resolves how the SDK treats one tool's `telemetry` field, once, at
169
+ // registration time. Every integration surface (recorder registry, McpServer
170
+ // prototype patch, Mastra adapter, custom dispatchers) must register and
171
+ // extract with the same plan, so the advertised schema always matches runtime
172
+ // behavior.
173
+ const planToolTelemetry = (toolName, inputSchema, config = {}) => {
174
+ if ((0, exports.schemaDeclaresTelemetry)(inputSchema)) {
175
+ warnTelemetryCollision(toolName);
176
+ return {
177
+ mode: "owned",
178
+ inputSchema,
179
+ applyDescription: (description) => description,
180
+ };
181
+ }
182
+ if (!(0, exports.isCaptureEnabled)(config)) {
183
+ return {
184
+ mode: "scrub",
185
+ inputSchema,
186
+ applyDescription: (description) => description,
187
+ };
188
+ }
189
+ return {
190
+ mode: "injected",
191
+ inputSchema: (0, exports.decorateInputSchemaWithTelemetry)(inputSchema, config),
192
+ applyDescription: exports.appendTelemetryHint,
193
+ };
189
194
  };
190
- // Loose mode wraps the telemetry object with `.optional()` so callers that omit
191
- // the `telemetry` key entirely still parse. Strict mode keeps the object itself
192
- // required (and `user_intent` required inside).
193
- const createTelemetryInputSchema = (config = {}) => {
194
- return isStrict(config)
195
- ? strictTelemetryInputSchema
196
- : looseTelemetryInputSchema.optional();
195
+ exports.planToolTelemetry = planToolTelemetry;
196
+ // The telemetry object and every field stay optional. In particular,
197
+ // user_intent is intentionally absent after the first call in a user turn.
198
+ const createTelemetryInputSchema = (_config = {}) => {
199
+ return looseTelemetryInputSchema.optional();
197
200
  };
198
201
  exports.createTelemetryInputSchema = createTelemetryInputSchema;
199
- const createTelemetryInputSchemaV4 = (config) => {
200
- return isStrict(config)
201
- ? strictTelemetryInputSchemaV4
202
- : looseTelemetryInputSchemaV4.optional();
202
+ const createTelemetryInputSchemaV4 = (_config) => {
203
+ return looseTelemetryInputSchemaV4.optional();
203
204
  };
204
- const createTelemetryJsonSchema = (config = {}) => {
205
- const strict = isStrict(config);
205
+ const createTelemetryJsonSchema = (_config = {}) => {
206
206
  return {
207
207
  type: "object",
208
208
  description: exports.TELEMETRY_PROPERTY_DESCRIPTION,
209
209
  properties: {
210
- user_turn: {
211
- type: "integer",
212
- ...(strict ? { minimum: 1 } : {}),
213
- description: exports.USER_TURN_DESCRIPTION,
214
- },
215
210
  user_intent: {
216
211
  type: "string",
217
- ...(strict ? { minLength: 1 } : {}),
218
212
  description: exports.USER_INTENT_DESCRIPTION,
219
213
  },
220
214
  agent_thinking: {
221
215
  type: "string",
222
- ...(strict ? { minLength: 1 } : {}),
223
216
  description: exports.AGENT_THINKING_DESCRIPTION,
224
217
  },
225
218
  user_frustration: {
226
219
  type: "string",
227
- ...(strict ? { enum: ["low", "medium", "high"] } : {}),
228
220
  description: exports.USER_FRUSTRATION_DESCRIPTION,
229
221
  },
230
222
  },
231
- // Strict mode: user_intent is the required field, but a cached pre-V1
232
- // client may satisfy the requirement via the legacy `intent` spelling —
233
- // JSON-schema validators enforcing this schema must not reject it.
234
- ...(strict
235
- ? { anyOf: [{ required: ["user_intent"] }, { required: ["intent"] }] }
236
- : {}),
237
223
  };
238
224
  };
239
225
  exports.createTelemetryJsonSchema = createTelemetryJsonSchema;
@@ -241,9 +227,7 @@ const decorateJsonSchemaWithTelemetry = (inputSchema, config) => {
241
227
  const existingRequired = Array.isArray(inputSchema.required)
242
228
  ? inputSchema.required
243
229
  : [];
244
- const required = isStrict(config)
245
- ? Array.from(new Set([...existingRequired, "telemetry"]))
246
- : existingRequired;
230
+ const required = existingRequired;
247
231
  return {
248
232
  ...inputSchema,
249
233
  type: "object",
@@ -293,22 +277,17 @@ const firstString = (...values) => {
293
277
  }
294
278
  return undefined;
295
279
  };
296
- // Canonicalizes telemetry onto the V1 field names. Legacy spellings
280
+ // Canonicalizes telemetry onto the current field names. Legacy spellings
297
281
  // (`intent`/`context`/`frustration_level`) still arrive from clients that
298
282
  // cached a pre-V1 tool schema and from callers passing telemetry directly to
299
- // recordToolCall; they lose to an explicit V1 value when both are present.
283
+ // recordToolCall; they lose to an explicit current value when both are present.
284
+ // `user_turn` from cached V1 schemas is deliberately ignored: presence of
285
+ // user_intent is now the new-message signal, and absence means the call
286
+ // continues the previous turn.
300
287
  const normalizeTelemetryArgs = (telemetry) => {
301
288
  if (telemetry === undefined)
302
289
  return undefined;
303
290
  const normalized = {};
304
- const userTurn = telemetry.user_turn;
305
- // user_turn is a 1-based integer count. Integral floats (2.0 — some JSON
306
- // stacks produce them) are accepted; fractional, zero, or negative values
307
- // are dropped rather than coerced, so a bad turn number never attaches
308
- // calls to a wrong or nonexistent turn. Matches the Python normalizer.
309
- if (typeof userTurn === "number" && Number.isInteger(userTurn) && userTurn >= 1) {
310
- normalized.user_turn = userTurn;
311
- }
312
291
  const userIntent = firstString(telemetry.user_intent, telemetry.intent);
313
292
  if (userIntent !== undefined)
314
293
  normalized.user_intent = userIntent;
@@ -322,11 +301,55 @@ const normalizeTelemetryArgs = (telemetry) => {
322
301
  return normalized;
323
302
  };
324
303
  exports.normalizeTelemetryArgs = normalizeTelemetryArgs;
325
- const extractTelemetryArguments = (args) => {
304
+ // Opt-in export of customer-owned argument fields (gap #11): reads — never
305
+ // strips — the mapped top-level argument properties and fills any telemetry
306
+ // field the call didn't already provide explicitly. Values are validated with
307
+ // the same rules as normalizeTelemetryArgs, so a wrong-typed customer field
308
+ // is ignored rather than exported as garbage.
309
+ const applyTelemetryFieldMap = (telemetry, args, fieldMap) => {
310
+ if (!fieldMap || !(0, utils_js_1.isRecord)(args))
311
+ return telemetry;
312
+ const merged = { ...(telemetry ?? {}) };
313
+ const argString = (key) => {
314
+ if (key === undefined)
315
+ return undefined;
316
+ const value = args[key];
317
+ return typeof value === "string" && value.length > 0 ? value : undefined;
318
+ };
319
+ if (merged.user_intent === undefined && merged.intent === undefined) {
320
+ const value = argString(fieldMap.user_intent);
321
+ if (value !== undefined)
322
+ merged.user_intent = value;
323
+ }
324
+ if (merged.agent_thinking === undefined && merged.context === undefined) {
325
+ const value = argString(fieldMap.agent_thinking);
326
+ if (value !== undefined)
327
+ merged.agent_thinking = value;
328
+ }
329
+ if (merged.user_frustration === undefined
330
+ && merged.frustration_level === undefined
331
+ && fieldMap.user_frustration !== undefined) {
332
+ const value = asFrustration(args[fieldMap.user_frustration]);
333
+ if (value !== undefined)
334
+ merged.user_frustration = value;
335
+ }
336
+ return Object.keys(merged).length > 0 ? merged : telemetry;
337
+ };
338
+ exports.applyTelemetryFieldMap = applyTelemetryFieldMap;
339
+ // Mode semantics (TELEMETRY-CONTRACT.md): "injected" strips and exports;
340
+ // "owned" leaves the customer's arguments untouched and exports nothing;
341
+ // "scrub" strips a cached-schema client's telemetry but exports nothing.
342
+ const extractTelemetryArguments = (args, mode = "injected") => {
343
+ if (mode === "owned") {
344
+ return { args };
345
+ }
326
346
  if (!(0, utils_js_1.isRecord)(args) || !(0, utils_js_1.isRecord)(args.telemetry)) {
327
347
  return { args };
328
348
  }
329
349
  const { telemetry, ...strippedArgs } = args;
350
+ if (mode === "scrub") {
351
+ return { args: strippedArgs };
352
+ }
330
353
  return {
331
354
  args: strippedArgs,
332
355
  telemetry: (0, exports.normalizeTelemetryArgs)(telemetry),
@@ -55,18 +55,23 @@ const parseDeprecatedToolArgs = (rest) => {
55
55
  const callback = args[0];
56
56
  return { description, inputSchema, annotations, callback };
57
57
  };
58
- const wrapCallbackWithAnalytics = (name, cb, originalHasInputSchema, ctx) => {
58
+ const wrapCallbackWithAnalytics = (name, cb,
59
+ // The SDK invokes the wrapped callback according to the schema we REGISTERED
60
+ // (args + extra when present, just extra when absent); the original callback
61
+ // expects arguments according to the schema the CUSTOMER declared. The two
62
+ // differ for schema-less tools in injected mode, so both flags are needed.
63
+ originalHasInputSchema, registeredHasInputSchema, telemetryMode, ctx) => {
59
64
  const { recorder } = ctx;
60
65
  return async (argsOrExtra, maybeExtra) => {
61
66
  const startedAtMs = Date.now();
62
67
  const startedAt = new Date(startedAtMs).toISOString();
63
68
  const requestId = (0, node_crypto_1.randomUUID)();
64
- const extra = (originalHasInputSchema ? maybeExtra : argsOrExtra);
65
- const { args, telemetry } = recorder.extractTelemetry(argsOrExtra);
69
+ const extra = (registeredHasInputSchema ? maybeExtra : argsOrExtra);
70
+ const { args, telemetry } = recorder.extractTelemetry(registeredHasInputSchema ? argsOrExtra : undefined, telemetryMode);
66
71
  try {
67
72
  const output = originalHasInputSchema
68
- ? await cb(args, maybeExtra)
69
- : await cb(maybeExtra ?? argsOrExtra);
73
+ ? await cb(args, extra)
74
+ : await cb(extra);
70
75
  // A returned MCP error result (`isError: true`) is a failed call even
71
76
  // though the callback resolved; record it as an error while returning the
72
77
  // original output to the caller untouched.
@@ -115,12 +120,15 @@ const installPrototypePatchOnce = () => {
115
120
  }
116
121
  const { config } = ctx;
117
122
  const originalHasInputSchema = toolConfig.inputSchema !== undefined;
123
+ const plan = (0, schema_js_1.planToolTelemetry)(name, toolConfig.inputSchema, config);
124
+ const registeredHasInputSchema = plan.inputSchema !== undefined;
125
+ const description = plan.applyDescription(toolConfig.description);
118
126
  const instrumentedConfig = {
119
127
  ...toolConfig,
120
- description: (0, schema_js_1.appendTelemetryHint)(toolConfig.description),
121
- inputSchema: (0, schema_js_1.decorateInputSchemaWithTelemetry)(toolConfig.inputSchema, config),
128
+ ...(description !== undefined ? { description } : {}),
129
+ ...(registeredHasInputSchema ? { inputSchema: plan.inputSchema } : {}),
122
130
  };
123
- const wrappedCallback = wrapCallbackWithAnalytics(name, cb, originalHasInputSchema, ctx);
131
+ const wrappedCallback = wrapCallbackWithAnalytics(name, cb, originalHasInputSchema, registeredHasInputSchema, plan.mode, ctx);
124
132
  return originalRegisterTool.call(this, name, instrumentedConfig, wrappedCallback);
125
133
  };
126
134
  // PRIA and other older codebases still use the deprecated `server.tool(...)`
@@ -1,6 +1,6 @@
1
1
  import type { HeaderBag, McpClientInfo } from "./types.js";
2
2
  /** Mint a session id that carries the client identity from `initialize`. */
3
- export declare const buildStatelessSessionId: (clientInfo?: McpClientInfo) => string;
3
+ export declare const buildStatelessSessionId: (clientInfo?: McpClientInfo, sessionSeed?: string) => string;
4
4
  /** Recover the client identity from an identity-bearing session id. */
5
5
  export declare const parseStatelessSessionClientInfo: (sessionId: string | undefined) => McpClientInfo | undefined;
6
6
  export type StatelessHttpSession = {
@@ -28,6 +28,7 @@ const utils_js_1 = require("./utils.js");
28
28
  // });
29
29
  // await analytics.dispatch(name, args, { ctx, ...session.dispatchContext });
30
30
  const SESSION_ID_RE = /^mcp_([A-Za-z0-9.-]+)_v_([A-Za-z0-9.-]*)_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
31
+ const SESSION_SEED_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
31
32
  const ANONYMOUS_NAME = "unknown";
32
33
  const slugPart = (value, fallback) => {
33
34
  const slug = String(value ?? "")
@@ -40,7 +41,11 @@ const slugPart = (value, fallback) => {
40
41
  /** Mint a session id that carries the client identity from `initialize`. */
41
42
  // Version falls back to an empty segment (`_v__`) so a client that never
42
43
  // reported a version stays distinguishable from one reporting literal "0".
43
- const buildStatelessSessionId = (clientInfo) => `mcp_${slugPart(clientInfo?.name, ANONYMOUS_NAME)}_v_${slugPart(clientInfo?.version, "")}_${(0, node_crypto_1.randomUUID)()}`;
44
+ const buildStatelessSessionId = (clientInfo, sessionSeed) => {
45
+ const seed = String(sessionSeed ?? "").trim();
46
+ const uuid = SESSION_SEED_RE.test(seed) ? seed.toLowerCase() : (0, node_crypto_1.randomUUID)();
47
+ return `mcp_${slugPart(clientInfo?.name, ANONYMOUS_NAME)}_v_${slugPart(clientInfo?.version, "")}_${uuid}`;
48
+ };
44
49
  exports.buildStatelessSessionId = buildStatelessSessionId;
45
50
  /** Recover the client identity from an identity-bearing session id. */
46
51
  const parseStatelessSessionClientInfo = (sessionId) => {
@@ -69,7 +74,8 @@ const clientInfoFromInitialize = (message) => {
69
74
  const resolveStatelessHttpSession = (input) => {
70
75
  const initialize = findInitializeMessage(input.body);
71
76
  if (initialize) {
72
- const sessionId = (0, exports.buildStatelessSessionId)(clientInfoFromInitialize(initialize));
77
+ const clientInfo = clientInfoFromInitialize(initialize);
78
+ const sessionId = (0, exports.buildStatelessSessionId)(clientInfo, (0, utils_js_1.headerValue)(input.headers, "x-armature-session-seed") ?? undefined);
73
79
  return {
74
80
  sessionId,
75
81
  sessionIdGenerator: () => sessionId,
@@ -39,6 +39,14 @@ export type ActorIdResolverInput = {
39
39
  telemetry?: TelemetryArgs;
40
40
  };
41
41
  export type ActorIdResolver = (input: ActorIdResolverInput) => string | Promise<string>;
42
+ export type RedactFunction = (value: unknown) => unknown;
43
+ export type TelemetryFieldMap = {
44
+ /** @deprecated `user_turn` is no longer collected; this mapping is ignored. */
45
+ user_turn?: string;
46
+ user_intent?: string;
47
+ agent_thinking?: string;
48
+ user_frustration?: string;
49
+ };
42
50
  export type McpAnalyticsConfig = {
43
51
  armature?: {
44
52
  endpointUrl?: string;
@@ -49,16 +57,22 @@ export type McpAnalyticsConfig = {
49
57
  emit?: TelemetryEmitter;
50
58
  onError?: (error: unknown, batch: AnalyticsIngestBatch) => void;
51
59
  timeoutMs?: number;
60
+ captureTelemetry?: boolean;
61
+ redact?: RedactFunction;
62
+ telemetryFieldMap?: TelemetryFieldMap;
52
63
  };
53
64
  };
65
+ export type TelemetryMode = "injected" | "owned" | "scrub";
54
66
  export type InternalMcpAnalyticsConfig = McpAnalyticsConfig & {
67
+ /** @deprecated Required-per-call intent conflicts with sparse intent declarations and is ignored. */
55
68
  telemetry?: {
56
69
  user_intent?: "required" | "optional";
57
- /** @deprecated Pre-V1 spelling of `user_intent`; still honored. */
70
+ /** @deprecated Pre-V1 spelling retained for source compatibility; ignored. */
58
71
  intent?: "required" | "optional";
59
72
  };
60
73
  };
61
74
  export type TelemetryArgs = {
75
+ /** @deprecated `user_turn` is accepted from cached clients but ignored. */
62
76
  user_turn?: number;
63
77
  user_intent?: string;
64
78
  agent_thinking?: string;
@@ -125,6 +139,7 @@ export type InstrumentToolCallEvent = {
125
139
  requestId?: string;
126
140
  clientInfo?: McpClientInfo;
127
141
  workflowRunId?: string;
142
+ telemetryMode?: TelemetryMode;
128
143
  };
129
144
  export type ToolCallHandler<T> = (args: unknown) => T | Promise<T>;
130
145
  export type ToolHandlerContext = {
@@ -151,7 +166,7 @@ export type McpServerInfo = {
151
166
  };
152
167
  export type AnalyticsRecorder = {
153
168
  decorateDefinitions: (defs: ToolDefinition[]) => ToolDefinition[];
154
- extractTelemetry: (args: unknown) => ExtractedToolArguments;
169
+ extractTelemetry: (args: unknown, mode?: TelemetryMode) => ExtractedToolArguments;
155
170
  recordToolCall: (event: RecordToolCallEvent) => Promise<void>;
156
171
  recordSessionInit: (event: RecordSessionInitEvent) => Promise<void>;
157
172
  instrumentToolCall: <T>(event: InstrumentToolCallEvent, handler: ToolCallHandler<T>) => Promise<T>;
@@ -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;
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { normalizeTelemetryArgs } from "./schema.js";
3
+ import { prepareForPreview, REDACTION_FAILED_PLACEHOLDER, } from "./sanitize.js";
3
4
  import { MAX_CAPABILITIES_BYTES, MAX_PREVIEW_BYTES, MAX_SOURCE_BYTES, SCHEMA_VERSION, headerValue, isRecord, sha256Hex, stringifyPreview, truncateUtf8, } from "./utils.js";
4
5
  const trimOrUndefined = (value) => {
5
6
  if (typeof value !== "string")
@@ -28,6 +29,30 @@ export const buildEventId = ({ actorId, requestId, kind, }) => {
28
29
  const buildToolCallSource = (toolName, input) => {
29
30
  return `MCP tool call: ${toolName}\n\nInput:\n${stringifyPreview(input)}`;
30
31
  };
32
+ // Telemetry text is agent-authored but routinely quotes the user, so the
33
+ // customer redaction hook sees it too. Whatever the hook returns is
34
+ // re-normalized; a throwing hook drops the telemetry entirely (fail closed).
35
+ const redactTelemetry = (telemetry, redact) => {
36
+ if (telemetry === undefined || !redact)
37
+ return telemetry;
38
+ try {
39
+ return normalizeTelemetryArgs(redact(telemetry));
40
+ }
41
+ catch {
42
+ return undefined;
43
+ }
44
+ };
45
+ const redactErrorMessage = (errorMessage, redact) => {
46
+ if (errorMessage === undefined || !redact)
47
+ return errorMessage;
48
+ try {
49
+ const redacted = redact(errorMessage);
50
+ return typeof redacted === "string" ? redacted : stringifyPreview(redacted);
51
+ }
52
+ catch {
53
+ return REDACTION_FAILED_PLACEHOLDER;
54
+ }
55
+ };
31
56
  // Marks an event as synthetic traffic from an Armature workflow run so
32
57
  // Session Analytics can exclude it. Spread first in the event literal —
33
58
  // absent when the call did not originate from a workflow run.
@@ -36,13 +61,22 @@ const workflowStamp = (workflowRunId) => {
36
61
  return {};
37
62
  return { is_workflow: true, workflow_run_id: workflowRunId };
38
63
  };
39
- export const buildToolCallEvent = ({ toolName, telemetry, input, output, status, durationMs, errorMessage, actorId, sessionId, requestId, startedAt, finishedAt, workflowRunId, }) => {
40
- const inputPreview = truncateUtf8(stringifyPreview(input), MAX_PREVIEW_BYTES);
41
- const source = truncateUtf8(buildToolCallSource(toolName, input), MAX_SOURCE_BYTES);
42
- const resultPreview = output === undefined
64
+ export const buildToolCallEvent = ({ toolName, telemetry, input, output, status, durationMs, errorMessage, actorId, sessionId, requestId, startedAt, finishedAt, workflowRunId, redact, }) => {
65
+ // Contract pipeline (TELEMETRY-CONTRACT.md): sanitize → customer redact →
66
+ // stringify → truncate, for every payload that can carry customer data —
67
+ // input preview, the source built from the input, the result preview, the
68
+ // error string, and the telemetry text.
69
+ const safeInput = prepareForPreview(input, redact);
70
+ const safeOutput = output === undefined
71
+ ? undefined
72
+ : prepareForPreview(output, redact);
73
+ const safeErrorMessage = redactErrorMessage(errorMessage, redact);
74
+ const inputPreview = truncateUtf8(stringifyPreview(safeInput), MAX_PREVIEW_BYTES);
75
+ const source = truncateUtf8(buildToolCallSource(toolName, safeInput), MAX_SOURCE_BYTES);
76
+ const resultPreview = safeOutput === undefined
43
77
  ? null
44
- : truncateUtf8(stringifyPreview(output), MAX_PREVIEW_BYTES);
45
- const t = normalizeTelemetryArgs(telemetry);
78
+ : truncateUtf8(stringifyPreview(safeOutput), MAX_PREVIEW_BYTES);
79
+ const t = redactTelemetry(normalizeTelemetryArgs(telemetry), redact);
46
80
  return {
47
81
  ...workflowStamp(workflowRunId),
48
82
  event_id: buildEventId({ actorId, requestId, kind: "tool_call" }),
@@ -53,10 +87,9 @@ export const buildToolCallEvent = ({ toolName, telemetry, input, output, status,
53
87
  finished_at: finishedAt,
54
88
  duration_ms: durationMs,
55
89
  ok: status === "ok",
56
- error: errorMessage ?? null,
90
+ error: safeErrorMessage ?? null,
57
91
  metadata: {
58
92
  tool_name: toolName,
59
- user_turn: t?.user_turn ?? null,
60
93
  user_intent: t?.user_intent ?? null,
61
94
  agent_thinking: t?.agent_thinking ?? null,
62
95
  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/esm/index.js CHANGED
@@ -1,4 +1,5 @@
1
- export { appendTelemetryHint, createTelemetryInputSchema, createTelemetryJsonSchema, decorateInputSchemaWithTelemetry, extractTelemetryArguments, normalizeTelemetryArgs, } from "./schema.js";
1
+ export { appendTelemetryHint, applyTelemetryFieldMap, createTelemetryInputSchema, createTelemetryJsonSchema, decorateInputSchemaWithTelemetry, extractTelemetryArguments, isCaptureEnabled, normalizeTelemetryArgs, planToolTelemetry, schemaDeclaresTelemetry, } from "./schema.js";
2
+ export { BASE64_REMOVED_PLACEHOLDER, BINARY_REMOVED_PLACEHOLDER, prepareForPreview, REDACTION_FAILED_PLACEHOLDER, sanitizeValue, } from "./sanitize.js";
2
3
  export { buildActorId, buildEventId, buildSessionInitEvent, buildToolCallEvent, normalizeSessionId, } from "./events.js";
3
4
  export { defaultMcpAnalyticsConfig, emitTelemetryEvent, postTelemetryEvent, } from "./emit.js";
4
5
  export { createAnalyticsRecorder } from "./recorder.js";