@armature-tech/mcp-analytics 0.6.18 → 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 (51) hide show
  1. package/README.md +99 -4
  2. package/SKILL.md +29 -4
  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 +18 -5
  12. package/dist/cjs/events.js +127 -41
  13. package/dist/cjs/index.d.ts +6 -4
  14. package/dist/cjs/index.js +15 -1
  15. package/dist/cjs/mastra.js +42 -0
  16. package/dist/cjs/queue.d.ts +9 -0
  17. package/dist/cjs/queue.js +116 -0
  18. package/dist/cjs/recorder.js +157 -70
  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 +5 -1
  24. package/dist/cjs/sanitize.js +51 -37
  25. package/dist/cjs/server.js +20 -0
  26. package/dist/cjs/types.d.ts +25 -1
  27. package/dist/esm/cli.d.ts +2 -0
  28. package/dist/esm/cli.js +60 -0
  29. package/dist/esm/doctor-args.d.ts +2 -0
  30. package/dist/esm/doctor-args.js +97 -0
  31. package/dist/esm/doctor.d.ts +63 -0
  32. package/dist/esm/doctor.js +315 -0
  33. package/dist/esm/emit.d.ts +3 -0
  34. package/dist/esm/emit.js +14 -1
  35. package/dist/esm/events.d.ts +18 -5
  36. package/dist/esm/events.js +124 -40
  37. package/dist/esm/index.d.ts +6 -4
  38. package/dist/esm/index.js +5 -3
  39. package/dist/esm/mastra.js +42 -0
  40. package/dist/esm/queue.d.ts +9 -0
  41. package/dist/esm/queue.js +112 -0
  42. package/dist/esm/recorder.js +159 -72
  43. package/dist/esm/redact-secrets.d.ts +10 -0
  44. package/dist/esm/redact-secrets.js +115 -0
  45. package/dist/esm/request-capability.d.ts +12 -0
  46. package/dist/esm/request-capability.js +45 -0
  47. package/dist/esm/sanitize.d.ts +5 -1
  48. package/dist/esm/sanitize.js +50 -36
  49. package/dist/esm/server.js +20 -0
  50. package/dist/esm/types.d.ts +25 -1
  51. package/package.json +6 -1
