@armature-tech/mcp-analytics 0.6.17 → 0.6.19

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.
Files changed (59) hide show
  1. package/README.md +116 -4
  2. package/SKILL.md +30 -5
  3. package/dist/cjs/cli.d.ts +2 -0
  4. package/dist/cjs/cli.js +62 -0
  5. package/dist/cjs/doctor-args.d.ts +2 -0
  6. package/dist/cjs/doctor-args.js +101 -0
  7. package/dist/cjs/doctor.d.ts +63 -0
  8. package/dist/cjs/doctor.js +325 -0
  9. package/dist/cjs/emit.d.ts +3 -0
  10. package/dist/cjs/emit.js +18 -3
  11. package/dist/cjs/events.d.ts +19 -5
  12. package/dist/cjs/events.js +141 -22
  13. package/dist/cjs/index.d.ts +7 -4
  14. package/dist/cjs/index.js +25 -1
  15. package/dist/cjs/mastra.js +50 -4
  16. package/dist/cjs/queue.d.ts +9 -0
  17. package/dist/cjs/queue.js +116 -0
  18. package/dist/cjs/recorder.js +194 -81
  19. package/dist/cjs/redact-secrets.d.ts +10 -0
  20. package/dist/cjs/redact-secrets.js +121 -0
  21. package/dist/cjs/request-capability.d.ts +12 -0
  22. package/dist/cjs/request-capability.js +50 -0
  23. package/dist/cjs/sanitize.d.ts +10 -0
  24. package/dist/cjs/sanitize.js +102 -0
  25. package/dist/cjs/schema.d.ts +18 -66
  26. package/dist/cjs/schema.js +129 -106
  27. package/dist/cjs/server.js +36 -8
  28. package/dist/cjs/stateless-http.d.ts +1 -1
  29. package/dist/cjs/stateless-http.js +8 -2
  30. package/dist/cjs/types.d.ts +42 -3
  31. package/dist/esm/cli.d.ts +2 -0
  32. package/dist/esm/cli.js +60 -0
  33. package/dist/esm/doctor-args.d.ts +2 -0
  34. package/dist/esm/doctor-args.js +97 -0
  35. package/dist/esm/doctor.d.ts +63 -0
  36. package/dist/esm/doctor.js +315 -0
  37. package/dist/esm/emit.d.ts +3 -0
  38. package/dist/esm/emit.js +14 -1
  39. package/dist/esm/events.d.ts +19 -5
  40. package/dist/esm/events.js +138 -21
  41. package/dist/esm/index.d.ts +7 -4
  42. package/dist/esm/index.js +6 -3
  43. package/dist/esm/mastra.js +51 -5
  44. package/dist/esm/queue.d.ts +9 -0
  45. package/dist/esm/queue.js +112 -0
  46. package/dist/esm/recorder.js +197 -84
  47. package/dist/esm/redact-secrets.d.ts +10 -0
  48. package/dist/esm/redact-secrets.js +115 -0
  49. package/dist/esm/request-capability.d.ts +12 -0
  50. package/dist/esm/request-capability.js +45 -0
  51. package/dist/esm/sanitize.d.ts +10 -0
  52. package/dist/esm/sanitize.js +97 -0
  53. package/dist/esm/schema.d.ts +18 -66
  54. package/dist/esm/schema.js +124 -105
  55. package/dist/esm/server.js +37 -9
  56. package/dist/esm/stateless-http.d.ts +1 -1
  57. package/dist/esm/stateless-http.js +8 -2
  58. package/dist/esm/types.d.ts +42 -3
  59. package/package.json +8 -1
package/dist/esm/index.js CHANGED
@@ -1,6 +1,9 @@
1
- export { appendTelemetryHint, createTelemetryInputSchema, createTelemetryJsonSchema, decorateInputSchemaWithTelemetry, extractTelemetryArguments, normalizeTelemetryArgs, } from "./schema.js";
2
- export { buildActorId, buildEventId, buildSessionInitEvent, buildToolCallEvent, normalizeSessionId, } from "./events.js";
3
- export { defaultMcpAnalyticsConfig, emitTelemetryEvent, postTelemetryEvent, } from "./emit.js";
1
+ export { appendTelemetryHint, applyTelemetryFieldMap, createTelemetryInputSchema, createTelemetryJsonSchema, decorateInputSchemaWithTelemetry, extractTelemetryArguments, isCaptureEnabled, normalizeTelemetryArgs, planToolTelemetry, schemaDeclaresTelemetry, } from "./schema.js";
2
+ export { BASE64_REMOVED_PLACEHOLDER, BINARY_REMOVED_PLACEHOLDER, prepareForPreview, REDACTION_FAILED_PLACEHOLDER, sanitizeValue, SANITIZATION_BUDGET, } from "./sanitize.js";
3
+ export { normalizeSensitiveFieldName, redactSecretsInString, redactSecretsInValue, SECRET_PATTERN_RULES, SENSITIVE_FIELD_NAMES, } from "./redact-secrets.js";
4
+ export { createPrivacyQueue, PRIVACY_QUEUE_BATCH_SIZE, PRIVACY_QUEUE_CAPACITY, } from "./queue.js";
5
+ export { buildActorId, buildActorIdentityEvent, buildEventId, buildSessionInitEvent, buildToolCallEvent, finalizeToolCallEvent, normalizeSessionId, } from "./events.js";
6
+ export { defaultMcpAnalyticsConfig, emitTelemetryEvent, postTelemetryEvent, reportEmitError, } from "./emit.js";
4
7
  export { createAnalyticsRecorder } from "./recorder.js";
