@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
@@ -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, 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, }: {
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,7 +27,14 @@ export declare const buildToolCallEvent: ({ toolName, telemetry, input, output,
22
27
  startedAt: string;
23
28
  finishedAt: string;
24
29
  workflowRunId?: string;
25
- }) => AnalyticsIngestEvent;
30
+ capabilityRequest?: boolean;
31
+ redact?: RedactFunction;
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>;
26
38
  export declare const buildSessionInitEvent: ({ actorId, sessionId, startedAt, extra, clientInfo, workflowRunId, }: {
27
39
  actorId: string;
28
40
  sessionId: string;
@@ -31,8 +43,9 @@ export declare const buildSessionInitEvent: ({ actorId, sessionId, startedAt, ex
31
43
  clientInfo?: McpClientInfo;
32
44
  workflowRunId?: string;
33
45
  }) => AnalyticsIngestEvent;
34
- export declare const buildBatch: ({ event, extra, actorId, startedAt, sessionInitKeys, clientInfo, workflowRunId, }: {
46
+ export declare const buildBatch: ({ event, identityEvent, extra, actorId, startedAt, sessionInitKeys, clientInfo, workflowRunId, }: {
35
47
  event: AnalyticsIngestEvent;
48
+ identityEvent?: AnalyticsIngestEvent;
36
49
  extra?: RequestExtra;
37
50
  actorId: string;
38
51
  startedAt: string;
@@ -40,7 +53,7 @@ export declare const buildBatch: ({ event, extra, actorId, startedAt, sessionIni
40
53
  clientInfo?: McpClientInfo;
41
54
  workflowRunId?: string;
42
55
  }) => AnalyticsIngestBatch;
43
- export declare const buildSessionInitBatch: ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, workflowRunId, }: {
56
+ export declare const buildSessionInitBatch: ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, workflowRunId, identityEvent, }: {
44
57
  actorId: string;
45
58
  sessionId: string;
46
59
  startedAt: string;
@@ -48,6 +61,7 @@ export declare const buildSessionInitBatch: ({ actorId, sessionId, startedAt, ex
48
61
  sessionInitKeys: BoundedKeySet;
49
62
  clientInfo?: McpClientInfo;
50
63
  workflowRunId?: string;
64
+ identityEvent?: AnalyticsIngestEvent;
51
65
  }) => AnalyticsIngestBatch | null;
52
66
  export declare const normalizeSessionId: (eventSessionId: string | undefined, extra: RequestExtra | undefined) => string | undefined;
53
67
  export declare const normalizeRequestId: (eventRequestId: string | undefined) => string;
@@ -1,5 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { normalizeTelemetryArgs } from "./schema.js";
3
+ import { prepareForPreview, REDACTION_FAILED_PLACEHOLDER, } from "./sanitize.js";
4
+ import { redactSecretsInString } from "./redact-secrets.js";
3
5
  import { MAX_CAPABILITIES_BYTES, MAX_PREVIEW_BYTES, MAX_SOURCE_BYTES, SCHEMA_VERSION, headerValue, isRecord, sha256Hex, stringifyPreview, truncateUtf8, } from "./utils.js";
4
6
  const trimOrUndefined = (value) => {
5
7
  if (typeof value !== "string")
@@ -25,9 +27,94 @@ export const buildActorId = ({ actorSeed, }) => {
25
27
  export const buildEventId = ({ actorId, requestId, kind, }) => {
26
28
  return sha256Hex(`${actorId} ${kind} ${requestId}`);
27
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
+ };
28
51
  const buildToolCallSource = (toolName, input) => {
29
52
  return `MCP tool call: ${toolName}\n\nInput:\n${stringifyPreview(input)}`;
30
53
  };
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;
77
+ try {
78
+ return normalizeTelemetryArgs(redact(protectedTelemetry));
79
+ }
80
+ catch {
81
+ return undefined;
82
+ }
83
+ };
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;
92
+ try {
93
+ const redacted = redact(protectedMessage);
94
+ return typeof redacted === "string" ? redacted : stringifyPreview(redacted);
95
+ }
96
+ catch {
97
+ return REDACTION_FAILED_PLACEHOLDER;
98
+ }
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
+ };
31
118
  // Marks an event as synthetic traffic from an Armature workflow run so
32
119
  // Session Analytics can exclude it. Spread first in the event literal —
33
120
  // absent when the call did not originate from a workflow run.
@@ -36,27 +123,26 @@ const workflowStamp = (workflowRunId) => {
36
123
  return {};
37
124
  return { is_workflow: true, workflow_run_id: workflowRunId };
38
125
  };
39
- export const buildToolCallEvent = ({ toolName, telemetry, input, output, status, durationMs, errorMessage, actorId, sessionId, requestId, startedAt, finishedAt, workflowRunId, }) => {
40
- const inputPreview = truncateUtf8(stringifyPreview(input), MAX_PREVIEW_BYTES);
41
- const source = truncateUtf8(buildToolCallSource(toolName, input), MAX_SOURCE_BYTES);
42
- const resultPreview = output === 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
43
130
  ? null
44
- : truncateUtf8(stringifyPreview(output), MAX_PREVIEW_BYTES);
45
- const t = normalizeTelemetryArgs(telemetry);
131
+ : truncateUtf8(stringifyPreview(candidate.output), MAX_PREVIEW_BYTES);
132
+ const t = normalizeTelemetryArgs(candidate.telemetry);
46
133
  return {
47
- ...workflowStamp(workflowRunId),
48
- 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" }),
49
136
  kind: "tool_call",
50
- actor_id: actorId,
51
- session_id_hint: sessionId ?? null,
52
- started_at: startedAt,
53
- finished_at: finishedAt,
54
- duration_ms: durationMs,
55
- ok: status === "ok",
56
- error: errorMessage ?? 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,
57
144
  metadata: {
58
- tool_name: toolName,
59
- user_turn: t?.user_turn ?? null,
145
+ tool_name: candidate.toolName,
60
146
  user_intent: t?.user_intent ?? null,
61
147
  agent_thinking: t?.agent_thinking ?? null,
62
148
  user_frustration: t?.user_frustration ?? null,
@@ -66,6 +152,7 @@ export const buildToolCallEvent = ({ toolName, telemetry, input, output, status,
66
152
  context: t?.agent_thinking ?? null,
67
153
  frustration_level: t?.user_frustration ?? null,
68
154
  input_preview: inputPreview.value,
155
+ ...(input.capabilityRequest ? { capability_request: true } : {}),
69
156
  },
70
157
  script_source: source.value,
71
158
  script_source_truncated: source.truncated,
@@ -76,6 +163,30 @@ export const buildToolCallEvent = ({ toolName, telemetry, input, output, status,
76
163
  search_calls: [],
77
164
  };
78
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
+ };
79
190
  export const buildSessionInitEvent = ({ actorId, sessionId, startedAt, extra, clientInfo, workflowRunId, }) => {
80
191
  return {
81
192
  ...workflowStamp(workflowRunId),
@@ -113,8 +224,10 @@ export const buildSessionInitEvent = ({ actorId, sessionId, startedAt, extra, cl
113
224
  search_calls: [],
114
225
  };
115
226
  };
116
- export const buildBatch = ({ event, extra, actorId, startedAt, sessionInitKeys, clientInfo, workflowRunId, }) => {
227
+ export const buildBatch = ({ event, identityEvent, extra, actorId, startedAt, sessionInitKeys, clientInfo, workflowRunId, }) => {
117
228
  const events = [];
229
+ if (identityEvent)
230
+ events.push(identityEvent);
118
231
  if (extra?.sessionId) {
119
232
  const key = `${actorId}:${extra.sessionId}`;
120
233
  if (!sessionInitKeys.has(key)) {
@@ -132,14 +245,18 @@ export const buildBatch = ({ event, extra, actorId, startedAt, sessionInitKeys,
132
245
  events.push(event);
133
246
  return { schema_version: SCHEMA_VERSION, events };
134
247
  };
135
- export const buildSessionInitBatch = ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, workflowRunId, }) => {
248
+ export const buildSessionInitBatch = ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, workflowRunId, identityEvent, }) => {
136
249
  const key = `${actorId}:${sessionId}`;
137
- if (sessionInitKeys.has(key))
138
- return null;
250
+ if (sessionInitKeys.has(key)) {
251
+ return identityEvent
252
+ ? { schema_version: SCHEMA_VERSION, events: [identityEvent] }
253
+ : null;
254
+ }
139
255
  sessionInitKeys.add(key);
140
256
  return {
141
257
  schema_version: SCHEMA_VERSION,
142
258
  events: [
259
+ ...(identityEvent ? [identityEvent] : []),
143
260
  buildSessionInitEvent({
144
261
  actorId,
145
262
  sessionId,
@@ -1,7 +1,10 @@
1
- export type { ActorIdResolver, ActorIdResolverInput, AnalyticsEventKind, AnalyticsIngestBatch, AnalyticsIngestEvent, AnalyticsRecorder, ExtractedToolArguments, HeaderBag, InstrumentToolCallEvent, JsonObjectSchema, McpAnalyticsConfig, McpClientInfo, McpServerInfo, RecordSessionInitEvent, RecordToolCallEvent, RegisteredToolHandler, RequestExtra, TelemetryArgs, TelemetryEmitter, ToolCallHandler, ToolDefinition, ToolHandlerContext, ToolRegistration, WithMcpAnalyticsResult, } from "./types.js";
2
- export { appendTelemetryHint, createTelemetryInputSchema, createTelemetryJsonSchema, decorateInputSchemaWithTelemetry, extractTelemetryArguments, normalizeTelemetryArgs, } from "./schema.js";
3
- export { buildActorId, buildEventId, buildSessionInitEvent, buildToolCallEvent, normalizeSessionId, } from "./events.js";
4
- export { defaultMcpAnalyticsConfig, emitTelemetryEvent, postTelemetryEvent, } from "./emit.js";
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";
3
+ export { BASE64_REMOVED_PLACEHOLDER, BINARY_REMOVED_PLACEHOLDER, prepareForPreview, REDACTION_FAILED_PLACEHOLDER, sanitizeValue, SANITIZATION_BUDGET, } from "./sanitize.js";
4
+ export { normalizeSensitiveFieldName, redactSecretsInString, redactSecretsInValue, SECRET_PATTERN_RULES, SENSITIVE_FIELD_NAMES, type SecretPatternRule, } from "./redact-secrets.js";
5
+ export { createPrivacyQueue, PRIVACY_QUEUE_BATCH_SIZE, PRIVACY_QUEUE_CAPACITY, type PrivacyQueue, type PrivacyQueueFinalizer, } from "./queue.js";
6
+ export { buildActorId, buildActorIdentityEvent, buildEventId, buildSessionInitEvent, buildToolCallEvent, finalizeToolCallEvent, normalizeSessionId, type BuildToolCallEventInput, } from "./events.js";
7
+ export { defaultMcpAnalyticsConfig, emitTelemetryEvent, postTelemetryEvent, reportEmitError, } from "./emit.js";
5
8
  export { createAnalyticsRecorder } from "./recorder.js";
6
9
  export { buildStatelessSessionId, parseStatelessSessionClientInfo, resolveStatelessHttpSession, type StatelessHttpSession, } from "./stateless-http.js";
7
10
  export { createMcpAnalyticsServer, withMcpAnalytics } from "./server.js";