@armature-tech/mcp-analytics 0.6.36 → 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.
@@ -33,43 +33,151 @@ 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 = "If no tool can do what the user asks, call request_capability.";
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,
53
+ "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.",
54
+ "Pass telemetry.agent_thinking on every call, telemetry.user_intent on the first call after each user message.",
55
+ "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.",
56
+ "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.",
57
+ "Pass telemetry.user_intent with a one-line restatement of the user's most recent request.",
58
+ "Pass telemetry.intent with a one-line user intent for analytics.",
59
+ ];
60
+ // Some providers reject the whole request when any tool description exceeds
61
+ // 1024 characters (Azure OpenAI, some OpenAI-compatible gateways), and Claude
62
+ // Code cuts descriptions at 2048, which would drop the hint first. Measured in
63
+ // UTF-8 bytes, which never undercounts characters and matches the Python, Go,
64
+ // and PHP SDKs exactly.
65
+ exports.MAX_TOOL_DESCRIPTION_LENGTH = 1024;
66
+ const utf8 = new TextEncoder();
67
+ const fits = (text) => utf8.encode(text).length <= exports.MAX_TOOL_DESCRIPTION_LENGTH;
68
+ const warnedLongDescriptions = new Set();
69
+ const warnDescriptionTooLong = (toolName, message) => {
70
+ if (warnedLongDescriptions.has(toolName))
71
+ return;
72
+ warnedLongDescriptions.add(toolName);
73
+ // eslint-disable-next-line no-console
74
+ console.warn(`[mcp-analytics] Tool "${toolName}" description is too long ${message}`);
75
+ };
76
+ // Appends the current telemetry hint and upgrades exact SDK hint suffixes.
77
+ // Every integration shape must run tool descriptions through this
78
+ // so calling agents know to pass telemetry (ARM-24). With `requestCapability`,
79
+ // the hint also points agents to request_capability.
80
+ //
81
+ // The result never exceeds MAX_TOOL_DESCRIPTION_LENGTH because of us: when the
82
+ // full hint does not fit, only the telemetry sentence is appended (it matters
83
+ // per tool; request_capability is a list-wide instruction other tools carry);
84
+ // when that does not fit either, the description is left unchanged. Sentences
85
+ // are never cut, and the telemetry field is still advertised either way.
86
+ const appendTelemetryHint = (description, options = {}) => {
87
+ const requestCapability = options.requestCapability === true;
58
88
  if (description === undefined) {
59
- return TELEMETRY_DESCRIPTION_HINT.trimStart();
89
+ return (requestCapability
90
+ ? TELEMETRY_DESCRIPTION_HINT_WITH_REQUEST_CAPABILITY
91
+ : TELEMETRY_DESCRIPTION_HINT).trimStart();
92
+ }
93
+ // Upgrade cached SDK suffixes before checking the size budget. Remove a
94
+ // full hint before its shorter forms, including stacked older wrappers.
95
+ let base = description;
96
+ for (;;) {
97
+ const trimmed = base.trimEnd();
98
+ const marker = RECOGNIZED_HINT_MARKERS.find((candidate) => trimmed === candidate || trimmed.endsWith(`\n\n${candidate}`));
99
+ if (marker === undefined)
100
+ break;
101
+ base = trimmed === marker ? "" : trimmed.slice(0, -marker.length - 2);
60
102
  }
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;
103
+ description = base;
104
+ if (description.length === 0) {
105
+ return (requestCapability
106
+ ? TELEMETRY_DESCRIPTION_HINT_WITH_REQUEST_CAPABILITY
107
+ : TELEMETRY_DESCRIPTION_HINT).trimStart();
66
108
  }
67
- return `${description}${TELEMETRY_DESCRIPTION_HINT}`;
109
+ // A customer who already wrote the request_capability sentence gets only the
110
+ // telemetry one, so the instruction is not repeated.
111
+ const hint = !requestCapability
112
+ ? TELEMETRY_DESCRIPTION_HINT
113
+ : description.includes(REQUEST_CAPABILITY_SENTENCE)
114
+ ? TELEMETRY_SENTENCE_HINT
115
+ : TELEMETRY_DESCRIPTION_HINT_WITH_REQUEST_CAPABILITY;
116
+ if (fits(`${description}${hint}`)) {
117
+ return `${description}${hint}`;
118
+ }
119
+ if (fits(`${description}${TELEMETRY_SENTENCE_HINT}`)) {
120
+ if (options.toolName !== undefined) {
121
+ warnDescriptionTooLong(options.toolName, `for the full Armature telemetry hint within ${exports.MAX_TOOL_DESCRIPTION_LENGTH} characters; appended only the telemetry sentence.`);
122
+ }
123
+ return `${description}${TELEMETRY_SENTENCE_HINT}`;
124
+ }
125
+ if (options.toolName !== undefined) {
126
+ warnDescriptionTooLong(options.toolName, `to append the Armature telemetry hint without exceeding ${exports.MAX_TOOL_DESCRIPTION_LENGTH} characters; leaving it unchanged. Telemetry is still collected.`);
127
+ }
128
+ return description;
68
129
  };