5
8
  export { buildStatelessSessionId, parseStatelessSessionClientInfo, resolveStatelessHttpSession, } from "./stateless-http.js";
6
9
  export { createMcpAnalyticsServer, withMcpAnalytics } from "./server.js";
@@ -1,6 +1,8 @@
1
1
  import { createAnalyticsRecorder } from "./recorder.js";
2
- import { appendTelemetryHint, decorateInputSchemaWithTelemetry, } from "./schema.js";
2
+ import { planToolTelemetry } from "./schema.js";
3
3
  import { isRecord } from "./utils.js";
4
+ import { z } from "zod";
5
+ import { isRequestCapabilityEnabled, REQUEST_CAPABILITY_ARGUMENT_DESCRIPTION, REQUEST_CAPABILITY_DESCRIPTION, REQUEST_CAPABILITY_TOOL_NAME, } from "./request-capability.js";
4
6
  const readMcpExtra = (mastraContext) => {
5
7
  if (!isRecord(mastraContext))
6
8
  return undefined;
@@ -90,9 +92,11 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
90
92
  }
91
93
  const originalExecute = tool.execute;
92
94
  const toolName = tool.id ?? toolKey;
93
- const decoratedInputSchema = tool.inputSchema === undefined
94
- ? undefined
95
- : decorateInputSchemaWithTelemetry(tool.inputSchema, config);
95
+ // Mastra tools without an inputSchema keep no schema (Mastra derives its own
96
+ // default); planToolTelemetry is only consulted for decoration when the tool
97
+ // has one, but its mode still drives extraction either way.
98
+ const plan = planToolTelemetry(toolName, tool.inputSchema, config);
99
+ const decoratedInputSchema = tool.inputSchema === undefined ? undefined : plan.inputSchema;
96
100
  const wrappedExecute = (inputData, mastraContext) => {
97
101
  // Always extract standard Mastra MCP context (`context.mcp.extra` or the
98
102
  // `requestContext.get("mcp.extra")` fallback). A user-supplied
@@ -112,11 +116,13 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
112
116
  // `normalizeRequestId`). The JSON-RPC id stays available via `extra`.
113
117
  authInfo: extra?.authInfo,
114
118
  headers: extra?.requestInfo?.headers,
119
+ telemetryMode: plan.mode,
115
120
  }, (strippedArgs) => originalExecute(strippedArgs, mastraContext));
116
121
  };
