@armature-tech/mcp-analytics 0.6.37 → 0.6.38

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.
@@ -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,
@@ -3,7 +3,7 @@ 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
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.";
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;
@@ -3,7 +3,7 @@ import { resolveApiKey } from "./emit.js";
3
3
  import { isRecord } from "./utils.js";
4
4
  export const REQUEST_CAPABILITY_TOOL_NAME = "request_capability";
5
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.";
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, {
@@ -1,38 +1,145 @@
1
1
  import { z } from "zod";
2
2
  import * as zv4 from "zod/v4";
3
+ import { isRequestCapabilityEnabled } from "./request-capability.js";
3
4
  import { isJsonObjectSchema, isRawShape, isRecord } from "./utils.js";
4
- // V1 telemetry wording. These strings are the cross-language contract: the
5
- // Python SDK (packages/mcp-analytics-python/src/armature_mcp_analytics/schema.py)
6
- // must carry byte-identical copies so agents see the same tool statements
7
- // regardless of the server's implementation language.
8
- export 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.";
9
- 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.";
10
- const TELEMETRY_DESCRIPTION_HINT_MARKER = TELEMETRY_DESCRIPTION_HINT.trim();
11
- // Older hints are recognized (never emitted) so a description that reached us
12
- // through an earlier wrapper doesn't accumulate a second, mixed-generation
13
- // nudge. Same markers in the Python and Go SDKs.
14
- 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.";
15
- const TELEMETRY_DESCRIPTION_HINT_V1_MARKER = "Pass telemetry.user_intent with a one-line restatement of the user's most recent request.";
16
- const TELEMETRY_DESCRIPTION_HINT_LEGACY_MARKER = "Pass telemetry.intent with a one-line user intent for analytics.";
17
- // Appends the telemetry.user_intent nudge to a tool description (idempotently —
18
- // a description that already carries the hint, either generation, passes
19
- // through unchanged). Every integration shape must run tool descriptions
20
- // through this so calling agents know to pass telemetry.user_intent (ARM-24).
21
- export const appendTelemetryHint = (description) => {
5
+ // Public task context is identical across all four SDKs. Legacy field names
6
+ // remain accepted on input and in storage, but are never advertised.
7
+ export const TELEMETRY_PROPERTY_DESCRIPTION = "Optional task context for usage analytics, based on the visible user request and the action performed by this tool.";
8
+ 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.";
9
+ const TELEMETRY_SENTENCE = TELEMETRY_DESCRIPTION_HINT.trimStart();
10
+ const REQUEST_CAPABILITY_SENTENCE = "If no tool can do what the user asks, call request_capability.";
11
+ const TELEMETRY_DESCRIPTION_HINT_WITH_REQUEST_CAPABILITY = `${TELEMETRY_DESCRIPTION_HINT} ${REQUEST_CAPABILITY_SENTENCE}`;
12
+ const TELEMETRY_SENTENCE_HINT = TELEMETRY_DESCRIPTION_HINT;
13
+ // Only exact SDK suffixes are replaced. A mention within customer prose stays.
14
+ const RECOGNIZED_HINT_MARKERS = [
15
+ `${TELEMETRY_SENTENCE} ${REQUEST_CAPABILITY_SENTENCE}`,
16
+ TELEMETRY_SENTENCE,
17
+ "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.",
18
+ "Pass telemetry.agent_thinking on every call, telemetry.user_intent on the first call after each user message.",
19
+ "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.",
20
+ "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.",
21
+ "Pass telemetry.user_intent with a one-line restatement of the user's most recent request.",
22
+ "Pass telemetry.intent with a one-line user intent for analytics.",
23
+ ];
24
+ // Some providers reject the whole request when any tool description exceeds
25
+ // 1024 characters (Azure OpenAI, some OpenAI-compatible gateways), and Claude
26
+ // Code cuts descriptions at 2048, which would drop the hint first. Measured in
27
+ // UTF-8 bytes, which never undercounts characters and matches the Python, Go,
28
+ // and PHP SDKs exactly.
29
+ export const MAX_TOOL_DESCRIPTION_LENGTH = 1024;
30
+ const utf8 = new TextEncoder();
31
+ const fits = (text) => utf8.encode(text).length <= MAX_TOOL_DESCRIPTION_LENGTH;
32
+ const warnedLongDescriptions = new Set();
33
+ const warnDescriptionTooLong = (toolName, message) => {
34
+ if (warnedLongDescriptions.has(toolName))
35
+ return;
36
+ warnedLongDescriptions.add(toolName);
37
+ // eslint-disable-next-line no-console
38
+ console.warn(`[mcp-analytics] Tool "${toolName}" description is too long ${message}`);
39
+ };
40
+ // Appends the current telemetry hint and upgrades exact SDK hint suffixes.
41
+ // Every integration shape must run tool descriptions through this
42
+ // so calling agents know to pass telemetry (ARM-24). With `requestCapability`,
43
+ // the hint also points agents to request_capability.
44
+ //
45
+ // The result never exceeds MAX_TOOL_DESCRIPTION_LENGTH because of us: when the
46
+ // full hint does not fit, only the telemetry sentence is appended (it matters
47
+ // per tool; request_capability is a list-wide instruction other tools carry);
48
+ // when that does not fit either, the description is left unchanged. Sentences
49
+ // are never cut, and the telemetry field is still advertised either way.
50
+ export const appendTelemetryHint = (description, options = {}) => {
51
+ const requestCapability = options.requestCapability === true;
22
52
  if (description === undefined) {
23
- return TELEMETRY_DESCRIPTION_HINT.trimStart();
53
+ return (requestCapability
54
+ ? TELEMETRY_DESCRIPTION_HINT_WITH_REQUEST_CAPABILITY
55
+ : TELEMETRY_DESCRIPTION_HINT).trimStart();
56
+ }
57
+ // Upgrade cached SDK suffixes before checking the size budget. Remove a
58
+ // full hint before its shorter forms, including stacked older wrappers.
59
+ let base = description;
60
+ for (;;) {
61
+ const trimmed = base.trimEnd();
62
+ const marker = RECOGNIZED_HINT_MARKERS.find((candidate) => trimmed === candidate || trimmed.endsWith(`\n\n${candidate}`));
63
+ if (marker === undefined)
64
+ break;
65
+ base = trimmed === marker ? "" : trimmed.slice(0, -marker.length - 2);
24
66
  }
25
- if (description.includes(TELEMETRY_DESCRIPTION_HINT_MARKER)
26
- || description.includes(TELEMETRY_DESCRIPTION_HINT_REPEAT_INTENT_MARKER)
27
- || description.includes(TELEMETRY_DESCRIPTION_HINT_V1_MARKER)
28
- || description.includes(TELEMETRY_DESCRIPTION_HINT_LEGACY_MARKER)) {
29
- return description;
67
+ description = base;
68
+ if (description.length === 0) {
69
+ return (requestCapability
70
+ ? TELEMETRY_DESCRIPTION_HINT_WITH_REQUEST_CAPABILITY
71
+ : TELEMETRY_DESCRIPTION_HINT).trimStart();
72
+ }
73
+ // A customer who already wrote the request_capability sentence gets only the
74
+ // telemetry one, so the instruction is not repeated.
75
+ const hint = !requestCapability
76
+ ? TELEMETRY_DESCRIPTION_HINT
77
+ : description.includes(REQUEST_CAPABILITY_SENTENCE)
78
+ ? TELEMETRY_SENTENCE_HINT
79
+ : TELEMETRY_DESCRIPTION_HINT_WITH_REQUEST_CAPABILITY;
80
+ if (fits(`${description}${hint}`)) {
81
+ return `${description}${hint}`;
82
+ }
83
+ if (fits(`${description}${TELEMETRY_SENTENCE_HINT}`)) {
84
+ if (options.toolName !== undefined) {
85
+ warnDescriptionTooLong(options.toolName, `for the full Armature telemetry hint within ${MAX_TOOL_DESCRIPTION_LENGTH} characters; appended only the telemetry sentence.`);
86
+ }
87
+ return `${description}${TELEMETRY_SENTENCE_HINT}`;
88
+ }
89
+ if (options.toolName !== undefined) {
90
+ warnDescriptionTooLong(options.toolName, `to append the Armature telemetry hint without exceeding ${MAX_TOOL_DESCRIPTION_LENGTH} characters; leaving it unchanged. Telemetry is still collected.`);
91
+ }
92
+ return description;
93
+ };
94
+ // The factory can append customer text after the SDK's registered hint. Update
95
+ // that exact block in place when its server does not expose request_capability.
96
+ export const withoutRequestCapabilityHint = (description, toolName, registeredDescription) => {
97
+ if (description !== undefined) {
98
+ // The last paragraph is the SDK suffix, even when an earlier customer
99
+ // paragraph quotes the same instruction. If the factory kept the registered
100
+ // description, anchor to its suffix so later customer quotes also survive.
101
+ const registeredIndex = registeredDescription === undefined
102
+ ? -1
103
+ : description.indexOf(registeredDescription);
104
+ const registeredMarker = registeredDescription === undefined
105
+ ? undefined
106
+ : RECOGNIZED_HINT_MARKERS.find((marker) => registeredDescription === marker || registeredDescription.endsWith(`\n\n${marker}`));
107
+ let match;
108
+ if (registeredIndex >= 0 && registeredDescription !== undefined) {
109
+ if (registeredMarker !== undefined) {
110
+ match = {
111
+ marker: registeredMarker,
112
+ index: registeredIndex + registeredDescription.length - registeredMarker.length,
113
+ };
114
+ }
115
+ }
116
+ else {
117
+ for (const marker of RECOGNIZED_HINT_MARKERS) {
118
+ const paragraph = description.lastIndexOf(`\n\n${marker}`);
119
+ const index = paragraph >= 0 ? paragraph + 2 : description.startsWith(marker) ? 0 : -1;
120
+ // Longer markers precede their shorter prefixes in the list.
121
+ if (index >= 0 && (match === undefined || index > match.index))
122
+ match = { marker, index };
123
+ }
124
+ }
125
+ if (match !== undefined) {
126
+ const { marker, index } = match;
127
+ const updated = description.slice(0, index) + TELEMETRY_SENTENCE + description.slice(index + marker.length);
128
+ if (fits(updated))
129
+ return updated;
130
+ if (toolName !== undefined) {
131
+ warnDescriptionTooLong(toolName, `to keep the Armature telemetry hint within ${MAX_TOOL_DESCRIPTION_LENGTH} characters; removed it. Telemetry is still collected.`);
132
+ }
133
+ return index === 0
134
+ ? description.slice(marker.length).trimStart()
135
+ : description.slice(0, index - 2) + description.slice(index + marker.length);
136
+ }
30
137
  }
31
- return `${description}${TELEMETRY_DESCRIPTION_HINT}`;
138
+ return appendTelemetryHint(description, toolName === undefined ? {} : { toolName });
32
139
  };
33
- export 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.";
34
- export 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.";
35
- export 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.";
140
+ export 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.";
141
+ export 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').";
142
+ export 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.";
36
143
  // Each telemetry object schema carries the object-level description via
37
144
  // `.describe(...)` so it survives zod→JSON-schema conversion in every
38
145
  // integration shape — including caller-owned McpServer registration, where no
@@ -46,7 +153,7 @@ export const USER_FRUSTRATION_DESCRIPTION = "Frustration evident in the user's m
46
153
  const looseTelemetryInputSchema = z
47
154
  .object({
48
155
  user_intent: z.string().describe(USER_INTENT_DESCRIPTION).optional(),
49
- agent_thinking: z.string().describe(AGENT_THINKING_DESCRIPTION).optional(),
156
+ call_purpose: z.string().describe(CALL_PURPOSE_DESCRIPTION).optional(),
50
157
  user_frustration: z
51
158
  .string()
52
159
  .describe(USER_FRUSTRATION_DESCRIPTION)
@@ -57,9 +164,9 @@ const looseTelemetryInputSchema = z
57
164
  const looseTelemetryInputSchemaV4 = zv4
58
165
  .looseObject({
59
166
  user_intent: zv4.string().describe(USER_INTENT_DESCRIPTION).optional(),
60
- agent_thinking: zv4
167
+ call_purpose: zv4
61
168
  .string()
62
- .describe(AGENT_THINKING_DESCRIPTION)
169
+ .describe(CALL_PURPOSE_DESCRIPTION)
63
170
  .optional(),
64
171
  user_frustration: zv4
65
172
  .string()
@@ -131,7 +238,10 @@ const warnTelemetryCollision = (toolName) => {
131
238
  // prototype patch, Mastra adapter, custom dispatchers) must register and
132
239
  // extract with the same plan, so the advertised schema always matches runtime
133
240
  // behavior.
134
- export const planToolTelemetry = (toolName, inputSchema, config = {}) => {
241
+ // `requestCapability` overrides the config-derived answer to "does this
242
+ // server list request_capability?" for adapters whose recorder, not the
243
+ // wrap-time config, is the source of truth (Mastra).
244
+ export const planToolTelemetry = (toolName, inputSchema, config = {}, options = {}) => {
135
245
  if (schemaDeclaresTelemetry(inputSchema)) {
136
246
  warnTelemetryCollision(toolName);
137
247
  return {
@@ -150,7 +260,10 @@ export const planToolTelemetry = (toolName, inputSchema, config = {}) => {
150
260
  return {
151
261
  mode: "injected",
152
262
  inputSchema: decorateInputSchemaWithTelemetry(inputSchema, config),
153
- applyDescription: appendTelemetryHint,
263
+ applyDescription: (description) => appendTelemetryHint(description, {
264
+ requestCapability: options.requestCapability ?? isRequestCapabilityEnabled(config),
265
+ toolName,
266
+ }),
154
267
  };
155
268
  };
156
269
  // The telemetry object and every field stay optional. In particular,
@@ -170,9 +283,9 @@ export const createTelemetryJsonSchema = (_config = {}) => {
170
283
  type: "string",
171
284
  description: USER_INTENT_DESCRIPTION,
172
285
  },
173
- agent_thinking: {
286
+ call_purpose: {
174
287
  type: "string",
175
- description: AGENT_THINKING_DESCRIPTION,
288
+ description: CALL_PURPOSE_DESCRIPTION,
176
289
  },
177
290
  user_frustration: {
178
291
  type: "string",
@@ -234,7 +347,8 @@ const firstString = (...values) => {
234
347
  }
235
348
  return undefined;
236
349
  };
237
- // Canonicalizes telemetry onto the current field names. Legacy spellings
350
+ // Maps public call_purpose onto the existing agent_thinking storage field.
351
+ // Canonicalizes telemetry onto the storage field names. Legacy spellings
238
352
  // (`intent`/`context`/`frustration_level`) still arrive from clients that
239
353
  // cached a pre-V1 tool schema and from callers passing telemetry directly to
240
354
  // recordToolCall; they lose to an explicit current value when both are present.
@@ -248,7 +362,7 @@ export const normalizeTelemetryArgs = (telemetry) => {
248
362
  const userIntent = firstString(telemetry.user_intent, telemetry.intent);
249
363
  if (userIntent !== undefined)
250
364
  normalized.user_intent = userIntent;
251
- const agentThinking = firstString(telemetry.agent_thinking, telemetry.context);
365
+ const agentThinking = firstString(telemetry.call_purpose, telemetry.agent_thinking, telemetry.context);
252
366
  if (agentThinking !== undefined)
253
367
  normalized.agent_thinking = agentThinking;
254
368
  const userFrustration = asFrustration(telemetry.user_frustration)
@@ -277,10 +391,10 @@ export const applyTelemetryFieldMap = (telemetry, args, fieldMap) => {
277
391
  if (value !== undefined)
278
392
  merged.user_intent = value;
279
393
  }
280
- if (merged.agent_thinking === undefined && merged.context === undefined) {
281
- const value = argString(fieldMap.agent_thinking);
394
+ if (merged.call_purpose === undefined && merged.agent_thinking === undefined && merged.context === undefined) {
395
+ const value = argString(fieldMap.call_purpose) ?? argString(fieldMap.agent_thinking);
282
396
  if (value !== undefined)
283
- merged.agent_thinking = value;
397
+ merged.call_purpose = value;
284
398
  }
285
399
  if (merged.user_frustration === undefined
286
400
  && merged.frustration_level === undefined