@@ -0,0 +1,315 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
4
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
5
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
6
+ const DEFAULT_INGEST_URL = "https://app.armature.tech/api/mcp-analytics/ingest";
7
+ const DEFAULT_TIMEOUT_MS = 10_000;
8
+ const CURRENT_TELEMETRY_MARKER = "Conversation telemetry.";
9
+ const LEGACY_TELEMETRY_MARKERS = [
10
+ "Pass telemetry.user_intent",
11
+ "Pass telemetry.intent",
12
+ ];
13
+ const isRecord = (value) => (typeof value === "object" && value !== null && !Array.isArray(value));
14
+ const errorMessage = (error) => {
15
+ if (error instanceof Error && error.message)
16
+ return error.message;
17
+ return String(error || "unknown error");
18
+ };
19
+ const withTimeout = async (promise, timeoutMs, label) => {
20
+ let timer;
21
+ try {
22
+ return await Promise.race([
23
+ promise,
24
+ new Promise((_resolve, reject) => {
25
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
26
+ }),
27
+ ]);
28
+ }
29
+ finally {
30
+ if (timer)
31
+ clearTimeout(timer);
32
+ }
33
+ };
34
+ const currentProcessEnvironment = () => {
35
+ const out = {};
36
+ for (const [key, value] of Object.entries(process.env)) {
37
+ if (typeof value === "string")
38
+ out[key] = value;
39
+ }
40
+ return out;
41
+ };
42
+ export const inspectMcp = async (options) => {
43
+ const client = new Client({ name: "armature-mcp-doctor", version: "1" });
44
+ const transport = options.target.kind === "http"
45
+ ? new StreamableHTTPClientTransport(new URL(options.target.url), {
46
+ requestInit: { headers: options.target.headers },
47
+ })
48
+ : new StdioClientTransport({
49
+ command: options.target.command,
50
+ args: options.target.args,
51
+ cwd: options.target.cwd,
52
+ env: currentProcessEnvironment(),
53
+ stderr: "pipe",
54
+ });
55
+ if (transport instanceof StdioClientTransport) {
56
+ // The SDK exposes the PassThrough before spawning the child, so start
57
+ // draining immediately. Otherwise a chatty server can fill the bounded
58
+ // stderr pipe and block before it answers the MCP handshake.
59
+ transport.stderr?.on("data", () => undefined);
60
+ }
61
+ try {
62
+ await withTimeout(client.connect(transport), options.timeoutMs, "MCP initialize");
63
+ const listed = await withTimeout(client.listTools(), options.timeoutMs, "MCP tools/list");
64
+ const server = client.getServerVersion();
65
+ return {
66
+ serverName: server?.name,
67
+ serverVersion: server?.version,
68
+ tools: listed.tools.map((tool) => ({
69
+ name: tool.name,
70
+ description: tool.description,
71
+ inputSchema: tool.inputSchema,
72
+ })),
73
+ };
74
+ }
75
+ finally {
76
+ // Some stdio servers do not exit promptly after stdin closes. Diagnostics
77
+ // must still return a result instead of hanging on cleanup.
78
+ await withTimeout(client.close(), Math.min(options.timeoutMs, 1_000), "MCP close")
79
+ .catch(() => {
80
+ if (transport instanceof StdioClientTransport && transport.pid) {
81
+ try {
82
+ process.kill(transport.pid, "SIGTERM");
83
+ }
84
+ catch {
85
+ // The child may already have exited between the pid read and kill.
86
+ }
87
+ }
88
+ });
89
+ }
90
+ };
91
+ const telemetryShape = (tool) => {
92
+ if (!isRecord(tool.inputSchema))
93
+ return null;
94
+ const properties = tool.inputSchema.properties;
95
+ if (!isRecord(properties))
96
+ return null;
97
+ return isRecord(properties.telemetry) ? properties.telemetry : null;
98
+ };
99
+ export const classifyToolInstrumentation = (tool) => {
100
+ const inputProperties = isRecord(tool.inputSchema)
101
+ && isRecord(tool.inputSchema.properties)
102
+ ? tool.inputSchema.properties
103
+ : null;
104
+ const ownsTelemetryField = Boolean(inputProperties && "telemetry" in inputProperties);
105
+ const telemetry = telemetryShape(tool);
106
+ if (!telemetry)
107
+ return ownsTelemetryField ? "owned" : "missing";
108
+ const properties = isRecord(telemetry.properties) ? telemetry.properties : {};
109
+ const telemetryDescription = typeof telemetry.description === "string"
110
+ ? telemetry.description
111
+ : "";
112
+ const toolDescription = tool.description || "";
113
+ if ("agent_thinking" in properties
114
+ && "user_intent" in properties
115
+ && telemetryDescription.includes(CURRENT_TELEMETRY_MARKER)) {
116
+ return "current";
117
+ }
118
+ if ("intent" in properties
119
+ || "context" in properties
120
+ || LEGACY_TELEMETRY_MARKERS.some((marker) => toolDescription.includes(marker))) {
121
+ return "legacy";
122
+ }
123
+ return ownsTelemetryField ? "owned" : "missing";
124
+ };
125
+ export const inspectToolCoverage = (tools) => {
126
+ const current = [];
127
+ const legacy = [];
128
+ const owned = [];
129
+ const missing = [];
130
+ for (const tool of tools) {
131
+ const classification = classifyToolInstrumentation(tool);
132
+ if (classification === "current")
133
+ current.push(tool.name);
134
+ else if (classification === "legacy")
135
+ legacy.push(tool.name);
136
+ else if (classification === "owned")
137
+ owned.push(tool.name);
138
+ else
139
+ missing.push(tool.name);
140
+ }
141
+ return { current, legacy, owned, missing, total: tools.length };
142
+ };
143
+ const readIfPresent = async (path) => {
144
+ try {
145
+ return await readFile(path, "utf8");
146
+ }
147
+ catch (error) {
148
+ const code = isRecord(error) ? error.code : undefined;
149
+ if (code === "ENOENT")
150
+ return null;
151
+ throw error;
152
+ }
153
+ };
154
+ export const detectLocalSdks = async (cwd) => {
155
+ const found = [];
156
+ const packageJson = await readIfPresent(resolve(cwd, "package.json"));
157
+ if (packageJson) {
158
+ try {
159
+ const parsed = JSON.parse(packageJson);
160
+ const sections = [parsed.dependencies, parsed.devDependencies, parsed.peerDependencies];
161
+ for (const section of sections) {
162
+ if (isRecord(section) && typeof section["@armature-tech/mcp-analytics"] === "string") {
163
+ found.push({
164
+ language: "typescript",
165
+ declaration: `@armature-tech/mcp-analytics ${section["@armature-tech/mcp-analytics"]}`,
166
+ });
167
+ break;
168
+ }
169
+ }
170
+ }
171
+ catch {
172
+ // A malformed package.json will be reported by the customer's package manager.
173
+ }
174
+ }
175
+ const pyproject = await readIfPresent(resolve(cwd, "pyproject.toml"));
176
+ const requirements = await readIfPresent(resolve(cwd, "requirements.txt"));
177
+ const pythonDeclaration = [pyproject, requirements]
178
+ .filter((value) => Boolean(value))
179
+ .join("\n")
180
+ .match(/armature-mcp-analytics(?:\[[^\]]+\])?(?:\s*[<>=~!]+\s*[^\s"',\]]+)?/i)?.[0];
181
+ if (pythonDeclaration) {
182
+ found.push({ language: "python", declaration: pythonDeclaration.replace(/["',]/g, "") });
183
+ }
184
+ const goMod = await readIfPresent(resolve(cwd, "go.mod"));
185
+ const goDeclaration = goMod
186
+ ?.match(/github\.com\/armature-tech\/mcp-analytics-go(?:\/[^\s]+)?\s+v[^\s)]+/)?.[0];
187
+ if (goDeclaration)
188
+ found.push({ language: "go", declaration: goDeclaration });
189
+ return found;
190
+ };
191
+ export const verifyIngest = async (endpoint, apiKey, timeoutMs) => {
192
+ const url = new URL(endpoint);
193
+ if (!["http:", "https:"].includes(url.protocol)) {
194
+ throw new Error("ingest URL must use http or https");
195
+ }
196
+ const controller = new AbortController();
197
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
198
+ try {
199
+ // The ingest route resolves bearer auth before accepting an empty batch,
200
+ // so this validates reachability and the key without creating a session or
201
+ // sending tool, user, or response content. Keep that server contract covered
202
+ // by test/api-mcp-analytics-ingest-doctor.test.js.
203
+ const response = await fetch(url, {
204
+ method: "POST",
205
+ headers: {
206
+ "content-type": "application/json",
207
+ authorization: `Bearer ${apiKey}`,
208
+ },
209
+ body: JSON.stringify({ schema_version: 1, events: [] }),
210
+ signal: controller.signal,
211
+ });
212
+ // Drain the body so undici can release its pooled connection promptly and
213
+ // the one-shot CLI does not appear to hang after printing the report.
214
+ await response.arrayBuffer();
215
+ if (!response.ok) {
216
+ throw new Error(`Armature ingest returned HTTP ${response.status}`);
217
+ }
218
+ }
219
+ finally {
220
+ clearTimeout(timer);
221
+ }
222
+ };
223
+ const pass = (id, label, detail) => ({
224
+ id, label, detail, status: "pass",
225
+ });
226
+ const warn = (id, label, detail, remediation) => ({
227
+ id, label, detail, status: "warn", ...(remediation ? { remediation } : {}),
228
+ });
229
+ const fail = (id, label, detail, remediation) => ({
230
+ id, label, detail, status: "fail", ...(remediation ? { remediation } : {}),
231
+ });
232
+ export const runDoctor = async (options, dependencies = { inspectMcp, detectLocalSdks, verifyIngest }, environment = process.env) => {
233
+ const checks = [];
234
+ try {
235
+ const sdks = await dependencies.detectLocalSdks(options.cwd);
236
+ if (sdks.length === 0) {
237
+ checks.push(warn("sdk-declaration", "SDK dependency", "No Armature SDK declaration was found in this directory.", "Run the doctor from the MCP project root, or confirm the SDK is installed in the deployed project."));
238
+ }
239
+ else {
240
+ checks.push(pass("sdk-declaration", "SDK dependency", sdks.map((sdk) => `${sdk.language}: ${sdk.declaration}`).join("; ")));
241
+ }
242
+ }
243
+ catch (error) {
244
+ checks.push(warn("sdk-declaration", "SDK dependency", errorMessage(error)));
245
+ }
246
+ try {
247
+ const inspection = await dependencies.inspectMcp(options);
248
+ const identity = [inspection.serverName, inspection.serverVersion].filter(Boolean).join(" ");
249
+ checks.push(pass("mcp-initialize", "MCP initialize", identity ? `Connected to ${identity}.` : "The server completed the MCP handshake."));
250
+ if (inspection.tools.length === 0) {
251
+ checks.push(fail("tools-list", "Tool discovery", "The server returned zero tools, so wrapping cannot be verified.", "Register at least one tool and run the doctor again."));
252
+ }
253
+ else {
254
+ checks.push(pass("tools-list", "Tool discovery", `The server returned ${inspection.tools.length} tool${inspection.tools.length === 1 ? "" : "s"}.`));
255
+ const coverage = inspectToolCoverage(inspection.tools);
256
+ if (!options.expectCapture) {
257
+ const exposed = coverage.current.length + coverage.legacy.length;
258
+ checks.push(exposed === 0
259
+ ? pass("tool-wrapping", "Telemetry capture", "No Armature telemetry fields are advertised, as requested.")
260
+ : warn("tool-wrapping", "Telemetry capture", `${exposed}/${coverage.total} tools still advertise Armature telemetry fields.`, "Confirm captureTelemetry=false is applied before tools are registered."));
261
+ }
262
+ else if (coverage.missing.length > 0) {
263
+ const sample = coverage.missing.slice(0, 5).join(", ");
264
+ checks.push(fail("tool-wrapping", "Tool wrapping", `${coverage.missing.length}/${coverage.total} tools do not expose the Armature telemetry contract${sample ? `: ${sample}` : ""}.`, "Wrap the same server instance that is started, and register tools inside withMcpAnalytics or through an Armature recorder."));
265
+ }
266
+ else if (coverage.legacy.length > 0) {
267
+ checks.push(warn("tool-wrapping", "Tool wrapping", `All ${coverage.total} tools are wrapped, but ${coverage.legacy.length} use the legacy telemetry contract.`, "Upgrade the Armature SDK and restart the MCP server."));
268
+ }
269
+ else if (coverage.owned.length > 0) {
270
+ const sample = coverage.owned.slice(0, 5).join(", ");
271
+ checks.push(warn("tool-wrapping", "Tool wrapping", `${coverage.current.length}/${coverage.total} tools expose the current Armature telemetry contract; ${coverage.owned.length} own a top-level telemetry field and are intentionally untouched${sample ? `: ${sample}` : ""}.`, "Rename the tool-owned telemetry input if you want Armature analytics for that tool, then restart the MCP server."));
272
+ }
273
+ else {
274
+ checks.push(pass("tool-wrapping", "Tool wrapping", `All ${coverage.total} tools expose the current Armature telemetry contract.`));
275
+ }
276
+ }
277
+ }
278
+ catch (error) {
279
+ checks.push(fail("mcp-initialize", "MCP initialize", errorMessage(error), options.target.kind === "http"
280
+ ? "Start the MCP server, verify the URL/auth headers, and run the doctor again."
281
+ : "Run the server command directly once, fix startup errors, then run the doctor again."));
282
+ }
283
+ if (options.skipIngest) {
284
+ checks.push(warn("ingest-auth", "Armature ingest", "Skipped by --skip-ingest; no network request was made."));
285
+ }
286
+ else {
287
+ const apiKey = environment.ANALYTICS_INGEST_API_KEY;
288
+ const endpoint = environment.ANALYTICS_INGEST_URL || DEFAULT_INGEST_URL;
289
+ if (!apiKey) {
290
+ checks.push(fail("ingest-auth", "Armature ingest", "ANALYTICS_INGEST_API_KEY is not set in the doctor environment.", "Export the same ingest key used by the MCP server, then run the doctor again."));
291
+ }
292
+ else {
293
+ try {
294
+ await dependencies.verifyIngest(endpoint, apiKey, options.timeoutMs);
295
+ checks.push(pass("ingest-auth", "Armature ingest", "The endpoint accepted an empty authenticated health probe; no session or customer content was sent."));
296
+ }
297
+ catch (error) {
298
+ checks.push(fail("ingest-auth", "Armature ingest", errorMessage(error), "Check ANALYTICS_INGEST_API_KEY and ANALYTICS_INGEST_URL, then run the doctor again."));
299
+ }
300
+ }
301
+ }
302
+ return {
303
+ healthy: !checks.some((check) => check.status === "fail"),
304
+ target: options.target.kind,
305
+ checks,
306
+ };
307
+ };
308
+ export const defaultDoctorOptions = (target) => ({
309
+ target,
310
+ cwd: process.cwd(),
311
+ timeoutMs: DEFAULT_TIMEOUT_MS,
312
+ expectCapture: true,
313
+ skipIngest: false,
314
+ json: false,
315
+ });
@@ -9,6 +9,8 @@ export declare const defaultMcpAnalyticsConfig: {
9
9
  export declare const resolveEndpointUrl: (config: McpAnalyticsConfig) => string;
10
10
  export declare const resolveApiKey: (config: McpAnalyticsConfig) => string | undefined;
11
11
  export declare const resolveActorSeed: (config: McpAnalyticsConfig, input: ActorIdResolverInput) => Promise<string>;
12
+ /** Resolve the optional caller-provided identifier without interpreting it. */
13
+ export declare const resolveActorIdentifier: (config: McpAnalyticsConfig, input: ActorIdResolverInput) => Promise<string | undefined>;
12
14
  export declare const postTelemetryEvent: (batch: AnalyticsIngestBatch, config?: McpAnalyticsConfig) => Promise<{
13
15
  skipped: boolean;
14
16
  reason: string;
@@ -20,6 +22,7 @@ export declare const postTelemetryEvent: (batch: AnalyticsIngestBatch, config?:
20
22
  status: number;
21
23
  reason?: undefined;
22
24
  }>;
25
+ export declare const reportEmitError: (error: unknown, batch: AnalyticsIngestBatch, config: McpAnalyticsConfig) => void;
23
26
  export declare const emitTelemetryEvent: (batch: AnalyticsIngestBatch, config?: McpAnalyticsConfig) => Promise<void>;
24
27
  export declare const createFlushableEmitter: (config: McpAnalyticsConfig) => {
25
28
  emitBatch: (batch: AnalyticsIngestBatch) => Promise<void>;
package/dist/esm/emit.js CHANGED
@@ -34,6 +34,19 @@ export const resolveActorSeed = async (config, input) => {
34
34
  return authorization;
35
35
  return "anonymous";
36
36
  };
37
+ const MAX_ACTOR_IDENTIFIER_BYTES = 8 * 1024;
38
+ /** Resolve the optional caller-provided identifier without interpreting it. */
39
+ export const resolveActorIdentifier = async (config, input) => {
40
+ const configured = config.armature?.actorIdentifier;
41
+ if (configured === undefined)
42
+ return undefined;
43
+ const value = typeof configured === "function" ? await configured(input) : configured;
44
+ if (typeof value !== "string" || value.length === 0)
45
+ return undefined;
46
+ return new TextEncoder().encode(value).byteLength <= MAX_ACTOR_IDENTIFIER_BYTES
47
+ ? value
48
+ : undefined;
49
+ };
37
50
  export const postTelemetryEvent = async (batch, config = defaultMcpAnalyticsConfig) => {
38
51
  const endpointUrl = resolveEndpointUrl(config);
39
52
  const apiKey = resolveApiKey(config);
@@ -62,7 +75,7 @@ export const postTelemetryEvent = async (batch, config = defaultMcpAnalyticsConf
62
75
  clearTimeout(timeout);
63
76
  }
64
77
  };
65
- const reportEmitError = (error, batch, config) => {
78
+ export const reportEmitError = (error, batch, config) => {
66
79
  const onError = config.armature?.onError;
67
80
  if (onError) {
68
81
  onError(error, batch);
@@ -1,4 +1,4 @@
1
- import type { AnalyticsEventKind, AnalyticsIngestBatch, AnalyticsIngestEvent, McpClientInfo, RedactFunction, RequestExtra, TelemetryArgs } from "./types.js";
1
+ import type { AnalyticsEventKind, AnalyticsIngestBatch, AnalyticsIngestEvent, McpClientInfo, RedactEventHook, RedactFunction, RequestExtra, TelemetryArgs } from "./types.js";
2
2
  import { type BoundedKeySet } from "./utils.js";
3
3
  export declare const buildActorId: ({ actorSeed, }: {
4
4
  actorSeed: string;
@@ -8,7 +8,12 @@ export declare const buildEventId: ({ actorId, requestId, kind, }: {
8
8
  requestId: string;
9
9
  kind: AnalyticsEventKind;
10
10
  }) => string;
11
- export declare const buildToolCallEvent: ({ toolName, telemetry, input, output, status, durationMs, errorMessage, actorId, sessionId, requestId, startedAt, finishedAt, workflowRunId, redact, }: {
11
+ export declare const buildActorIdentityEvent: ({ actorId, identifier, startedAt, }: {
12
+ actorId: string;
13
+ identifier: string;
14
+ startedAt: string;
15
+ }) => AnalyticsIngestEvent;
16
+ export type BuildToolCallEventInput = {
12
17
  toolName: string;
13
18
  telemetry?: TelemetryArgs;
14
19
  input: unknown;
@@ -22,8 +27,14 @@ export declare const buildToolCallEvent: ({ toolName, telemetry, input, output,
22
27
  startedAt: string;
23
28
  finishedAt: string;
24
29
  workflowRunId?: string;
30
+ capabilityRequest?: boolean;
25
31
  redact?: RedactFunction;
26
- }) => AnalyticsIngestEvent;
32
+ redactSecrets?: boolean;
33
+ };
34
+ export declare const buildToolCallEvent: (input: BuildToolCallEventInput) => AnalyticsIngestEvent;
35
+ export declare const finalizeToolCallEvent: (input: BuildToolCallEventInput & {
36
+ redactEvent?: RedactEventHook;
37
+ }) => Promise<AnalyticsIngestEvent | null>;
27
38
  export declare const buildSessionInitEvent: ({ actorId, sessionId, startedAt, extra, clientInfo, workflowRunId, }: {
28
39
  actorId: string;
29
40
  sessionId: string;
@@ -32,8 +43,9 @@ export declare const buildSessionInitEvent: ({ actorId, sessionId, startedAt, ex
32
43
  clientInfo?: McpClientInfo;
33
44
  workflowRunId?: string;
34
45
  }) => AnalyticsIngestEvent;
35
- export declare const buildBatch: ({ event, extra, actorId, startedAt, sessionInitKeys, clientInfo, workflowRunId, }: {
46
+ export declare const buildBatch: ({ event, identityEvent, extra, actorId, startedAt, sessionInitKeys, clientInfo, workflowRunId, }: {
36
47
  event: AnalyticsIngestEvent;
48
+ identityEvent?: AnalyticsIngestEvent;
37
49
  extra?: RequestExtra;
38
50
  actorId: string;
39
51
  startedAt: string;
@@ -41,7 +53,7 @@ export declare const buildBatch: ({ event, extra, actorId, startedAt, sessionIni
41
53
  clientInfo?: McpClientInfo;
42
54
  workflowRunId?: string;
43
55
  }) => AnalyticsIngestBatch;
44
- export declare const buildSessionInitBatch: ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, workflowRunId, }: {
56
+ export declare const buildSessionInitBatch: ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, workflowRunId, identityEvent, }: {
45
57
  actorId: string;
46
58
  sessionId: string;
47
59
  startedAt: string;
@@ -49,6 +61,7 @@ export declare const buildSessionInitBatch: ({ actorId, sessionId, startedAt, ex
49
61
  sessionInitKeys: BoundedKeySet;
50
62
  clientInfo?: McpClientInfo;
51
63
  workflowRunId?: string;
64
+ identityEvent?: AnalyticsIngestEvent;
52
65
  }) => AnalyticsIngestBatch | null;
53
66
  export declare const normalizeSessionId: (eventSessionId: string | undefined, extra: RequestExtra | undefined) => string | undefined;
54
67
  export declare const normalizeRequestId: (eventRequestId: string | undefined) => string;
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { normalizeTelemetryArgs } from "./schema.js";
3
3
  import { prepareForPreview, REDACTION_FAILED_PLACEHOLDER, } from "./sanitize.js";
4
+ import { redactSecretsInString } from "./redact-secrets.js";
4
5
  import { MAX_CAPABILITIES_BYTES, MAX_PREVIEW_BYTES, MAX_SOURCE_BYTES, SCHEMA_VERSION, headerValue, isRecord, sha256Hex, stringifyPreview, truncateUtf8, } from "./utils.js";
5
6
  const trimOrUndefined = (value) => {
6
7
  if (typeof value !== "string")
@@ -26,33 +27,94 @@ export const buildActorId = ({ actorSeed, }) => {
26
27
  export const buildEventId = ({ actorId, requestId, kind, }) => {
27
28
  return sha256Hex(`${actorId} ${kind} ${requestId}`);
28
29
  };
30
+ export const buildActorIdentityEvent = ({ actorId, identifier, startedAt, }) => {
31
+ return {
32
+ event_id: buildEventId({ actorId, requestId: identifier, kind: "actor_identity" }),
33
+ kind: "actor_identity",
34
+ actor_id: actorId,
35
+ session_id_hint: null,
36
+ started_at: startedAt,
37
+ finished_at: startedAt,
38
+ duration_ms: 0,
39
+ ok: true,
40
+ error: null,
41
+ metadata: { identifier },
42
+ script_source: null,
43
+ script_source_truncated: false,
44
+ result_preview: null,
45
+ result_truncated: false,
46
+ calls: [],
47
+ logs: [],
48
+ search_calls: [],
49
+ };
50
+ };
29
51
  const buildToolCallSource = (toolName, input) => {
30
52
  return `MCP tool call: ${toolName}\n\nInput:\n${stringifyPreview(input)}`;
31
53
  };
32
- // Telemetry text is agent-authored but routinely quotes the user, so the
33
- // customer redaction hook sees it too. Whatever the hook returns is
34
- // re-normalized; a throwing hook drops the telemetry entirely (fail closed).
35
- const redactTelemetry = (telemetry, redact) => {
36
- if (telemetry === undefined || !redact)
37
- return telemetry;
54
+ const prepareTelemetry = (telemetry, redact, redactSecrets) => {
55
+ const normalized = normalizeTelemetryArgs(telemetry);
56
+ if (!normalized)
57
+ return undefined;
58
+ const protectedTelemetry = {
59
+ ...normalized,
60
+ ...(typeof normalized.user_intent === "string"
61
+ ? {
62
+ user_intent: redactSecrets
63
+ ? redactSecretsInString(normalized.user_intent)
64
+ : normalized.user_intent,
65
+ }
66
+ : {}),
67
+ ...(typeof normalized.agent_thinking === "string"
68
+ ? {
69
+ agent_thinking: redactSecrets
70
+ ? redactSecretsInString(normalized.agent_thinking)
71
+ : normalized.agent_thinking,
72
+ }
73
+ : {}),
74
+ };
75
+ if (!redact)
76
+ return protectedTelemetry;
38
77
  try {
39
- return normalizeTelemetryArgs(redact(telemetry));
78
+ return normalizeTelemetryArgs(redact(protectedTelemetry));
40
79
  }
41
80
  catch {
42
81
  return undefined;
43
82
  }
44
83
  };
45
- const redactErrorMessage = (errorMessage, redact) => {
46
- if (errorMessage === undefined || !redact)
47
- return errorMessage;
84
+ const prepareErrorMessage = (errorMessage, redact, redactSecrets) => {
85
+ if (errorMessage === undefined)
86
+ return undefined;
87
+ const protectedMessage = redactSecrets
88
+ ? redactSecretsInString(errorMessage)
89
+ : errorMessage;
90
+ if (!redact)
91
+ return protectedMessage;
48
92
  try {
49
- const redacted = redact(errorMessage);
93
+ const redacted = redact(protectedMessage);
50
94
  return typeof redacted === "string" ? redacted : stringifyPreview(redacted);
51
95
  }
52
96
  catch {
53
97
  return REDACTION_FAILED_PLACEHOLDER;
54
98
  }
55
99
  };
100
+ const prepareToolCallCandidate = ({ toolName, telemetry, input, output, status, durationMs, errorMessage, sessionId, redact, redactSecrets = true, }) => {
101
+ const preparedTelemetry = prepareTelemetry(telemetry, redact, redactSecrets);
102
+ return {
103
+ kind: "tool_call",
104
+ toolName,
105
+ status,
106
+ durationMs,
107
+ ...(sessionId ? { sessionId } : {}),
108
+ input: prepareForPreview(input, redact, { redactSecrets }),
109
+ ...(output === undefined
110
+ ? {}
111
+ : { output: prepareForPreview(output, redact, { redactSecrets }) }),
112
+ ...(errorMessage === undefined
113
+ ? {}
114
+ : { errorMessage: prepareErrorMessage(errorMessage, redact, redactSecrets) }),
115
+ ...(preparedTelemetry === undefined ? {} : { telemetry: preparedTelemetry }),
116
+ };
117
+ };
56
118
  // Marks an event as synthetic traffic from an Armature workflow run so
57
119
  // Session Analytics can exclude it. Spread first in the event literal —
58
120
  // absent when the call did not originate from a workflow run.
@@ -61,35 +123,26 @@ const workflowStamp = (workflowRunId) => {
61
123
  return {};
62
124
  return { is_workflow: true, workflow_run_id: workflowRunId };
63
125
  };
64
- export const buildToolCallEvent = ({ toolName, telemetry, input, output, status, durationMs, errorMessage, actorId, sessionId, requestId, startedAt, finishedAt, workflowRunId, redact, }) => {
65
- // Contract pipeline (TELEMETRY-CONTRACT.md): sanitize → customer redact →
66
- // stringify → truncate, for every payload that can carry customer data —
67
- // input preview, the source built from the input, the result preview, the
68
- // error string, and the telemetry text.
69
- const safeInput = prepareForPreview(input, redact);
70
- const safeOutput = output === undefined
71
- ? undefined
72
- : prepareForPreview(output, redact);
73
- const safeErrorMessage = redactErrorMessage(errorMessage, redact);
74
- const inputPreview = truncateUtf8(stringifyPreview(safeInput), MAX_PREVIEW_BYTES);
75
- const source = truncateUtf8(buildToolCallSource(toolName, safeInput), MAX_SOURCE_BYTES);
76
- const resultPreview = safeOutput === undefined
126
+ const assembleToolCallEvent = (candidate, input) => {
127
+ const inputPreview = truncateUtf8(stringifyPreview(candidate.input), MAX_PREVIEW_BYTES);
128
+ const source = truncateUtf8(buildToolCallSource(candidate.toolName, candidate.input), MAX_SOURCE_BYTES);
129
+ const resultPreview = candidate.output === undefined
77
130
  ? null
78
- : truncateUtf8(stringifyPreview(safeOutput), MAX_PREVIEW_BYTES);
79
- const t = redactTelemetry(normalizeTelemetryArgs(telemetry), redact);
131
+ : truncateUtf8(stringifyPreview(candidate.output), MAX_PREVIEW_BYTES);
132
+ const t = normalizeTelemetryArgs(candidate.telemetry);
80
133
  return {
81
- ...workflowStamp(workflowRunId),
82
- event_id: buildEventId({ actorId, requestId, kind: "tool_call" }),
134
+ ...workflowStamp(input.workflowRunId),
135
+ event_id: buildEventId({ actorId: input.actorId, requestId: input.requestId, kind: "tool_call" }),
83
136
  kind: "tool_call",
84
- actor_id: actorId,
85
- session_id_hint: sessionId ?? null,
86
- started_at: startedAt,
87
- finished_at: finishedAt,
88
- duration_ms: durationMs,
89
- ok: status === "ok",
90
- error: safeErrorMessage ?? null,
137
+ actor_id: input.actorId,
138
+ session_id_hint: candidate.sessionId ?? null,
139
+ started_at: input.startedAt,
140
+ finished_at: input.finishedAt,
141
+ duration_ms: candidate.durationMs,
142
+ ok: candidate.status === "ok",
143
+ error: candidate.errorMessage ?? null,
91
144
  metadata: {
92
- tool_name: toolName,
145
+ tool_name: candidate.toolName,
93
146
  user_intent: t?.user_intent ?? null,
94
147
  agent_thinking: t?.agent_thinking ?? null,
95
148
  user_frustration: t?.user_frustration ?? null,
@@ -99,6 +152,7 @@ export const buildToolCallEvent = ({ toolName, telemetry, input, output, status,
99
152
  context: t?.agent_thinking ?? null,
100
153
  frustration_level: t?.user_frustration ?? null,
101
154
  input_preview: inputPreview.value,
155
+ ...(input.capabilityRequest ? { capability_request: true } : {}),
102
156
  },
103
157
  script_source: source.value,
104
158
  script_source_truncated: source.truncated,
@@ -109,6 +163,30 @@ export const buildToolCallEvent = ({ toolName, telemetry, input, output, status,
109
163
  search_calls: [],
110
164
  };
111
165
  };
166
+ export const buildToolCallEvent = (input) => {
167
+ return assembleToolCallEvent(prepareToolCallCandidate(input), input);
168
+ };
169
+ export const finalizeToolCallEvent = async (input) => {
170
+ let candidate = prepareToolCallCandidate(input);
171
+ if (input.redactEvent) {
172
+ try {
173
+ const redacted = await input.redactEvent(candidate);
174
+ if (redacted === null)
175
+ return null;
176
+ candidate = redacted;
177
+ }
178
+ catch {
179
+ candidate = {
180
+ ...candidate,
181
+ input: REDACTION_FAILED_PLACEHOLDER,
182
+ output: REDACTION_FAILED_PLACEHOLDER,
183
+ errorMessage: REDACTION_FAILED_PLACEHOLDER,
184
+ telemetry: undefined,
185
+ };
186
+ }
187
+ }
188
+ return assembleToolCallEvent(candidate, input);
189
+ };
112
190
  export const buildSessionInitEvent = ({ actorId, sessionId, startedAt, extra, clientInfo, workflowRunId, }) => {
113
191
  return {
114
192
  ...workflowStamp(workflowRunId),
@@ -146,8 +224,10 @@ export const buildSessionInitEvent = ({ actorId, sessionId, startedAt, extra, cl
146
224
  search_calls: [],
147
225
  };
148
226
  };
149
- export const buildBatch = ({ event, extra, actorId, startedAt, sessionInitKeys, clientInfo, workflowRunId, }) => {
227
+ export const buildBatch = ({ event, identityEvent, extra, actorId, startedAt, sessionInitKeys, clientInfo, workflowRunId, }) => {
150
228
  const events = [];
229
+ if (identityEvent)
230
+ events.push(identityEvent);
151
231
  if (extra?.sessionId) {
152
232
  const key = `${actorId}:${extra.sessionId}`;
153
233
  if (!sessionInitKeys.has(key)) {
@@ -165,14 +245,18 @@ export const buildBatch = ({ event, extra, actorId, startedAt, sessionInitKeys,
165
245
  events.push(event);
166
246
  return { schema_version: SCHEMA_VERSION, events };
167
247
  };
168
- export const buildSessionInitBatch = ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, workflowRunId, }) => {
248
+ export const buildSessionInitBatch = ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, workflowRunId, identityEvent, }) => {
169
249
  const key = `${actorId}:${sessionId}`;
170
- if (sessionInitKeys.has(key))
171
- return null;
250
+ if (sessionInitKeys.has(key)) {
251
+ return identityEvent
252
+ ? { schema_version: SCHEMA_VERSION, events: [identityEvent] }
253
+ : null;
254
+ }
172
255
  sessionInitKeys.add(key);
173
256
  return {
174
257
  schema_version: SCHEMA_VERSION,
175
258
  events: [
259
+ ...(identityEvent ? [identityEvent] : []),
176
260
  buildSessionInitEvent({
177
261
  actorId,
178
262
  sessionId,