@armature-tech/mcp-analytics 0.6.18 → 0.6.20

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 +65 -0
  8. package/dist/cjs/doctor.js +342 -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 +65 -0
  32. package/dist/esm/doctor.js +331 -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
@@ -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,
@@ -1,8 +1,10 @@
1
- export type { ActorIdResolver, ActorIdResolverInput, AnalyticsEventKind, AnalyticsIngestBatch, AnalyticsIngestEvent, AnalyticsRecorder, ExtractedToolArguments, HeaderBag, InstrumentToolCallEvent, JsonObjectSchema, McpAnalyticsConfig, McpClientInfo, McpServerInfo, RecordSessionInitEvent, RecordToolCallEvent, RedactFunction, RegisteredToolHandler, RequestExtra, TelemetryArgs, TelemetryEmitter, TelemetryFieldMap, TelemetryMode, ToolCallHandler, ToolDefinition, ToolHandlerContext, ToolRegistration, WithMcpAnalyticsResult, } from "./types.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
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, } from "./sanitize.js";
4
- export { buildActorId, buildEventId, buildSessionInitEvent, buildToolCallEvent, normalizeSessionId, } from "./events.js";
5
- export { defaultMcpAnalyticsConfig, emitTelemetryEvent, postTelemetryEvent, } from "./emit.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";
6
8
  export { createAnalyticsRecorder } from "./recorder.js";
7
9
  export { buildStatelessSessionId, parseStatelessSessionClientInfo, resolveStatelessHttpSession, type StatelessHttpSession, } from "./stateless-http.js";
8
10
  export { createMcpAnalyticsServer, withMcpAnalytics } from "./server.js";
package/dist/esm/index.js CHANGED
@@ -1,7 +1,9 @@
1
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, } from "./sanitize.js";
3
- export { buildActorId, buildEventId, buildSessionInitEvent, buildToolCallEvent, normalizeSessionId, } from "./events.js";
4
- export { defaultMcpAnalyticsConfig, emitTelemetryEvent, postTelemetryEvent, } from "./emit.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";
5
7
  export { createAnalyticsRecorder } from "./recorder.js";
6
8
  export { buildStatelessSessionId, parseStatelessSessionClientInfo, resolveStatelessHttpSession, } from "./stateless-http.js";
7
9
  export { createMcpAnalyticsServer, withMcpAnalytics } from "./server.js";
@@ -1,6 +1,8 @@
1
1
  import { createAnalyticsRecorder } from "./recorder.js";
2
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;
@@ -137,9 +139,49 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
137
139
  // passes the constraint without a cast.
138
140
  export const wrapMastraToolsWithRecorder = (tools, recorder, config = {}, options = {}) => {
139
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
+ }
140
151
  for (const [key, tool] of Object.entries(tools)) {
141
152
  out[key] = wrapOneTool(key, tool, recorder, config, options.resolveExtra);
142
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
+ }
143
185
  return out;
144
186
  };
145
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
+ };