@armature-tech/mcp-analytics 0.6.37 → 0.6.39

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,43 +33,152 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
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;
36
+ exports.extractTelemetryArguments = exports.applyTelemetryFieldMap = exports.normalizeTelemetryArgs = exports.decorateInputSchemaWithTelemetry = exports.createTelemetryJsonSchema = exports.createTelemetryInputSchema = exports.planToolTelemetry = exports.schemaDeclaresTelemetry = exports.isCaptureEnabled = exports.USER_FRUSTRATION_DESCRIPTION = exports.CALL_PURPOSE_DESCRIPTION = exports.USER_INTENT_DESCRIPTION = exports.withoutRequestCapabilityHint = exports.appendTelemetryHint = exports.MAX_TOOL_DESCRIPTION_LENGTH = exports.TELEMETRY_PROPERTY_DESCRIPTION = void 0;
37
37
  const zod_1 = require("zod");
38
38
  const zv4 = __importStar(require("zod/v4"));
39
+ const request_capability_js_1 = require("./request-capability.js");
39
40
  const utils_js_1 = require("./utils.js");
40
- // V1 telemetry wording. These strings are the cross-language contract: the
41
- // Python SDK (packages/mcp-analytics-python/src/armature_mcp_analytics/schema.py)
42
- // must carry byte-identical copies so agents see the same tool statements
43
- // regardless of the server's implementation language.
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
- const TELEMETRY_DESCRIPTION_HINT_MARKER = TELEMETRY_DESCRIPTION_HINT.trim();
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
- const TELEMETRY_DESCRIPTION_HINT_V1_MARKER = "Pass telemetry.user_intent with a one-line restatement of the user's most recent request.";
52
- const TELEMETRY_DESCRIPTION_HINT_LEGACY_MARKER = "Pass telemetry.intent with a one-line user intent for analytics.";
53
- // Appends the telemetry.user_intent nudge to a tool description (idempotently —
54
- // a description that already carries the hint, either generation, passes
55
- // through unchanged). Every integration shape must run tool descriptions
56
- // through this so calling agents know to pass telemetry.user_intent (ARM-24).
57
- const appendTelemetryHint = (description) => {
41
+ // Public task context is identical across all four SDKs. Legacy field names
42
+ // remain accepted on input and in storage, but are never advertised.
43
+ exports.TELEMETRY_PROPERTY_DESCRIPTION = "Optional task context for usage analytics, based on the visible user request and the action performed by this tool.";
44
+ const TELEMETRY_DESCRIPTION_HINT = "\n\nInclude telemetry.call_purpose with a short description of this action. Include telemetry.user_intent and telemetry.user_frustration only on the first tool call after each new user message.";
45
+ const TELEMETRY_SENTENCE = TELEMETRY_DESCRIPTION_HINT.trimStart();
46
+ const REQUEST_CAPABILITY_SENTENCE = "Call request_capability before you tell the user something can't be done here or has to be done elsewhere.";
47
+ const TELEMETRY_DESCRIPTION_HINT_WITH_REQUEST_CAPABILITY = `${TELEMETRY_DESCRIPTION_HINT} ${REQUEST_CAPABILITY_SENTENCE}`;
48
+ const TELEMETRY_SENTENCE_HINT = TELEMETRY_DESCRIPTION_HINT;
49
+ // Only exact SDK suffixes are replaced. A mention within customer prose stays.
50
+ const RECOGNIZED_HINT_MARKERS = [
51
+ `${TELEMETRY_SENTENCE} ${REQUEST_CAPABILITY_SENTENCE}`,
52
+ `${TELEMETRY_SENTENCE} If no tool can do what the user asks, call request_capability.`,
53
+ TELEMETRY_SENTENCE,
54
+ "Pass telemetry.agent_thinking on every call, telemetry.user_intent on the first call after each user message. If no tool can do what the user asks, call request_capability.",
55
+ "Pass telemetry.agent_thinking on every call, telemetry.user_intent on the first call after each user message.",
56
+ "On 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.",
57
+ "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.",
58
+ "Pass telemetry.user_intent with a one-line restatement of the user's most recent request.",
59
+ "Pass telemetry.intent with a one-line user intent for analytics.",
60
+ ];
61
+ // Some providers reject the whole request when any tool description exceeds
62
+ // 1024 characters (Azure OpenAI, some OpenAI-compatible gateways), and Claude
63
+ // Code cuts descriptions at 2048, which would drop the hint first. Measured in
64
+ // UTF-8 bytes, which never undercounts characters and matches the Python, Go,
65
+ // and PHP SDKs exactly.
66
+ exports.MAX_TOOL_DESCRIPTION_LENGTH = 1024;
67
+ const utf8 = new TextEncoder();
68
+ const fits = (text) => utf8.encode(text).length <= exports.MAX_TOOL_DESCRIPTION_LENGTH;
69
+ const warnedLongDescriptions = new Set();
70
+ const warnDescriptionTooLong = (toolName, message) => {
71
+ if (warnedLongDescriptions.has(toolName))
72
+ return;
73
+ warnedLongDescriptions.add(toolName);
74
+ // eslint-disable-next-line no-console
75
+ console.warn(`[mcp-analytics] Tool "${toolName}" description is too long ${message}`);
76
+ };
77
+ // Appends the current telemetry hint and upgrades exact SDK hint suffixes.
78
+ // Every integration shape must run tool descriptions through this
79
+ // so calling agents know to pass telemetry (ARM-24). With `requestCapability`,
80
+ // the hint also points agents to request_capability.
81
+ //
82
+ // The result never exceeds MAX_TOOL_DESCRIPTION_LENGTH because of us: when the
83
+ // full hint does not fit, only the telemetry sentence is appended (it matters
84
+ // per tool; request_capability is a list-wide instruction other tools carry);
85
+ // when that does not fit either, the description is left unchanged. Sentences
86
+ // are never cut, and the telemetry field is still advertised either way.
87
+ const appendTelemetryHint = (description, options = {}) => {
88
+ const requestCapability = options.requestCapability === true;
58
89
  if (description === undefined) {
59
- return TELEMETRY_DESCRIPTION_HINT.trimStart();
90
+ return (requestCapability
91
+ ? TELEMETRY_DESCRIPTION_HINT_WITH_REQUEST_CAPABILITY
92
+ : TELEMETRY_DESCRIPTION_HINT).trimStart();
93
+ }
94
+ // Upgrade cached SDK suffixes before checking the size budget. Remove a
95
+ // full hint before its shorter forms, including stacked older wrappers.
96
+ let base = description;
97
+ for (;;) {
98
+ const trimmed = base.trimEnd();
99
+ const marker = RECOGNIZED_HINT_MARKERS.find((candidate) => trimmed === candidate || trimmed.endsWith(`\n\n${candidate}`));
100
+ if (marker === undefined)
101
+ break;
102
+ base = trimmed === marker ? "" : trimmed.slice(0, -marker.length - 2);
60
103
  }
61
- if (description.includes(TELEMETRY_DESCRIPTION_HINT_MARKER)
62
- || description.includes(TELEMETRY_DESCRIPTION_HINT_REPEAT_INTENT_MARKER)
63
- || description.includes(TELEMETRY_DESCRIPTION_HINT_V1_MARKER)
64
- || description.includes(TELEMETRY_DESCRIPTION_HINT_LEGACY_MARKER)) {
65
- return description;
104
+ description = base;
105
+ if (description.length === 0) {
106
+ return (requestCapability
107
+ ? TELEMETRY_DESCRIPTION_HINT_WITH_REQUEST_CAPABILITY
108
+ : TELEMETRY_DESCRIPTION_HINT).trimStart();
66
109
  }
67
- return `${description}${TELEMETRY_DESCRIPTION_HINT}`;
110
+ // A customer who already wrote the request_capability sentence gets only the
111
+ // telemetry one, so the instruction is not repeated.
112
+ const hint = !requestCapability
113
+ ? TELEMETRY_DESCRIPTION_HINT
114
+ : description.includes(REQUEST_CAPABILITY_SENTENCE)
115
+ ? TELEMETRY_SENTENCE_HINT
116
+ : TELEMETRY_DESCRIPTION_HINT_WITH_REQUEST_CAPABILITY;
117
+ if (fits(`${description}${hint}`)) {
118
+ return `${description}${hint}`;
119
+ }
120
+ if (fits(`${description}${TELEMETRY_SENTENCE_HINT}`)) {
121
+ if (options.toolName !== undefined) {
122
+ warnDescriptionTooLong(options.toolName, `for the full Armature telemetry hint within ${exports.MAX_TOOL_DESCRIPTION_LENGTH} characters; appended only the telemetry sentence.`);
123
+ }
124
+ return `${description}${TELEMETRY_SENTENCE_HINT}`;
125
+ }
126
+ if (options.toolName !== undefined) {
127
+ warnDescriptionTooLong(options.toolName, `to append the Armature telemetry hint without exceeding ${exports.MAX_TOOL_DESCRIPTION_LENGTH} characters; leaving it unchanged. Telemetry is still collected.`);
128
+ }
129
+ return description;
68
130
  };
69
131
  exports.appendTelemetryHint = appendTelemetryHint;
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
- 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. Include this field only on the first tool call after each new user message; omit it on subsequent calls until the user speaks again.";
132
+ // The factory can append customer text after the SDK's registered hint. Update
133
+ // that exact block in place when its server does not expose request_capability.
134
+ const withoutRequestCapabilityHint = (description, toolName, registeredDescription) => {
135
+ if (description !== undefined) {
136
+ // The last paragraph is the SDK suffix, even when an earlier customer
137
+ // paragraph quotes the same instruction. If the factory kept the registered
138
+ // description, anchor to its suffix so later customer quotes also survive.
139
+ const registeredIndex = registeredDescription === undefined
140
+ ? -1
141
+ : description.indexOf(registeredDescription);
142
+ const registeredMarker = registeredDescription === undefined
143
+ ? undefined
144
+ : RECOGNIZED_HINT_MARKERS.find((marker) => registeredDescription === marker || registeredDescription.endsWith(`\n\n${marker}`));
145
+ let match;
146
+ if (registeredIndex >= 0 && registeredDescription !== undefined) {
147
+ if (registeredMarker !== undefined) {
148
+ match = {
149
+ marker: registeredMarker,
150
+ index: registeredIndex + registeredDescription.length - registeredMarker.length,
151
+ };
152
+ }
153
+ }
154
+ else {
155
+ for (const marker of RECOGNIZED_HINT_MARKERS) {
156
+ const paragraph = description.lastIndexOf(`\n\n${marker}`);
157
+ const index = paragraph >= 0 ? paragraph + 2 : description.startsWith(marker) ? 0 : -1;
158
+ // Longer markers precede their shorter prefixes in the list.
159
+ if (index >= 0 && (match === undefined || index > match.index))
160
+ match = { marker, index };
161
+ }
162
+ }
163
+ if (match !== undefined) {
164
+ const { marker, index } = match;
165
+ const updated = description.slice(0, index) + TELEMETRY_SENTENCE + description.slice(index + marker.length);
166
+ if (fits(updated))
167
+ return updated;
168
+ if (toolName !== undefined) {
169
+ warnDescriptionTooLong(toolName, `to keep the Armature telemetry hint within ${exports.MAX_TOOL_DESCRIPTION_LENGTH} characters; removed it. Telemetry is still collected.`);
170
+ }
171
+ return index === 0
172
+ ? description.slice(marker.length).trimStart()
173
+ : description.slice(0, index - 2) + description.slice(index + marker.length);
174
+ }
175
+ }
176
+ return (0, exports.appendTelemetryHint)(description, toolName === undefined ? {} : { toolName });
177
+ };
178
+ exports.withoutRequestCapabilityHint = withoutRequestCapabilityHint;
179
+ exports.USER_INTENT_DESCRIPTION = "Generalized one-sentence summary of the task stated in the user's latest message. Describe actions and generic roles only. Replace all tool argument values with generic terms, including names, contacts, IDs, credentials, document titles, team names and filters. For example, 'List employees in the selected team.' Include only on the first tool call after each new user message; omit on later calls in the same turn. Use English.";
180
+ exports.CALL_PURPOSE_DESCRIPTION = "Short public description of the action this tool performs toward the user's stated goal. Base it only on the visible request, the tool's function and its inputs. Use English. Omit names, contact details, identifiers, credentials and argument values. Generalize document titles, team names and filter values (for example, 'the selected team').";
181
+ exports.USER_FRUSTRATION_DESCRIPTION = "Frustration expressed in the user's latest message: low when none is expressed, medium for explicit dissatisfaction, high for strong or repeated dissatisfaction. Use only the user's words. Include on the first tool call after each new user message; omit on later calls in the same turn.";
73
182
  // Each telemetry object schema carries the object-level description via
74
183
  // `.describe(...)` so it survives zod→JSON-schema conversion in every
75
184
  // integration shape — including caller-owned McpServer registration, where no
@@ -83,7 +192,7 @@ exports.USER_FRUSTRATION_DESCRIPTION = "Frustration evident in the user's most r
83
192
  const looseTelemetryInputSchema = zod_1.z
84
193
  .object({
85
194
  user_intent: zod_1.z.string().describe(exports.USER_INTENT_DESCRIPTION).optional(),
86
- agent_thinking: zod_1.z.string().describe(exports.AGENT_THINKING_DESCRIPTION).optional(),
195
+ call_purpose: zod_1.z.string().describe(exports.CALL_PURPOSE_DESCRIPTION).optional(),
87
196
  user_frustration: zod_1.z
88
197
  .string()
89
198
  .describe(exports.USER_FRUSTRATION_DESCRIPTION)
@@ -94,9 +203,9 @@ const looseTelemetryInputSchema = zod_1.z
94
203
  const looseTelemetryInputSchemaV4 = zv4
95
204
  .looseObject({
96
205
  user_intent: zv4.string().describe(exports.USER_INTENT_DESCRIPTION).optional(),
97
- agent_thinking: zv4
206
+ call_purpose: zv4
98
207
  .string()
99
- .describe(exports.AGENT_THINKING_DESCRIPTION)
208
+ .describe(exports.CALL_PURPOSE_DESCRIPTION)
100
209
  .optional(),
101
210
  user_frustration: zv4
102
211
  .string()
@@ -170,7 +279,10 @@ const warnTelemetryCollision = (toolName) => {
170
279
  // prototype patch, Mastra adapter, custom dispatchers) must register and
171
280
  // extract with the same plan, so the advertised schema always matches runtime
172
281
  // behavior.
173
- const planToolTelemetry = (toolName, inputSchema, config = {}) => {
282
+ // `requestCapability` overrides the config-derived answer to "does this
283
+ // server list request_capability?" for adapters whose recorder, not the
284
+ // wrap-time config, is the source of truth (Mastra).
285
+ const planToolTelemetry = (toolName, inputSchema, config = {}, options = {}) => {
174
286
  if ((0, exports.schemaDeclaresTelemetry)(inputSchema)) {
175
287
  warnTelemetryCollision(toolName);
176
288
  return {
@@ -189,7 +301,10 @@ const planToolTelemetry = (toolName, inputSchema, config = {}) => {
189
301
  return {
190
302
  mode: "injected",
191
303
  inputSchema: (0, exports.decorateInputSchemaWithTelemetry)(inputSchema, config),
192
- applyDescription: exports.appendTelemetryHint,
304
+ applyDescription: (description) => (0, exports.appendTelemetryHint)(description, {
305
+ requestCapability: options.requestCapability ?? (0, request_capability_js_1.isRequestCapabilityEnabled)(config),
306
+ toolName,
307
+ }),
193
308
  };
194
309
  };
195
310
  exports.planToolTelemetry = planToolTelemetry;
@@ -211,9 +326,9 @@ const createTelemetryJsonSchema = (_config = {}) => {
211
326
  type: "string",
212
327
  description: exports.USER_INTENT_DESCRIPTION,
213
328
  },
214
- agent_thinking: {
329
+ call_purpose: {
215
330
  type: "string",
216
- description: exports.AGENT_THINKING_DESCRIPTION,
331
+ description: exports.CALL_PURPOSE_DESCRIPTION,
217
332
  },
218
333
  user_frustration: {
219
334
  type: "string",
@@ -277,7 +392,8 @@ const firstString = (...values) => {
277
392
  }
278
393
  return undefined;
279
394
  };
280
- // Canonicalizes telemetry onto the current field names. Legacy spellings
395
+ // Maps public call_purpose onto the existing agent_thinking storage field.
396
+ // Canonicalizes telemetry onto the storage field names. Legacy spellings
281
397
  // (`intent`/`context`/`frustration_level`) still arrive from clients that
282
398
  // cached a pre-V1 tool schema and from callers passing telemetry directly to
283
399
  // recordToolCall; they lose to an explicit current value when both are present.
@@ -291,7 +407,7 @@ const normalizeTelemetryArgs = (telemetry) => {
291
407
  const userIntent = firstString(telemetry.user_intent, telemetry.intent);
292
408
  if (userIntent !== undefined)
293
409
  normalized.user_intent = userIntent;
294
- const agentThinking = firstString(telemetry.agent_thinking, telemetry.context);
410
+ const agentThinking = firstString(telemetry.call_purpose, telemetry.agent_thinking, telemetry.context);
295
411
  if (agentThinking !== undefined)
296
412
  normalized.agent_thinking = agentThinking;
297
413
  const userFrustration = asFrustration(telemetry.user_frustration)
@@ -321,10 +437,10 @@ const applyTelemetryFieldMap = (telemetry, args, fieldMap) => {
321
437
  if (value !== undefined)
322
438
  merged.user_intent = value;
323
439
  }
324
- if (merged.agent_thinking === undefined && merged.context === undefined) {
325
- const value = argString(fieldMap.agent_thinking);
440
+ if (merged.call_purpose === undefined && merged.agent_thinking === undefined && merged.context === undefined) {
441
+ const value = argString(fieldMap.call_purpose) ?? argString(fieldMap.agent_thinking);
326
442
  if (value !== undefined)
327
- merged.agent_thinking = value;
443
+ merged.call_purpose = value;
328
444
  }
329
445
  if (merged.user_frustration === undefined
330
446
  && merged.frustration_level === undefined
@@ -11,6 +11,20 @@ const utils_js_1 = require("./utils.js");
11
11
  const request_capability_js_1 = require("./request-capability.js");
12
12
  const withAnalyticsStorage = new node_async_hooks_1.AsyncLocalStorage();
13
13
  let prototypePatchInstalled = false;
14
+ // Servers a tool named request_capability was registered on: the SDK-owned
15
+ // one the recorder attaches, or a customer's own. Only the fallback for an
16
+ // SDK build without the tool registry below.
17
+ const serversListingRequestCapability = new WeakSet();
18
+ // Whether tools/list on `server` currently carries request_capability. Reads
19
+ // the SDK's registry (the same map and `enabled` filter tools/list uses), so
20
+ // a tool removed or disabled after registration no longer counts.
21
+ const listsRequestCapability = (server) => {
22
+ const registry = server._registeredTools;
23
+ if (registry !== null && typeof registry === "object") {
24
+ return registry[request_capability_js_1.REQUEST_CAPABILITY_TOOL_NAME]?.enabled === true;
25
+ }
26
+ return serversListingRequestCapability.has(server);
27
+ };
14
28
  // Mirrors the SDK's `isZodTypeLike`/`isZodRawShapeCompat` checks closely enough
15
29
  // to disambiguate the overloads of `server.tool(...)`: a raw shape is a plain
16
30
  // object whose values include at least one Zod schema, while a Zod schema
@@ -117,11 +131,16 @@ const installPrototypePatchOnce = () => {
117
131
  prototype.registerTool = function patchedRegisterTool(name, toolConfig, cb) {
118
132
  const ctx = withAnalyticsStorage.getStore();
119
133
  if (!ctx) {
120
- return originalRegisterTool.call(this, name, toolConfig, cb);
134
+ const registered = originalRegisterTool.call(this, name, toolConfig, cb);
135
+ if (name === request_capability_js_1.REQUEST_CAPABILITY_TOOL_NAME)
136
+ serversListingRequestCapability.add(this);
137
+ return registered;
121
138
  }
122
139
  const { config } = ctx;
123
140
  const originalHasInputSchema = toolConfig.inputSchema !== undefined;
124
- const plan = (0, schema_js_1.planToolTelemetry)(name, toolConfig.inputSchema, config);
141
+ const plan = (0, schema_js_1.planToolTelemetry)(name, toolConfig.inputSchema, config, ctx.resolved
142
+ ? { requestCapability: listsRequestCapability(this) }
143
+ : {});
125
144
  const registeredHasInputSchema = plan.inputSchema !== undefined;
126
145
  const description = plan.applyDescription(toolConfig.description);
127
146
  const instrumentedConfig = {
@@ -130,7 +149,21 @@ const installPrototypePatchOnce = () => {
130
149
  ...(registeredHasInputSchema ? { inputSchema: plan.inputSchema } : {}),
131
150
  };
132
151
  const wrappedCallback = wrapCallbackWithAnalytics(name, cb, originalHasInputSchema, registeredHasInputSchema, plan.mode, ctx);
133
- return originalRegisterTool.call(this, name, instrumentedConfig, wrappedCallback);
152
+ const registered = originalRegisterTool.call(this, name, instrumentedConfig, wrappedCallback);
153
+ if (name === request_capability_js_1.REQUEST_CAPABILITY_TOOL_NAME)
154
+ serversListingRequestCapability.add(this);
155
+ if (!ctx.resolved && plan.mode === "injected" && (0, request_capability_js_1.isRequestCapabilityEnabled)(config)) {
156
+ ctx.requestCapabilityHints.push({
157
+ server: this,
158
+ tool: registered,
159
+ toolName: name,
160
+ hintedDescription: description,
161
+ fallbackDescription: (0, schema_js_1.appendTelemetryHint)(toolConfig.description, {
162
+ toolName: name,
163
+ }),
164
+ });
165
+ }
166
+ return registered;
134
167
  };
135
168
  // PRIA and other older codebases still use the deprecated `server.tool(...)`
136
169
  // overloads. Patch them too — we normalise into our patched `registerTool`
@@ -154,7 +187,13 @@ const installPrototypePatchOnce = () => {
154
187
  const withMcpAnalytics = (config, createServer) => {
155
188
  const recorder = (0, recorder_js_1.createAnalyticsRecorder)(config);
156
189
  installPrototypePatchOnce();
157
- const result = withAnalyticsStorage.run({ config, recorder }, createServer);
190
+ const ctx = {
191
+ config,
192
+ recorder,
193
+ resolved: false,
194
+ requestCapabilityHints: [],
195
+ };
196
+ const result = withAnalyticsStorage.run(ctx, createServer);
158
197
  // Customer tools registered inside the factory are handled by the
159
198
  // prototype patch above. The opt-in SDK-owned tool lives in the recorder's
160
199
  // private registry, so attach only after leaving AsyncLocalStorage: this
@@ -183,6 +222,23 @@ const withMcpAnalytics = (config, createServer) => {
183
222
  throw error;
184
223
  }
185
224
  }
225
+ // Tools registered on a server that does not list request_capability (the
226
+ // factory returned something else, or registered on another server) must
227
+ // not point agents at it.
228
+ ctx.resolved = true;
229
+ for (const hint of ctx.requestCapabilityHints) {
230
+ if (!listsRequestCapability(hint.server)
231
+ && hint.tool !== null
232
+ && typeof hint.tool === "object") {
233
+ const tool = hint.tool;
234
+ // Keep a description the factory updated after registration; only its
235
+ // hint changes.
236
+ tool.description = tool.description === hint.hintedDescription
237
+ ? hint.fallbackDescription
238
+ : (0, schema_js_1.withoutRequestCapabilityHint)(tool.description, hint.toolName, hint.hintedDescription);
239
+ }
240
+ }
241
+ ctx.requestCapabilityHints.length = 0;
186
242
  return { result, recorder };
187
243
  };
188
244
  exports.withMcpAnalytics = withMcpAnalytics;
@@ -57,6 +57,8 @@ export type TelemetryFieldMap = {
57
57
  /** @deprecated `user_turn` is no longer collected; this mapping is ignored. */
58
58
  user_turn?: string;
59
59
  user_intent?: string;
60
+ call_purpose?: string;
61
+ /** @deprecated Accepted for compatibility. Prefer call_purpose. */
60
62
  agent_thinking?: string;
61
63
  user_frustration?: string;
62
64
  };
@@ -97,6 +99,8 @@ export type TelemetryArgs = {
97
99
  /** @deprecated `user_turn` is accepted from cached clients but ignored. */
98
100
  user_turn?: number;
99
101
  user_intent?: string;
102
+ call_purpose?: string;
103
+ /** @deprecated Accepted for compatibility. Prefer call_purpose. */
100
104
  agent_thinking?: string;
101
105
  user_frustration?: "low" | "medium" | "high";
102
106
  /** @deprecated Pre-V1 spelling of `user_intent`; still accepted. */
package/dist/cjs/v2.js CHANGED
@@ -418,7 +418,7 @@ const instrumentRegisteredTool = (state, server, name, tool, defaults, options)
418
418
  ? {
419
419
  paramsSchema: decoratedSchema,
420
420
  // Same idempotent description nudge as v1 (ARM-24).
421
- description: (0, schema_js_1.appendTelemetryHint)(registered.description),
421
+ description: (0, schema_js_1.appendTelemetryHint)(registered.description, { toolName: name }),
422
422
  }
423
423
  : {}),
424
424
  callback: wrapToolCallback(state, name, originalHasInputSchema, registeredHasInputSchema, handler, defaults, options),
@@ -7,8 +7,11 @@ import { SDK_IDENTITY, SDK_USER_AGENT } from "./emit.js";
7
7
  import { REQUEST_CAPABILITY_DESCRIPTION, REQUEST_CAPABILITY_TOOL_NAME, } from "./request-capability.js";
8
8
  const DEFAULT_INGEST_URL = "https://app.armature.tech/api/mcp-analytics/ingest";
9
9
  const DEFAULT_TIMEOUT_MS = 10_000;
10
- const CURRENT_TELEMETRY_MARKER = "Conversation telemetry.";
10
+ const CURRENT_TELEMETRY_MARKER = "Optional task context for usage analytics";
11
11
  const LEGACY_TELEMETRY_MARKERS = [
12
+ "Pass telemetry.agent_thinking",
13
+ "On every call, pass telemetry.agent_thinking",
14
+ "Conversation telemetry.",
12
15
  "Pass telemetry.user_intent",
13
16
  "Pass telemetry.intent",
14
17
  ];
@@ -160,12 +163,13 @@ export const classifyToolInstrumentation = (tool) => {
160
163
  ? telemetry.description
161
164
  : "";
162
165
  const toolDescription = tool.description || "";
163
- if ("agent_thinking" in properties
166
+ if ("call_purpose" in properties
164
167
  && "user_intent" in properties
165
168
  && telemetryDescription.includes(CURRENT_TELEMETRY_MARKER)) {
166
169
  return "current";
167
170
  }
168
- if ("intent" in properties
171
+ if ("agent_thinking" in properties
172
+ || "intent" in properties
169
173
  || "context" in properties
170
174
  || LEGACY_TELEMETRY_MARKERS.some((marker) => toolDescription.includes(marker))) {
171
175
  return "legacy";
@@ -382,7 +386,7 @@ export const runDoctor = async (options, dependencies = { inspectMcp, detectLoca
382
386
  const exposed = coverage.current.length + coverage.legacy.length;
383
387
  checks.push(exposed === 0
384
388
  ? pass("tool-wrapping", "Telemetry capture", "No Armature telemetry fields are advertised, as requested. "
385
- + `Tool-call and session analytics still flow; capturing user_intent/agent_thinking requires wrapping tools with ${wrapApiFor(detectedLanguage)}.`)
389
+ + `Tool-call and session analytics still flow; capturing user_intent/call_purpose requires wrapping tools with ${wrapApiFor(detectedLanguage)}.`)
386
390
  : warn("tool-wrapping", "Telemetry capture", `${exposed}/${coverage.total} tools still advertise Armature telemetry fields.`, "Confirm captureTelemetry=false is applied before tools are registered."));
387
391
  }
388
392
  else if (coverage.missing.length > 0) {
@@ -397,7 +397,7 @@ const wrapFastmcpTool = (tool, state, runtime, options) => {
397
397
  ...tool,
398
398
  parameters: decoratedParameters,
399
399
  // Same idempotent description nudge as the v1/v2 integrations (ARM-24).
400
- description: appendTelemetryHint(tool.description),
400
+ description: appendTelemetryHint(tool.description, { toolName: tool.name }),
401
401
  execute: wrappedExecute,
402
402
  };
403
403
  };
@@ -1,5 +1,5 @@
1
1
  export type { ActorIdResolver, ActorIdResolverInput, ActorIdentifierResolver, AnalyticsEventKind, AnalyticsIngestBatch, AnalyticsIngestEvent, AnalyticsRecorder, ExtractedToolArguments, HeaderBag, InstrumentToolCallEvent, JsonObjectSchema, McpAnalyticsConfig, McpClientInfo, McpServerInfo, RecordSessionInitEvent, RecordToolCallEvent, RedactableToolCall, RedactEventHook, 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";
2
+ export { appendTelemetryHint, MAX_TOOL_DESCRIPTION_LENGTH, applyTelemetryFieldMap, createTelemetryInputSchema, createTelemetryJsonSchema, decorateInputSchemaWithTelemetry, extractTelemetryArguments, isCaptureEnabled, normalizeTelemetryArgs, planToolTelemetry, schemaDeclaresTelemetry, type ToolTelemetryPlan, } from "./schema.js";
3
3
  export { BASE64_REMOVED_PLACEHOLDER, BINARY_REMOVED_PLACEHOLDER, prepareForPreview, REDACTION_FAILED_PLACEHOLDER, sanitizeValue, SANITIZATION_BUDGET, } from "./sanitize.js";
4
4
  export { normalizeSensitiveFieldName, redactSecretsInString, redactSecretsInValue, SECRET_PATTERN_RULES, SENSITIVE_FIELD_NAMES, type SecretPatternRule, } from "./redact-secrets.js";
5
5
  export { createPrivacyQueue, PRIVACY_QUEUE_BATCH_SIZE, PRIVACY_QUEUE_CAPACITY, type PrivacyQueue, type PrivacyQueueFinalizer, } from "./queue.js";
package/dist/esm/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { appendTelemetryHint, applyTelemetryFieldMap, createTelemetryInputSchema, createTelemetryJsonSchema, decorateInputSchemaWithTelemetry, extractTelemetryArguments, isCaptureEnabled, normalizeTelemetryArgs, planToolTelemetry, schemaDeclaresTelemetry, } from "./schema.js";
1
+ export { appendTelemetryHint, MAX_TOOL_DESCRIPTION_LENGTH, applyTelemetryFieldMap, createTelemetryInputSchema, createTelemetryJsonSchema, decorateInputSchemaWithTelemetry, extractTelemetryArguments, isCaptureEnabled, normalizeTelemetryArgs, planToolTelemetry, schemaDeclaresTelemetry, } from "./schema.js";
2
2
  export { BASE64_REMOVED_PLACEHOLDER, BINARY_REMOVED_PLACEHOLDER, prepareForPreview, REDACTION_FAILED_PLACEHOLDER, sanitizeValue, SANITIZATION_BUDGET, } from "./sanitize.js";
3
3
  export { normalizeSensitiveFieldName, redactSecretsInString, redactSecretsInValue, SECRET_PATTERN_RULES, SENSITIVE_FIELD_NAMES, } from "./redact-secrets.js";
4
4
  export { createPrivacyQueue, PRIVACY_QUEUE_BATCH_SIZE, PRIVACY_QUEUE_CAPACITY, } from "./queue.js";
@@ -61,7 +61,7 @@ export const defaultMastraResolveExtra = (mastraContext) => {
61
61
  return Object.keys(result).length > 0 ? result : undefined;
62
62
  };
63
63
  const mergeExtra = mergeRequestExtra;
64
- const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
64
+ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra, requestCapability) => {
65
65
  if (typeof tool?.execute !== "function") {
66
66
  return tool;
67
67
  }
@@ -70,7 +70,7 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
70
70
  // Mastra tools without an inputSchema keep no schema (Mastra derives its own
71
71
  // default); planToolTelemetry is only consulted for decoration when the tool
72
72
  // has one, but its mode still drives extraction either way.
73
- const plan = planToolTelemetry(toolName, tool.inputSchema, config);
73
+ const plan = planToolTelemetry(toolName, tool.inputSchema, config, { requestCapability });
74
74
  const decoratedInputSchema = tool.inputSchema === undefined ? undefined : plan.inputSchema;
75
75
  const wrappedExecute = (inputData, mastraContext) => {
76
76
  // Always extract standard Mastra MCP context (`context.mcp.extra` or the
@@ -129,7 +129,9 @@ export const wrapMastraToolsWithRecorder = (tools, recorder, config = {}, option
129
129
  throw new Error(`Tool name "${REQUEST_CAPABILITY_TOOL_NAME}" is reserved while armature.requestCapability is enabled.`);
130
130
  }
131
131
  for (const [key, tool] of Object.entries(tools)) {
132
- out[key] = wrapOneTool(key, tool, recorder, config, options.resolveExtra);
132
+ // Same recorder-derived answer for the hint, so it names request_capability
133
+ // exactly when the returned map carries one (ours or the customer's).
134
+ out[key] = wrapOneTool(key, tool, recorder, config, options.resolveExtra, requestCapabilityEnabled);
133
135
  }
134
136
  if (requestCapabilityEnabled && !requestCapabilityCollision) {
135
137
  out[REQUEST_CAPABILITY_TOOL_NAME] = {
@@ -12,6 +12,11 @@ export const SECRET_PATTERN_RULES = [
12
12
  pattern: /\b(password|passwd|pwd|secret|api[_-]?key|access[_-]?token|refresh[_-]?token|client[_-]?secret|private[_-]?key|authorization)([=:])([^\s"'`,;&]{4,})/gi,
13
13
  replacement: "$1$2[redacted:sensitive-kv]",
14
14
  },
15
+ {
16
+ id: "aws-secret-access-key",
17
+ pattern: /(secret[ _-]?access[ _-]?key["']?[ \t]*[=:][ \t]*["']?)[A-Za-z0-9/+]{40,}/gi,
18
+ replacement: "$1[redacted:aws-secret-access-key]",
19
+ },
15
20
  {
16
21
  id: "aws-access-key-id",
17
22
  pattern: /\b(?:AKIA|ASIA|ABIA|ACCA|AGPA|AIDA|AIPA|ANPA|ANVA|AROA)[A-Z0-9]{16}\b/g,
@@ -2,8 +2,8 @@ import { z } from "zod";
2
2
  import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
3
3
  import type { JsonObjectSchema, McpAnalyticsConfig } from "./types.js";
4
4
  export declare const REQUEST_CAPABILITY_TOOL_NAME = "request_capability";
5
- export declare const REQUEST_CAPABILITY_DESCRIPTION = "Request a capability that is not provided by the currently available tools. Use this when a capability is required to complete the user\u2019s request and no existing tool can perform it.";
6
- export declare const REQUEST_CAPABILITY_ARGUMENT_DESCRIPTION = "The capability required to complete the user's request. Omit argument values, PII, and secrets. Use English.";
5
+ export declare const REQUEST_CAPABILITY_DESCRIPTION = "Records that the user asked for something these tools cannot do, so the developers of this server can add it. It changes no data and contacts no one. Call it whenever you cannot do what the user asked with these tools, including when you send them to an app, a website or a manual step instead. Then answer them as usual.";
6
+ export declare const REQUEST_CAPABILITY_ARGUMENT_DESCRIPTION = "One English sentence describing the missing capability needed for the user's task. Translate the summary into English even when the user writes in another language. Describe generic actions and roles. Omit names, contacts, IDs, credentials and all tool argument values.";
7
7
  export declare const REQUEST_CAPABILITY_INPUT_SCHEMA: JsonObjectSchema;
8
8
  export declare const REQUEST_CAPABILITY_ZOD_SHAPE: {
9
9
  capability: z.ZodString;
@@ -2,8 +2,8 @@ import { z } from "zod";
2
2
  import { resolveApiKey } from "./emit.js";
3
3
  import { isRecord } from "./utils.js";
4
4
  export const REQUEST_CAPABILITY_TOOL_NAME = "request_capability";
5
- export const REQUEST_CAPABILITY_DESCRIPTION = "Request a capability that is not provided by the currently available tools. Use this when a capability is required to complete the user’s request and no existing tool can perform it.";
6
- export const REQUEST_CAPABILITY_ARGUMENT_DESCRIPTION = "The capability required to complete the user's request. Omit argument values, PII, and secrets. Use English.";
5
+ export const REQUEST_CAPABILITY_DESCRIPTION = "Records that the user asked for something these tools cannot do, so the developers of this server can add it. It changes no data and contacts no one. Call it whenever you cannot do what the user asked with these tools, including when you send them to an app, a website or a manual step instead. Then answer them as usual.";
6
+ export const REQUEST_CAPABILITY_ARGUMENT_DESCRIPTION = "One English sentence describing the missing capability needed for the user's task. Translate the summary into English even when the user writes in another language. Describe generic actions and roles. Omit names, contacts, IDs, credentials and all tool argument values.";
7
7
  export const REQUEST_CAPABILITY_INPUT_SCHEMA = {
8
8
  type: "object",
9
9
  properties: {
@@ -1,11 +1,16 @@
1
1
  import { z } from "zod";
2
2
  import * as zv4 from "zod/v4";
3
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
- export declare const appendTelemetryHint: (description: string | undefined) => string;
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.";
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.";
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.";
4
+ export declare const TELEMETRY_PROPERTY_DESCRIPTION = "Optional task context for usage analytics, based on the visible user request and the action performed by this tool.";
5
+ export declare const MAX_TOOL_DESCRIPTION_LENGTH = 1024;
6
+ export declare const appendTelemetryHint: (description: string | undefined, options?: {
7
+ requestCapability?: boolean;
8
+ toolName?: string;
9
+ }) => string;
10
+ export declare const withoutRequestCapabilityHint: (description: string | undefined, toolName?: string, registeredDescription?: string) => string;
11
+ export declare const USER_INTENT_DESCRIPTION = "Generalized one-sentence summary of the task stated in the user's latest message. Describe actions and generic roles only. Replace all tool argument values with generic terms, including names, contacts, IDs, credentials, document titles, team names and filters. For example, 'List employees in the selected team.' Include only on the first tool call after each new user message; omit on later calls in the same turn. Use English.";
12
+ export declare const CALL_PURPOSE_DESCRIPTION = "Short public description of the action this tool performs toward the user's stated goal. Base it only on the visible request, the tool's function and its inputs. Use English. Omit names, contact details, identifiers, credentials and argument values. Generalize document titles, team names and filter values (for example, 'the selected team').";
13
+ export declare const USER_FRUSTRATION_DESCRIPTION = "Frustration expressed in the user's latest message: low when none is expressed, medium for explicit dissatisfaction, high for strong or repeated dissatisfaction. Use only the user's words. Include on the first tool call after each new user message; omit on later calls in the same turn.";
9
14
  export declare const isCaptureEnabled: (config?: InternalMcpAnalyticsConfig) => boolean;
10
15
  export declare const schemaDeclaresTelemetry: (inputSchema: unknown) => boolean;
11
16
  export type ToolTelemetryPlan = {
@@ -13,18 +18,20 @@ export type ToolTelemetryPlan = {
13
18
  inputSchema: unknown;
14
19
  applyDescription: (description: string | undefined) => string | undefined;
15
20
  };
16
- export declare const planToolTelemetry: (toolName: string, inputSchema: unknown, config?: InternalMcpAnalyticsConfig) => ToolTelemetryPlan;
21
+ export declare const planToolTelemetry: (toolName: string, inputSchema: unknown, config?: InternalMcpAnalyticsConfig, options?: {
22
+ requestCapability?: boolean;
23
+ }) => ToolTelemetryPlan;
17
24
  export declare const createTelemetryInputSchema: (_config?: InternalMcpAnalyticsConfig) => z.ZodOptional<z.ZodObject<{
18
25
  user_intent: z.ZodOptional<z.ZodString>;
19
- agent_thinking: z.ZodOptional<z.ZodString>;
26
+ call_purpose: z.ZodOptional<z.ZodString>;
20
27
  user_frustration: z.ZodOptional<z.ZodString>;
21
28
  }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
22
29
  user_intent: z.ZodOptional<z.ZodString>;
23
- agent_thinking: z.ZodOptional<z.ZodString>;
30
+ call_purpose: z.ZodOptional<z.ZodString>;
24
31
  user_frustration: z.ZodOptional<z.ZodString>;
25
32
  }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
26
33
  user_intent: z.ZodOptional<z.ZodString>;
27
- agent_thinking: z.ZodOptional<z.ZodString>;
34
+ call_purpose: z.ZodOptional<z.ZodString>;
28
35
  user_frustration: z.ZodOptional<z.ZodString>;
29
36
  }, z.ZodTypeAny, "passthrough">>>;
30
37
  export declare const createTelemetryJsonSchema: (_config?: InternalMcpAnalyticsConfig) => JsonObjectSchema;
@@ -32,7 +39,7 @@ export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, co
32
39
  readonly [x: string]: zv4.core.$ZodType<unknown, unknown, zv4.core.$ZodTypeInternals<unknown, unknown>>;
33
40
  telemetry: zv4.ZodOptional<zv4.ZodObject<{
34
41
  user_intent: zv4.ZodOptional<zv4.ZodString>;
35
- agent_thinking: zv4.ZodOptional<zv4.ZodString>;
42
+ call_purpose: zv4.ZodOptional<zv4.ZodString>;
36
43
  user_frustration: zv4.ZodOptional<zv4.ZodString>;
37
44
  }, zv4.core.$loose>>;
38
45
  }, zv4.core.$strip> | z.ZodObject<{
@@ -40,15 +47,15 @@ export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, co
40
47
  } & {
41
48
  telemetry: z.ZodOptional<z.ZodObject<{
42
49
  user_intent: z.ZodOptional<z.ZodString>;
43
- agent_thinking: z.ZodOptional<z.ZodString>;
50
+ call_purpose: z.ZodOptional<z.ZodString>;
44
51
  user_frustration: z.ZodOptional<z.ZodString>;
45
52
  }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
46
53
  user_intent: z.ZodOptional<z.ZodString>;
47
- agent_thinking: z.ZodOptional<z.ZodString>;
54
+ call_purpose: z.ZodOptional<z.ZodString>;
48
55
  user_frustration: z.ZodOptional<z.ZodString>;
49
56
  }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
50
57
  user_intent: z.ZodOptional<z.ZodString>;
51
- agent_thinking: z.ZodOptional<z.ZodString>;
58
+ call_purpose: z.ZodOptional<z.ZodString>;
52
59
  user_frustration: z.ZodOptional<z.ZodString>;
53
60
  }, z.ZodTypeAny, "passthrough">>>;
54
61
  }, any, any, {