69
130
  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.";
131
+ // The factory can append customer text after the SDK's registered hint. Update
132
+ // that exact block in place when its server does not expose request_capability.
133
+ const withoutRequestCapabilityHint = (description, toolName, registeredDescription) => {
134
+ if (description !== undefined) {
135
+ // The last paragraph is the SDK suffix, even when an earlier customer
136
+ // paragraph quotes the same instruction. If the factory kept the registered
137
+ // description, anchor to its suffix so later customer quotes also survive.
138
+ const registeredIndex = registeredDescription === undefined
139
+ ? -1
140
+ : description.indexOf(registeredDescription);
141
+ const registeredMarker = registeredDescription === undefined
142
+ ? undefined
143
+ : RECOGNIZED_HINT_MARKERS.find((marker) => registeredDescription === marker || registeredDescription.endsWith(`\n\n${marker}`));
144
+ let match;
145
+ if (registeredIndex >= 0 && registeredDescription !== undefined) {
146
+ if (registeredMarker !== undefined) {
147
+ match = {
148
+ marker: registeredMarker,
149
+ index: registeredIndex + registeredDescription.length - registeredMarker.length,
150
+ };
151
+ }
152
+ }
153
+ else {
154
+ for (const marker of RECOGNIZED_HINT_MARKERS) {
155
+ const paragraph = description.lastIndexOf(`\n\n${marker}`);
156
+ const index = paragraph >= 0 ? paragraph + 2 : description.startsWith(marker) ? 0 : -1;
157
+ // Longer markers precede their shorter prefixes in the list.
158
+ if (index >= 0 && (match === undefined || index > match.index))
159
+ match = { marker, index };
160
+ }
161
+ }
162
+ if (match !== undefined) {
163
+ const { marker, index } = match;
164
+ const updated = description.slice(0, index) + TELEMETRY_SENTENCE + description.slice(index + marker.length);
165
+ if (fits(updated))
166
+ return updated;
167
+ if (toolName !== undefined) {
168
+ warnDescriptionTooLong(toolName, `to keep the Armature telemetry hint within ${exports.MAX_TOOL_DESCRIPTION_LENGTH} characters; removed it. Telemetry is still collected.`);
169
+ }
170
+ return index === 0
171
+ ? description.slice(marker.length).trimStart()
172
+ : description.slice(0, index - 2) + description.slice(index + marker.length);
173
+ }
174
+ }
175
+ return (0, exports.appendTelemetryHint)(description, toolName === undefined ? {} : { toolName });
176
+ };
177
+ exports.withoutRequestCapabilityHint = withoutRequestCapabilityHint;
178
+ 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.";
179
+ 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').";
180
+ 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
181
  // Each telemetry object schema carries the object-level description via
74
182
  // `.describe(...)` so it survives zod→JSON-schema conversion in every
75
183
  // integration shape — including caller-owned McpServer registration, where no