122
+ const description = plan.applyDescription(tool.description);
117
123
  return {
118
124
  ...tool,
119
- description: appendTelemetryHint(tool.description),
125
+ ...(description !== undefined ? { description } : {}),
120
126
  ...(decoratedInputSchema !== undefined
121
127
  ? { inputSchema: decoratedInputSchema }
122
128
  : {}),
@@ -133,9 +139,49 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
133
139
  // passes the constraint without a cast.
134
140
  export const wrapMastraToolsWithRecorder = (tools, recorder, config = {}, options = {}) => {
135
141
  const out = {};
142
+ const requestCapabilityEnabled = isRequestCapabilityEnabled(config);
143
+ if (requestCapabilityEnabled !== recorder.hasTool(REQUEST_CAPABILITY_TOOL_NAME)) {
144
+ throw new Error("request_capability configuration does not match the supplied analytics recorder.");
145
+ }
146
+ if (requestCapabilityEnabled
147
+ && Object.entries(tools).some(([key, tool]) => key === REQUEST_CAPABILITY_TOOL_NAME
148
+ || tool.id === REQUEST_CAPABILITY_TOOL_NAME)) {
149
+ throw new Error(`Tool name "${REQUEST_CAPABILITY_TOOL_NAME}" is reserved while armature.requestCapability is enabled.`);
150
+ }
136
151
  for (const [key, tool] of Object.entries(tools)) {
137
152
  out[key] = wrapOneTool(key, tool, recorder, config, options.resolveExtra);
138
153
  }
154
+ if (requestCapabilityEnabled) {
155
+ out[REQUEST_CAPABILITY_TOOL_NAME] = {
156
+ id: REQUEST_CAPABILITY_TOOL_NAME,
157
+ description: REQUEST_CAPABILITY_DESCRIPTION,
158
+ inputSchema: z.object({
159
+ capability: z
160
+ .string()
161
+ .min(1)
162
+ .max(1000)
163
+ .describe(REQUEST_CAPABILITY_ARGUMENT_DESCRIPTION),
164
+ }),
165
+ execute: async (inputData, mastraContext) => {
166
+ const extra = mergeExtra(defaultMastraResolveExtra(mastraContext), options.resolveExtra?.(mastraContext));
167
+ const result = await recorder.dispatch(REQUEST_CAPABILITY_TOOL_NAME, inputData, {
168
+ ctx: mastraContext,
169
+ extra,
170
+ sessionId: extra?.sessionId,
171
+ authInfo: extra?.authInfo,
172
+ headers: extra?.requestInfo?.headers,
173
+ });
174
+ const text = result.content.find((content) => content.type === "text")?.text;
175
+ if (result.isError) {
176
+ throw new Error(text ?? "capability request failed");
177
+ }
178
+ // Mastra's MCPServer turns raw tool output into CallToolResult content.
179
+ // Returning the dispatcher's CallToolResult here would JSON-stringify
180
+ // and double-wrap it as text.
181
+ return text ?? "Capability request acknowledged.";
182
+ },
183
+ };
184
+ }
139
185
  return out;
140
186
  };
141
187
  export const wrapMastraTools = (tools, options = {}) => {
@@ -0,0 +1,9 @@
1
+ import type { AnalyticsIngestEvent, McpAnalyticsConfig } from "./types.js";
2
+ export declare const PRIVACY_QUEUE_CAPACITY = 1000;
3
+ export declare const PRIVACY_QUEUE_BATCH_SIZE = 20;
4
+ export type PrivacyQueueFinalizer = () => AnalyticsIngestEvent[] | null | Promise<AnalyticsIngestEvent[] | null>;
5
+ export type PrivacyQueue = {
6
+ enqueue: (finalize: PrivacyQueueFinalizer) => Promise<void>;
7
+ flush: () => Promise<void>;
8
+ };
9
+ export declare const createPrivacyQueue: (config: McpAnalyticsConfig) => PrivacyQueue;
@@ -0,0 +1,112 @@
1
+ import { postTelemetryEvent, reportEmitError, } from "./emit.js";
2
+ import { readEnv, SCHEMA_VERSION } from "./utils.js";
3
+ export const PRIVACY_QUEUE_CAPACITY = 1_000;
4
+ export const PRIVACY_QUEUE_BATCH_SIZE = 20;
5
+ let warnedServerlessWithoutSchedule = false;
6
+ const warn = (message, error) => {
7
+ // eslint-disable-next-line no-console
8
+ console.warn(`[mcp-analytics] ${message}`, ...(error === undefined ? [] : [error]));
9
+ };
10
+ export const createPrivacyQueue = (config) => {
11
+ const pending = [];
12
+ let running = null;
13
+ let dropped = 0;
14
+ let warnedDropped = false;
15
+ const isEnabled = () => config.armature?.enabled !== false;
16
+ if (isEnabled()
17
+ && config.armature?.delivery !== "await"
18
+ && !config.armature?.schedule
19
+ && !warnedServerlessWithoutSchedule
20
+ && (readEnv("AWS_LAMBDA_FUNCTION_NAME") || readEnv("VERCEL"))) {
21
+ warnedServerlessWithoutSchedule = true;
22
+ warn("background delivery may be frozen by this serverless runtime; use delivery: \"await\" or armature.schedule");
23
+ }
24
+ const emit = async (batch) => {
25
+ const emitter = config.armature?.emit
26
+ ?? (async (value) => {
27
+ await postTelemetryEvent(value, config);
28
+ });
29
+ try {
30
+ await emitter(batch);
31
+ }
32
+ catch (error) {
33
+ reportEmitError(error, batch, config);
34
+ }
35
+ };
36
+ const drain = async () => {
37
+ while (pending.length > 0) {
38
+ const items = pending.splice(0, PRIVACY_QUEUE_BATCH_SIZE);
39
+ const events = [];
40
+ for (const finalize of items) {
41
+ try {
42
+ const finalized = await finalize();
43
+ if (finalized)
44
+ events.push(...finalized);
45
+ }
46
+ catch (error) {
47
+ warn("privacy queue candidate failed and was dropped:", error);
48
+ }
49
+ }
50
+ if (events.length > 0) {
51
+ await emit({ schema_version: SCHEMA_VERSION, events });
52
+ }
53
+ }
54
+ };
55
+ const start = (deferred) => {
56
+ if (running)
57
+ return running;
58
+ const gate = deferred
59
+ ? new Promise((resolve) => {
60
+ if (typeof setImmediate === "function")
61
+ setImmediate(resolve);
62
+ else
63
+ queueMicrotask(resolve);
64
+ })
65
+ : Promise.resolve();
66
+ const task = gate
67
+ .then(drain)
68
+ .finally(() => {
69
+ if (running === task)
70
+ running = null;
71
+ if (pending.length > 0 && isEnabled())
72
+ scheduleBackground();
73
+ });
74
+ running = task;
75
+ return task;
76
+ };
77
+ const scheduleBackground = () => {
78
+ const work = start(true);
79
+ try {
80
+ config.armature?.schedule?.(work);
81
+ }
82
+ catch (error) {
83
+ warn("schedule hook threw; background work remains active:", error);
84
+ }
85
+ };
86
+ const flush = async () => {
87
+ if (!isEnabled())
88
+ return;
89
+ while (running || pending.length > 0) {
90
+ await (running ?? start(false));
91
+ }
92
+ };
93
+ const enqueue = (finalize) => {
94
+ if (!isEnabled())
95
+ return Promise.resolve();
96
+ if (pending.length >= PRIVACY_QUEUE_CAPACITY) {
97
+ pending.shift();
98
+ dropped += 1;
99
+ if (!warnedDropped) {
100
+ warnedDropped = true;
101
+ warn(`privacy queue overflow; dropped ${dropped} oldest candidate(s)`);
102
+ }
103
+ }
104
+ pending.push(finalize);
105
+ if (config.armature?.delivery === "await")
106
+ return flush();
107
+ if (!running)
108
+ scheduleBackground();
109
+ return Promise.resolve();
110
+ };
111
+ return { enqueue, flush };
112
+ };
@@ -1,11 +1,13 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
- import { buildActorId, buildBatch, buildSessionInitBatch, buildToolCallEvent, normalizeRequestId, normalizeSessionId, normalizeStartedAt, } from "./events.js";
3
- import { createFlushableEmitter, defaultMcpAnalyticsConfig, resolveActorSeed, } from "./emit.js";
4
- import { appendTelemetryHint, decorateInputSchemaWithTelemetry, extractTelemetryArguments, TELEMETRY_PROPERTY_DESCRIPTION, USER_INTENT_DESCRIPTION, } from "./schema.js";
2
+ import { buildActorId, buildActorIdentityEvent, buildBatch, buildSessionInitBatch, finalizeToolCallEvent, normalizeRequestId, normalizeSessionId, normalizeStartedAt, } from "./events.js";
3
+ import { defaultMcpAnalyticsConfig, resolveActorSeed, resolveActorIdentifier, } from "./emit.js";
4
+ import { applyTelemetryFieldMap, extractTelemetryArguments, isCaptureEnabled, planToolTelemetry, TELEMETRY_PROPERTY_DESCRIPTION, USER_INTENT_DESCRIPTION, } from "./schema.js";
5
5
  import { createBoundedKeySet, deriveToolResultError, headerValue, isJsonObjectSchema, isRecord, workflowRunIdFromHeaders } from "./utils.js";
6
6
  import { processScopedSessionId } from "./stdio-session.js";
7
7
  import { getClientInfoForSessionId, installClientInfoCapture, } from "./client-info-cache.js";
8
8
  import { parseStatelessSessionClientInfo } from "./stateless-http.js";
9
+ import { handleRequestCapability, isRequestCapabilityEnabled, REQUEST_CAPABILITY_DESCRIPTION, REQUEST_CAPABILITY_INPUT_SCHEMA, REQUEST_CAPABILITY_TOOL_NAME, REQUEST_CAPABILITY_ZOD_SHAPE, } from "./request-capability.js";
10
+ import { createPrivacyQueue } from "./queue.js";
9
11
  const nudgeTelemetryDescriptions = (schema) => {
10
12
  if (!isJsonObjectSchema(schema))
11
13
  return schema;
@@ -31,11 +33,13 @@ const nudgeTelemetryDescriptions = (schema) => {
31
33
  };
32
34
  };
33
35
  const createAnalyticsContext = async (config, input) => {
34
- const actorSeed = await resolveActorSeed(config, input);
35
- return { actorId: buildActorId({ actorSeed }) };
36
+ const actorIdentifier = await resolveActorIdentifier(config, input);
37
+ const actorSeed = actorIdentifier ?? await resolveActorSeed(config, input);
38
+ return { actorId: buildActorId({ actorSeed }), actorIdentifier };
36
39
  };
37
40
  export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
38
- const { emitBatch, flush } = createFlushableEmitter(config);
41
+ const privacyQueue = createPrivacyQueue(config);
42
+ const flush = privacyQueue.flush;
39
43
  // Tracks which (actorId, sessionId) pairs have already emitted a session_init,
40
44
  // so we emit it at most once per session. Bounded with FIFO eviction: MCP
41
45
  // gives no reliable session-closed signal, so an unbounded set would leak on
@@ -43,6 +47,26 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
43
47
  // session_init event_id is now stable per (actorId, sessionId), so a re-emit
44
48
  // after eviction collapses to the same id at ingest. 10k × ~60 bytes ≈ 600KB.
45
49
  const sessionInitKeys = createBoundedKeySet(10_000);
50
+ // Per-process change detection. Event ids are content-addressed, so an
51
+ // identical re-emit after restart is harmless and converges at ingest.
52
+ const actorIdentifiers = new Map();
53
+ const identityEventFor = (context, startedAt) => {
54
+ if (context.actorIdentifier === undefined)
55
+ return undefined;
56
+ if (actorIdentifiers.get(context.actorId) === context.actorIdentifier)
57
+ return undefined;
58
+ actorIdentifiers.set(context.actorId, context.actorIdentifier);
59
+ if (actorIdentifiers.size > 10_000) {
60
+ const oldest = actorIdentifiers.keys().next().value;
61
+ if (oldest !== undefined)
62
+ actorIdentifiers.delete(oldest);
63
+ }
64
+ return buildActorIdentityEvent({
65
+ actorId: context.actorId,
66
+ identifier: context.actorIdentifier,
67
+ startedAt,
68
+ });
69
+ };
46
70
  // Patch the SDK's Server.prototype the first time any recorder is created
47
71
  // so that the very next `initialize` handshake feeds the per-session client
48
72
  // info cache. Without this the dashboard's "Client" column would stay at
@@ -54,13 +78,18 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
54
78
  };
55
79
  const decorateDefinitions = (defs) => {
56
80
  return defs.map((definition) => {
57
- const inputSchema = nudgeTelemetryDescriptions(decorateInputSchemaWithTelemetry(definition.inputSchema ?? { type: "object", properties: {} }, config));
81
+ const plan = planToolTelemetry(definition.name, definition.inputSchema ?? { type: "object", properties: {} }, config);
82
+ // Owned/scrub tools pass through undecorated — their advertised schema
83
+ // and description must keep matching what the handler actually receives.
84
+ if (plan.mode !== "injected") {
85
+ return { ...definition, inputSchema: plan.inputSchema };
86
+ }
58
87
  return {
59
88
  ...definition,
60
- description: appendTelemetryHint(typeof definition.description === "string"
89
+ description: plan.applyDescription(typeof definition.description === "string"
61
90
  ? definition.description
62
91
  : undefined),
63
- inputSchema,
92
+ inputSchema: nudgeTelemetryDescriptions(plan.inputSchema),
64
93
  };
65
94
  });
66
95
  };
@@ -97,40 +126,46 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
97
126
  const sessionId = resolveSessionId(event);
98
127
  if (!sessionId)
99
128
  return;
100
- const context = await analyticsContextFor({
101
- ctx: event.ctx,
102
- extra: event.extra,
103
- headers: event.headers ?? event.extra?.requestInfo?.headers,
104
- authInfo: event.authInfo ?? event.extra?.authInfo,
105
- });
106
129
  const finishedAtMs = Date.now();
107
130
  const startedAt = normalizeStartedAt({
108
131
  startedAt: event.startedAt,
109
132
  finishedAtMs,
110
133
  });
111
- const batch = buildSessionInitBatch({
112
- actorId: context.actorId,
113
- sessionId,
114
- startedAt,
115
- extra: event.extra,
116
- sessionInitKeys,
117
- clientInfo: event.clientInfo
118
- ?? getClientInfoForSessionId(sessionId)
119
- ?? parseStatelessSessionClientInfo(sessionId),
120
- workflowRunId: resolveWorkflowRunId(event),
134
+ const workflowRunId = resolveWorkflowRunId(event);
135
+ return privacyQueue.enqueue(async () => {
136
+ const context = await analyticsContextFor({
137
+ ctx: event.ctx,
138
+ extra: event.extra,
139
+ headers: event.headers ?? event.extra?.requestInfo?.headers,
140
+ authInfo: event.authInfo ?? event.extra?.authInfo,
141
+ });
142
+ const batch = buildSessionInitBatch({
143
+ actorId: context.actorId,
144
+ sessionId,
145
+ startedAt,
146
+ extra: event.extra,
147
+ sessionInitKeys,
148
+ clientInfo: event.clientInfo
149
+ ?? getClientInfoForSessionId(sessionId)
150
+ ?? parseStatelessSessionClientInfo(sessionId),
151
+ workflowRunId,
152
+ identityEvent: identityEventFor(context, startedAt),
153
+ });
154
+ return batch?.events ?? null;
121
155
  });
122
- if (batch)
123
- await emitBatch(batch);
124
156
  };
125
157
  const recordToolCall = async (event) => {
126
- const context = await analyticsContextFor({
127
- ctx: event.ctx,
128
- extra: event.extra,
129
- headers: event.headers ?? event.extra?.requestInfo?.headers,
130
- authInfo: event.authInfo ?? event.extra?.authInfo,
131
- toolName: event.name,
132
- telemetry: event.telemetry,
133
- });
158
+ // Single choke point for capture-off and field ownership
159
+ // (TELEMETRY-CONTRACT.md): telemetry handed in by any path — extraction,
160
+ // direct recordToolCall callers, a cached-schema client — is dropped here
161
+ // before it can reach the actor resolver, the event builder, `emit`, or
162
+ // `onError`. A registered tool that owns its telemetry field never exports
163
+ // supplied telemetry either; the opt-in field map is the explicit way to
164
+ // export customer fields, and it only applies while capture is on.
165
+ const ownedTool = registeredTools.get(event.name)?.telemetryMode === "owned";
166
+ const telemetry = isCaptureEnabled(config)
167
+ ? applyTelemetryFieldMap(ownedTool ? undefined : event.telemetry, event.args, config.armature?.telemetryFieldMap)
168
+ : undefined;
134
169
  const finishedAtMs = Date.now();
135
170
  const finishedAt = new Date(finishedAtMs).toISOString();
136
171
  const durationMs = event.durationMs ?? 0;
@@ -147,43 +182,72 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
147
182
  ? event.error.message
148
183
  : String(event.error);
149
184
  const workflowRunId = resolveWorkflowRunId(event);
150
- const toolCallEvent = buildToolCallEvent({
151
- toolName: event.name,
152
- telemetry: event.telemetry,
153
- input: event.args,
154
- output: event.result,
155
- status: event.status,
156
- durationMs,
157
- errorMessage,
158
- actorId: context.actorId,
159
- sessionId,
160
- requestId,
161
- startedAt,
162
- finishedAt,
163
- workflowRunId,
164
- });
165
- // An explicit clientInfo on the event always wins; otherwise look up
166
- // whatever the initialize-handshake patch captured for this sessionId; as a
167
- // last resort, identity-bearing session ids (stateless HTTP) are parseable.
168
- const effectiveClientInfo = event.clientInfo
169
- ?? getClientInfoForSessionId(sessionId)
170
- ?? parseStatelessSessionClientInfo(sessionId);
171
- await emitBatch(buildBatch({
172
- event: toolCallEvent,
173
- extra: {
185
+ return privacyQueue.enqueue(async () => {
186
+ const context = await analyticsContextFor({
187
+ ctx: event.ctx,
188
+ extra: event.extra,
189
+ headers: event.headers ?? event.extra?.requestInfo?.headers,
190
+ authInfo: event.authInfo ?? event.extra?.authInfo,
191
+ toolName: event.name,
192
+ telemetry,
193
+ });
194
+ const toolCallEvent = await finalizeToolCallEvent({
195
+ toolName: event.name,
196
+ telemetry,
197
+ input: event.args,
198
+ output: event.result,
199
+ status: event.status,
200
+ durationMs,
201
+ errorMessage,
202
+ actorId: context.actorId,
203
+ sessionId,
204
+ requestId,
205
+ startedAt,
206
+ finishedAt,
207
+ workflowRunId,
208
+ capabilityRequest: event.capabilityRequest,
209
+ redact: config.armature?.redact,
210
+ redactSecrets: config.armature?.redactSecrets,
211
+ redactEvent: config.armature?.redactEvent,
212
+ });
213
+ const effectiveClientInfo = event.clientInfo
214
+ ?? getClientInfoForSessionId(sessionId)
215
+ ?? parseStatelessSessionClientInfo(sessionId);
216
+ const identityEvent = identityEventFor(context, startedAt);
217
+ const extra = {
174
218
  ...(event.extra ?? {}),
175
219
  ...(sessionId ? { sessionId } : {}),
176
- },
177
- actorId: context.actorId,
178
- startedAt,
179
- sessionInitKeys,
180
- clientInfo: effectiveClientInfo,
181
- workflowRunId,
182
- }));
220
+ };
221
+ if (toolCallEvent) {
222
+ return buildBatch({
223
+ event: toolCallEvent,
224
+ extra,
225
+ actorId: context.actorId,
226
+ startedAt,
227
+ sessionInitKeys,
228
+ clientInfo: effectiveClientInfo,
229
+ workflowRunId,
230
+ identityEvent,
231
+ }).events;
232
+ }
233
+ if (sessionId) {
234
+ return buildSessionInitBatch({
235
+ actorId: context.actorId,
236
+ sessionId,
237
+ startedAt,
238
+ extra,
239
+ sessionInitKeys,
240
+ clientInfo: effectiveClientInfo,
241
+ workflowRunId,
242
+ identityEvent,
243
+ })?.events ?? null;
244
+ }
245
+ return identityEvent ? [identityEvent] : null;
246
+ });
183
247
  };
184
248
  const registeredTools = new Map();
185
249
  const instrumentToolCall = async (event, handler) => {
186
- const { args, telemetry } = extractTelemetryArguments(event.args);
250
+ const { args, telemetry } = extractTelemetryArguments(event.args, event.telemetryMode ?? "injected");
187
251
  const startedAtMs = Date.now();
188
252
  const startedAt = new Date(startedAtMs).toISOString();
189
253
  try {
@@ -222,7 +286,13 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
222
286
  if (!tool) {
223
287
  throw new Error(`Unknown tool: ${name}`);
224
288
  }
225
- return instrumentToolCall({ name, args: rawArgs, ...context }, (args) => tool.handler(args, context));
289
+ return instrumentToolCall({
290
+ name,
291
+ args: rawArgs,
292
+ telemetryMode: tool.telemetryMode,
293
+ capabilityRequest: tool.internal,
294
+ ...context,
295
+ }, (args) => tool.handler(args, context));
226
296
  };
227
297
  let attachedServer = null;
228
298
  const buildHandlerContext = (extra) => ({
@@ -238,36 +308,57 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
238
308
  headers: extra?.requestInfo?.headers,
239
309
  ctx: extra,
240
310
  });
241
- const registerWithServer = (server, registration, handler) => {
311
+ const registerWithServer = (server, registration, handler, internal = false) => {
242
312
  const originalHasInputSchema = registration.inputSchema !== undefined;
243
- const decoratedSchema = decorateInputSchemaWithTelemetry(registration.inputSchema, config);
313
+ const plan = internal
314
+ ? {
315
+ mode: "scrub",
316
+ inputSchema: registration.inputSchema,
317
+ applyDescription: (description) => description,
318
+ }
319
+ : planToolTelemetry(registration.name, registration.inputSchema, config);
320
+ // The MCP SDK passes (args, extra) to the callback whenever the registered
321
+ // tool has an input schema, and just (extra) when it has none — so the
322
+ // positional juggling below keys on what we actually registered, which for
323
+ // owned/scrub tools is the caller's original (possibly absent) schema.
324
+ const registeredHasInputSchema = plan.inputSchema !== undefined;
325
+ // Same nudge `decorateDefinitions` applies in the registry path — the
326
+ // caller-owned McpServer path must also tell agents to pass
327
+ // telemetry.user_intent, or sessions arrive with no intent (ARM-24).
328
+ // Owned/scrub tools keep their original description untouched.
329
+ const description = plan.applyDescription(registration.description);
244
330
  server.registerTool(registration.name, {
245
331
  ...(registration.title !== undefined ? { title: registration.title } : {}),
246
- // Same nudge `decorateDefinitions` applies in the registry path — the
247
- // caller-owned McpServer path must also tell agents to pass
248
- // telemetry.user_intent, or sessions arrive with no intent (ARM-24).
249
- description: appendTelemetryHint(registration.description),
250
- inputSchema: decoratedSchema,
332
+ ...(description !== undefined ? { description } : {}),
333
+ ...(registeredHasInputSchema ? { inputSchema: plan.inputSchema } : {}),
251
334
  }, (async (...callbackArgs) => {
252
335
  const argsOrExtra = callbackArgs[0];
253
336
  const maybeExtra = callbackArgs[1];
254
- const rawArgs = originalHasInputSchema ? argsOrExtra : {};
255
- const extra = (originalHasInputSchema ? maybeExtra : argsOrExtra);
337
+ const rawArgs = registeredHasInputSchema ? argsOrExtra : {};
338
+ const extra = (registeredHasInputSchema ? maybeExtra : argsOrExtra);
256
339
  return instrumentToolCall({
257
340
  name: registration.name,
258
341
  args: rawArgs,
259
342
  extra,
260
343
  sessionId: extra?.sessionId,
261
- }, (strippedArgs) => handler(strippedArgs, buildHandlerContext(extra)));
344
+ telemetryMode: plan.mode,
345
+ capabilityRequest: internal,
346
+ }, (strippedArgs) => handler(originalHasInputSchema ? strippedArgs : {}, buildHandlerContext(extra)));
262
347
  }));
263
348
  };
264
349
  const tool = (registration, handler) => {
350
+ if (isRequestCapabilityEnabled(config)
351
+ && registration.name === REQUEST_CAPABILITY_TOOL_NAME) {
352
+ throw new Error(`Tool name "${REQUEST_CAPABILITY_TOOL_NAME}" is reserved while armature.requestCapability is enabled.`);
353
+ }
265
354
  registeredTools.set(registration.name, {
266
355
  registration,
267
356
  handler: handler,
357
+ telemetryMode: planToolTelemetry(registration.name, registration.inputSchema, config).mode,
358
+ internal: false,
268
359
  });
269
360
  if (attachedServer) {
270
- registerWithServer(attachedServer, registration, handler);
361
+ registerWithServer(attachedServer, registration, handler, false);
271
362
  }
272
363
  return (rawArgs, context = {}) => dispatch(registration.name, rawArgs, context);
273
364
  };
@@ -276,8 +367,8 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
276
367
  throw new Error("This recorder is already attached to an McpServer.");
277
368
  }
278
369
  attachedServer = server;
279
- for (const { registration, handler } of registeredTools.values()) {
280
- registerWithServer(server, registration, handler);
370
+ for (const { registration, handler, internal } of registeredTools.values()) {
371
+ registerWithServer(server, registration, handler, internal);
281
372
  }
282
373
  return server;
283
374
  };
@@ -285,7 +376,16 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
285
376
  return attachToMcpServer(new McpServer(info));
286
377
  };
287
378
  const toolDefinitions = () => {
288
- return decorateDefinitions(Array.from(registeredTools.values()).map(({ registration }) => {
379
+ const definitions = [];
380
+ for (const { registration, internal } of registeredTools.values()) {
381
+ if (internal) {
382
+ definitions.push({
383
+ name: REQUEST_CAPABILITY_TOOL_NAME,
384
+ description: REQUEST_CAPABILITY_DESCRIPTION,
385
+ inputSchema: REQUEST_CAPABILITY_INPUT_SCHEMA,
386
+ });
387
+ continue;
388
+ }
289
389
  const definition = { name: registration.name };
290
390
  if (registration.title !== undefined)
291
391
  definition.title = registration.title;
@@ -295,10 +395,23 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
295
395
  if (registration.inputSchema !== undefined) {
296
396
  definition.inputSchema = registration.inputSchema;
297
397
  }
298
- return definition;
299
- }));
398
+ definitions.push(...decorateDefinitions([definition]));
399
+ }
400
+ return definitions;
300
401
  };
301
402
  const hasTool = (name) => registeredTools.has(name);
403
+ if (isRequestCapabilityEnabled(config)) {
404
+ registeredTools.set(REQUEST_CAPABILITY_TOOL_NAME, {
405
+ registration: {
406
+ name: REQUEST_CAPABILITY_TOOL_NAME,
407
+ description: REQUEST_CAPABILITY_DESCRIPTION,
408
+ inputSchema: REQUEST_CAPABILITY_ZOD_SHAPE,
409
+ },
410
+ handler: handleRequestCapability,
411
+ telemetryMode: "scrub",
412
+ internal: true,
413
+ });
414
+ }
302
415
  return {
303
416
  decorateDefinitions,
304
417
  extractTelemetry: extractTelemetryArguments,
@@ -0,0 +1,10 @@
1
+ export type SecretPatternRule = {
2
+ id: string;
3
+ pattern: RegExp;
4
+ replacement: string;
5
+ };
6
+ export declare const SECRET_PATTERN_RULES: readonly SecretPatternRule[];
7
+ export declare const SENSITIVE_FIELD_NAMES: Set<string>;
8
+ export declare const normalizeSensitiveFieldName: (key: string) => string;
9
+ export declare const redactSecretsInString: (value: string) => string;
10
+ export declare const redactSecretsInValue: (value: unknown, seen?: WeakSet<object>) => unknown;