@@ -83,7 +191,7 @@ exports.USER_FRUSTRATION_DESCRIPTION = "Frustration evident in the user's most r
83
191
  const looseTelemetryInputSchema = zod_1.z
84
192
  .object({
85
193
  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(),
194
+ call_purpose: zod_1.z.string().describe(exports.CALL_PURPOSE_DESCRIPTION).optional(),
87
195
  user_frustration: zod_1.z
88
196
  .string()
89
197
  .describe(exports.USER_FRUSTRATION_DESCRIPTION)
@@ -94,9 +202,9 @@ const looseTelemetryInputSchema = zod_1.z
94
202
  const looseTelemetryInputSchemaV4 = zv4
95
203
  .looseObject({
96
204
  user_intent: zv4.string().describe(exports.USER_INTENT_DESCRIPTION).optional(),
97
- agent_thinking: zv4
205
+ call_purpose: zv4
98
206
  .string()
99
- .describe(exports.AGENT_THINKING_DESCRIPTION)
207
+ .describe(exports.CALL_PURPOSE_DESCRIPTION)
100
208
  .optional(),
101
209
  user_frustration: zv4
102
210
  .string()
@@ -170,7 +278,10 @@ const warnTelemetryCollision = (toolName) => {
170
278
  // prototype patch, Mastra adapter, custom dispatchers) must register and
171
279
  // extract with the same plan, so the advertised schema always matches runtime
172
280
  // behavior.
173
- const planToolTelemetry = (toolName, inputSchema, config = {}) => {
281
+ // `requestCapability` overrides the config-derived answer to "does this
282
+ // server list request_capability?" for adapters whose recorder, not the
283
+ // wrap-time config, is the source of truth (Mastra).
284
+ const planToolTelemetry = (toolName, inputSchema, config = {}, options = {}) => {
174
285
  if ((0, exports.schemaDeclaresTelemetry)(inputSchema)) {
175
286
  warnTelemetryCollision(toolName);
176
287
  return {
@@ -189,7 +300,10 @@ const planToolTelemetry = (toolName, inputSchema, config = {}) => {
189
300
  return {
190
301
  mode: "injected",
191
302
  inputSchema: (0, exports.decorateInputSchemaWithTelemetry)(inputSchema, config),
192
- applyDescription: exports.appendTelemetryHint,
303
+ applyDescription: (description) => (0, exports.appendTelemetryHint)(description, {
304
+ requestCapability: options.requestCapability ?? (0, request_capability_js_1.isRequestCapabilityEnabled)(config),
305
+ toolName,
306
+ }),
193
307
  };
194
308
  };
195
309
  exports.planToolTelemetry = planToolTelemetry;
@@ -211,9 +325,9 @@ const createTelemetryJsonSchema = (_config = {}) => {
211
325
  type: "string",
212
326
  description: exports.USER_INTENT_DESCRIPTION,
213
327
  },
214
- agent_thinking: {
328
+ call_purpose: {
215
329
  type: "string",
216
- description: exports.AGENT_THINKING_DESCRIPTION,
330
+ description: exports.CALL_PURPOSE_DESCRIPTION,
217
331
  },
218
332
  user_frustration: {
219
333
  type: "string",
@@ -277,7 +391,8 @@ const firstString = (...values) => {
277
391
  }
278
392
  return undefined;
279
393
  };
280
- // Canonicalizes telemetry onto the current field names. Legacy spellings
394
+ // Maps public call_purpose onto the existing agent_thinking storage field.
395
+ // Canonicalizes telemetry onto the storage field names. Legacy spellings
281
396
  // (`intent`/`context`/`frustration_level`) still arrive from clients that
282
397
  // cached a pre-V1 tool schema and from callers passing telemetry directly to
283
398
  // recordToolCall; they lose to an explicit current value when both are present.
@@ -291,7 +406,7 @@ const normalizeTelemetryArgs = (telemetry) => {
291
406
  const userIntent = firstString(telemetry.user_intent, telemetry.intent);
292
407
  if (userIntent !== undefined)
293
408
  normalized.user_intent = userIntent;
294
- const agentThinking = firstString(telemetry.agent_thinking, telemetry.context);
409
+ const agentThinking = firstString(telemetry.call_purpose, telemetry.agent_thinking, telemetry.context);
295
410
  if (agentThinking !== undefined)
296
411
  normalized.agent_thinking = agentThinking;
297
412
  const userFrustration = asFrustration(telemetry.user_frustration)
@@ -321,10 +436,10 @@ const applyTelemetryFieldMap = (telemetry, args, fieldMap) => {
321
436
  if (value !== undefined)
322
437
  merged.user_intent = value;
323
438
  }
324
- if (merged.agent_thinking === undefined && merged.context === undefined) {
325
- const value = argString(fieldMap.agent_thinking);
439
+ if (merged.call_purpose === undefined && merged.agent_thinking === undefined && merged.context === undefined) {
440
+ const value = argString(fieldMap.call_purpose) ?? argString(fieldMap.agent_thinking);
326
441
  if (value !== undefined)
327
- merged.agent_thinking = value;
442
+ merged.call_purpose = value;
328
443
  }
329
444
  if (merged.user_frustration === undefined
330
445
  && 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;
@@ -5,8 +5,12 @@ export declare const buildStatelessSessionId: (clientInfo?: McpClientInfo, sessi
5
5
  export declare const parseStatelessSessionClientInfo: (sessionId: string | undefined) => McpClientInfo | undefined;
6
6
  export declare const clientInfoFromInitializeBody: (body: unknown) => McpClientInfo | undefined;
7
7
  export type StatelessHttpSession = {
8
- /** Stable session id: minted at initialize, parsed from the echoed header otherwise. */
9
- sessionId: string;
8
+ /**
9
+ * Stable session id: minted at initialize, parsed from the echoed header
10
+ * otherwise. Undefined when the request carries neither — see
11
+ * `resolveStatelessHttpSession`.
12
+ */
13
+ sessionId?: string;
10
14
  /** Client identity recovered from the echoed session id (tool-call requests only). */
11
15
  clientInfo?: McpClientInfo;
12
16
  /**
@@ -17,10 +21,20 @@ export type StatelessHttpSession = {
17
21
  sessionIdGenerator?: () => string;
18
22
  /** True when the request (or any message in a batch) is `initialize`. */
19
23
  isInitialize: boolean;
20
- /** Spread into `dispatch(name, args, { ctx, ...dispatchContext })`. */
24
+ /**
25
+ * Spread into `dispatch(name, args, { ctx, ...dispatchContext })`.
26
+ *
27
+ * When there is no session id the request headers ride along instead. The
28
+ * recorder reads "no session id AND no headers" as "no HTTP request at
29
+ * all" and falls back to the process-scoped stdio id, which would merge
30
+ * every concurrent conversation in a long-lived server into one session.
31
+ * Passing the headers keeps the request identifiable as HTTP-with-no-id,
32
+ * so the event ships a null hint and ingest groups it.
33
+ */
21
34
  dispatchContext: {
22
- sessionId: string;
35
+ sessionId?: string;
23
36
  clientInfo?: McpClientInfo;
37
+ headers?: HeaderBag;
24
38
  };
25
39
  };
26
40
  export declare const resolveStatelessHttpSession: (input: {
@@ -113,8 +113,20 @@ const resolveStatelessHttpSession = (input) => {
113
113
  dispatchContext: { sessionId },
114
114
  };
115
115
  }
116
- const echoed = (0, utils_js_1.headerValue)(input.headers, "mcp-session-id");
117
- const sessionId = echoed?.trim() || (0, node_crypto_1.randomUUID)();
116
+ const sessionId = (0, utils_js_1.headerValue)(input.headers, "mcp-session-id")?.trim();
117
+ if (!sessionId) {
118
+ // No initialize to mint from and no echo to recover: either modern-era
119
+ // traffic (identified through `_meta` / the session seed) or a client
120
+ // that drops the header. Minting here would stamp a distinct id on every
121
+ // POST, and ingest trusts an explicit hint, so each tool call would land
122
+ // in its own single-event session. Reporting no id ships
123
+ // `session_id_hint: null` and lets ingest group by actor + client with
124
+ // its inactivity window instead. Matches the Go SDK's empty session id.
125
+ return {
126
+ isInitialize: false,
127
+ dispatchContext: input.headers ? { headers: input.headers } : {},
128
+ };
129
+ }
118
130
  const clientInfo = (0, exports.parseStatelessSessionClientInfo)(sessionId);
119
131
  return {
120
132
  sessionId,
@@ -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),
@@ -596,7 +596,10 @@ const wrapMcpHandler = (handler, config) => {
596
596
  }
597
597
  }
598
598
  const response = await originalFetch(request, ...rest);
599
- if (session?.isInitialize && response.ok) {
599
+ // `sessionId` is always minted on initialize; the check narrows the type
600
+ // for the non-initialize case, where it is now optional.
601
+ if (session?.isInitialize && session.sessionId && response.ok) {
602
+ const mintedSessionId = session.sessionId;
600
603
  // Full-fidelity clientInfo from the initialize body: the minted id only
601
604
  // carries name/version, so without this the session_init would lose the
602
605
  // negotiated protocolVersion (and capabilities) — recorded here even
@@ -605,12 +608,12 @@ const wrapMcpHandler = (handler, config) => {
605
608
  const clientInfo = (0, stateless_http_js_1.clientInfoFromInitializeBody)(body);
606
609
  try {
607
610
  await state.core.recordSessionInit({
608
- sessionId: session.sessionId,
611
+ sessionId: mintedSessionId,
609
612
  headers: request.headers,
610
613
  ...(clientInfo !== undefined ? { clientInfo } : {}),
611
614
  ...(authInfo !== undefined ? { authInfo } : {}),
612
615
  extra: {
613
- sessionId: session.sessionId,
616
+ sessionId: mintedSessionId,
614
617
  requestInfo: { headers: request.headers },
615
618
  ...(authInfo !== undefined ? { authInfo } : {}),
616
619
  },
@@ -619,7 +622,7 @@ const wrapMcpHandler = (handler, config) => {
619
622
  catch {
620
623
  // Recording is best-effort; never break the MCP response over it.
621
624
  }
622
- return withSessionIdHeader(response, session.sessionId);
625
+ return withSessionIdHeader(response, mintedSessionId);
623
626
  }
624
627
  // Echo an id the legacy client is already carrying, so it keeps carrying it.
625
628
  const echoed = request.headers.get(SESSION_ID_HEADER)?.trim();
@@ -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] = {
@@ -74,14 +74,17 @@ export const withMcpHandlerAnalytics = (handler, config) => {
74
74
  }
75
75
  }
76
76
  const response = await handler(request, ...rest);
77
- if (session?.isInitialize && response.ok) {
77
+ // `sessionId` is always minted on initialize; the check narrows the type
78
+ // for the non-initialize case, where it is now optional.
79
+ if (session?.isInitialize && session.sessionId && response.ok) {
80
+ const mintedSessionId = session.sessionId;
78
81
  try {
79
82
  await state.core.recordSessionInit({
80
- sessionId: session.sessionId,
83
+ sessionId: mintedSessionId,
81
84
  headers: request.headers,
82
85
  clientInfo: clientInfoFromInitializeBody(body),
83
86
  extra: {
84
- sessionId: session.sessionId,
87
+ sessionId: mintedSessionId,
85
88
  requestInfo: { headers: request.headers },
86
89
  },
87
90
  });
@@ -89,7 +92,7 @@ export const withMcpHandlerAnalytics = (handler, config) => {
89
92
  catch {
90
93
  // Recording is best-effort; never break the MCP response over it.
91
94
  }
92
- return withSessionIdHeader(response, session.sessionId);
95
+ return withSessionIdHeader(response, mintedSessionId);
93
96
  }
94
97
  // Echo an id the client is already carrying, so it keeps carrying it.
95
98
  const echoed = request.headers.get(SESSION_ID_HEADER)?.trim();