@armature-tech/mcp-analytics 0.6.25 → 0.6.27

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.
package/dist/cjs/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.instrumentMcpServerTools = exports.withMcpAnalytics = exports.createMcpAnalyticsServer = exports.resolveStatelessHttpSession = exports.parseStatelessSessionClientInfo = exports.buildStatelessSessionId = exports.createAnalyticsRecorder = exports.reportEmitError = exports.postTelemetryEvent = exports.IngestDeliveryError = exports.emitTelemetryEvent = exports.defaultMcpAnalyticsConfig = exports.DEFAULT_INGEST_RETRY_DELAY_MS = exports.DEFAULT_INGEST_MAX_ATTEMPTS = exports.normalizeSessionId = exports.finalizeToolCallEvent = exports.buildToolCallEvent = exports.buildSessionInitEvent = exports.buildEventId = exports.buildActorIdentityEvent = exports.buildActorId = exports.PRIVACY_QUEUE_CAPACITY = exports.PRIVACY_QUEUE_BATCH_SIZE = exports.createPrivacyQueue = exports.SENSITIVE_FIELD_NAMES = exports.SECRET_PATTERN_RULES = exports.redactSecretsInValue = exports.redactSecretsInString = exports.normalizeSensitiveFieldName = exports.SANITIZATION_BUDGET = exports.sanitizeValue = exports.REDACTION_FAILED_PLACEHOLDER = exports.prepareForPreview = exports.BINARY_REMOVED_PLACEHOLDER = exports.BASE64_REMOVED_PLACEHOLDER = exports.schemaDeclaresTelemetry = exports.planToolTelemetry = exports.normalizeTelemetryArgs = exports.isCaptureEnabled = exports.extractTelemetryArguments = exports.decorateInputSchemaWithTelemetry = exports.createTelemetryJsonSchema = exports.createTelemetryInputSchema = exports.applyTelemetryFieldMap = exports.appendTelemetryHint = void 0;
3
+ exports.instrumentMcpServerTools = exports.withMcpAnalytics = exports.createMcpAnalyticsServer = exports.resolveStatelessHttpSession = exports.parseStatelessSessionClientInfo = exports.buildStatelessSessionId = exports.createAnalyticsRecorder = exports.reportEmitError = exports.postTelemetryEvent = exports.IngestRejectedError = exports.emitTelemetryEvent = exports.defaultMcpAnalyticsConfig = exports.normalizeSessionId = exports.finalizeToolCallEvent = exports.buildToolCallEvent = exports.buildSessionInitEvent = exports.buildEventId = exports.buildActorIdentityEvent = exports.buildActorId = exports.PRIVACY_QUEUE_CAPACITY = exports.PRIVACY_QUEUE_BATCH_SIZE = exports.createPrivacyQueue = exports.SENSITIVE_FIELD_NAMES = exports.SECRET_PATTERN_RULES = exports.redactSecretsInValue = exports.redactSecretsInString = exports.normalizeSensitiveFieldName = exports.SANITIZATION_BUDGET = exports.sanitizeValue = exports.REDACTION_FAILED_PLACEHOLDER = exports.prepareForPreview = exports.BINARY_REMOVED_PLACEHOLDER = exports.BASE64_REMOVED_PLACEHOLDER = exports.schemaDeclaresTelemetry = exports.planToolTelemetry = exports.normalizeTelemetryArgs = exports.isCaptureEnabled = exports.extractTelemetryArguments = exports.decorateInputSchemaWithTelemetry = exports.createTelemetryJsonSchema = exports.createTelemetryInputSchema = exports.applyTelemetryFieldMap = exports.appendTelemetryHint = void 0;
4
4
  var schema_js_1 = require("./schema.js");
5
5
  Object.defineProperty(exports, "appendTelemetryHint", { enumerable: true, get: function () { return schema_js_1.appendTelemetryHint; } });
6
6
  Object.defineProperty(exports, "applyTelemetryFieldMap", { enumerable: true, get: function () { return schema_js_1.applyTelemetryFieldMap; } });
@@ -38,11 +38,9 @@ Object.defineProperty(exports, "buildToolCallEvent", { enumerable: true, get: fu
38
38
  Object.defineProperty(exports, "finalizeToolCallEvent", { enumerable: true, get: function () { return events_js_1.finalizeToolCallEvent; } });
39
39
  Object.defineProperty(exports, "normalizeSessionId", { enumerable: true, get: function () { return events_js_1.normalizeSessionId; } });
40
40
  var emit_js_1 = require("./emit.js");
41
- Object.defineProperty(exports, "DEFAULT_INGEST_MAX_ATTEMPTS", { enumerable: true, get: function () { return emit_js_1.DEFAULT_INGEST_MAX_ATTEMPTS; } });
42
- Object.defineProperty(exports, "DEFAULT_INGEST_RETRY_DELAY_MS", { enumerable: true, get: function () { return emit_js_1.DEFAULT_INGEST_RETRY_DELAY_MS; } });
43
41
  Object.defineProperty(exports, "defaultMcpAnalyticsConfig", { enumerable: true, get: function () { return emit_js_1.defaultMcpAnalyticsConfig; } });
44
42
  Object.defineProperty(exports, "emitTelemetryEvent", { enumerable: true, get: function () { return emit_js_1.emitTelemetryEvent; } });
45
- Object.defineProperty(exports, "IngestDeliveryError", { enumerable: true, get: function () { return emit_js_1.IngestDeliveryError; } });
43
+ Object.defineProperty(exports, "IngestRejectedError", { enumerable: true, get: function () { return emit_js_1.IngestRejectedError; } });
46
44
  Object.defineProperty(exports, "postTelemetryEvent", { enumerable: true, get: function () { return emit_js_1.postTelemetryEvent; } });
47
45
  Object.defineProperty(exports, "reportEmitError", { enumerable: true, get: function () { return emit_js_1.reportEmitError; } });
48
46
  var recorder_js_1 = require("./recorder.js");
package/dist/cjs/queue.js CHANGED
@@ -26,9 +26,7 @@ const createPrivacyQueue = (config) => {
26
26
  }
27
27
  const emit = async (batch) => {
28
28
  const emitter = config.armature?.emit
29
- ?? (async (value) => {
30
- await (0, emit_js_1.postTelemetryEvent)(value, config);
31
- });
29
+ ?? ((value) => (0, emit_js_1.postAndCheck)(value, config));
32
30
  try {
33
31
  await emitter(batch);
34
32
  }
@@ -177,8 +177,8 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
177
177
  durationMs,
178
178
  finishedAtMs,
179
179
  });
180
- const requestId = (0, events_js_1.normalizeRequestId)(event.requestId);
181
180
  const sessionId = resolveSessionId(event);
181
+ const requestId = (0, events_js_1.normalizeRequestId)(event.requestId, sessionId);
182
182
  const errorMessage = event.error === undefined
183
183
  ? undefined
184
184
  : event.error instanceof Error
package/dist/esm/cli.js CHANGED
@@ -11,7 +11,6 @@ const usage = "Armature MCP analytics doctor\n"
11
11
  + " - the local project declares an Armature SDK dependency\n"
12
12
  + " - MCP initialize and tools/list succeed\n"
13
13
  + " - every served tool exposes the Armature telemetry contract\n"
14
- + " - marked ingest keys match the MCP and ingest endpoint regions\n"
15
14
  + " - the existing ingest endpoint accepts the configured key\n"
16
15
  + "\n"
17
16
  + "Options:\n"
@@ -22,7 +21,10 @@ const usage = "Armature MCP analytics doctor\n"
22
21
  + " --bearer-env <name> Read an HTTP bearer token from an environment variable\n"
23
22
  + " --cwd <path> Project directory for dependency detection and stdio spawn\n"
24
23
  + " --timeout <ms> Per-check timeout (default: 10000)\n"
25
- + " --capture <on|off> Expected telemetry capture state (default: on)\n"
24
+ + " --capture <on|off> Expected telemetry capture state (default: on).\n"
25
+ + " Use off for hooks-only or captureTelemetry=false\n"
26
+ + " servers, where tools are intentionally unwrapped\n"
27
+ + " (tool-call/session analytics still flow).\n"
26
28
  + " --skip-ingest Do not send the empty authenticated ingest health probe\n"
27
29
  + " --json Print a machine-readable report\n"
28
30
  + " --help Show this help\n"
@@ -1,4 +1,3 @@
1
- type DeploymentRegion = "us" | "eu";
2
1
  export type DoctorStatus = "pass" | "warn" | "fail";
3
2
  export type DoctorCheck = {
4
3
  id: string;
@@ -49,8 +48,6 @@ export type DoctorDependencies = {
49
48
  detectLocalSdks: (cwd: string) => Promise<LocalSdk[]>;
50
49
  verifyIngest: (endpoint: string, apiKey: string, timeoutMs: number) => Promise<void>;
51
50
  };
52
- export declare const regionFromIngestKey: (apiKey: string | undefined) => DeploymentRegion | undefined;
53
- export declare const regionFromArmatureUrl: (rawUrl: string | undefined) => DeploymentRegion | undefined;
54
51
  export declare const inspectMcp: (options: DoctorOptions) => Promise<McpInspection>;
55
52
  export declare const classifyToolInstrumentation: (tool: DoctorTool) => "current" | "legacy" | "owned" | "missing";
56
53
  export declare const isSdkOwnedCapabilityTool: (tool: DoctorTool) => boolean;
@@ -66,4 +63,3 @@ export declare const detectLocalSdks: (cwd: string) => Promise<LocalSdk[]>;
66
63
  export declare const verifyIngest: (endpoint: string, apiKey: string, timeoutMs: number) => Promise<void>;
67
64
  export declare const runDoctor: (options: DoctorOptions, dependencies?: DoctorDependencies, environment?: NodeJS.ProcessEnv) => Promise<DoctorReport>;
68
65
  export declare const defaultDoctorOptions: (target: DoctorTarget) => DoctorOptions;
69
- export {};
@@ -17,54 +17,6 @@ const errorMessage = (error) => {
17
17
  return error.message;
18
18
  return String(error || "unknown error");
19
19
  };
20
- const regionLabel = (region) => region.toUpperCase();
21
- export const regionFromIngestKey = (apiKey) => {
22
- if (!apiKey)
23
- return undefined;
24
- const marked = apiKey.match(/^ami_(us|eu)_/i)?.[1]?.toLowerCase();
25
- if (marked === "us" || marked === "eu")
26
- return marked;
27
- // Legacy unmarked keys remain US for backward compatibility.
28
- return /^ami_[a-z0-9]/i.test(apiKey) ? "us" : undefined;
29
- };
30
- export const regionFromArmatureUrl = (rawUrl) => {
31
- if (!rawUrl)
32
- return undefined;
33
- try {
34
- const hostname = new URL(rawUrl).hostname.toLowerCase();
35
- if (hostname === "eu.armature.tech"
36
- || hostname.endsWith(".eu.armature.tech"))
37
- return "eu";
38
- if (hostname === "app.armature.tech" || hostname === "mcp.armature.tech")
39
- return "us";
40
- }
41
- catch {
42
- return undefined;
43
- }
44
- return undefined;
45
- };
46
- const regionalConfigurationCheck = (target, endpoint, apiKey) => {
47
- const sources = [
48
- { label: "ingest key", region: regionFromIngestKey(apiKey) },
49
- { label: "ingest endpoint", region: regionFromArmatureUrl(endpoint) },
50
- {
51
- label: "MCP target",
52
- region: target.kind === "http" ? regionFromArmatureUrl(target.url) : undefined,
53
- },
54
- ];
55
- const recognized = sources.filter((source) => source.region !== undefined);
56
- const distinct = new Set(recognized.map((source) => source.region));
57
- if (distinct.size > 1) {
58
- return fail("regional-configuration", "Regional configuration", recognized.map((source) => `${source.label} is ${regionLabel(source.region)}`).join(", ") + ".", "Use an ingest key, ingest endpoint, and MCP application URL from the same region. The doctor will not probe a mismatched endpoint.");
59
- }
60
- if (recognized.length >= 2) {
61
- const region = recognized[0]?.region;
62
- return pass("regional-configuration", "Regional configuration", `${recognized.map((source) => source.label).join(" and ")} agree on ${regionLabel(region)}.`);
63
- }
64
- return warn("regional-configuration", "Regional configuration", recognized.length === 1
65
- ? `Only the ${recognized[0]?.label} identifies a known Armature region.`
66
- : "The key and URLs do not identify a known Armature region.", "For production, use an ami_us_ or ami_eu_ key and the matching regional Armature URLs.");
67
- };
68
20
  const withTimeout = async (promise, timeoutMs, label) => {
69
21
  let timer;
70
22
  try {
@@ -270,17 +222,54 @@ export const verifyIngest = async (endpoint, apiKey, timeoutMs) => {
270
222
  body: JSON.stringify({ schema_version: 1, events: [] }),
271
223
  signal: controller.signal,
272
224
  });
273
- // Drain the body so undici can release its pooled connection promptly and
274
- // the one-shot CLI does not appear to hang after printing the report.
275
- await response.arrayBuffer();
225
+ // Read the body so undici can release its pooled connection promptly (the
226
+ // one-shot CLI must not appear to hang) and so we can surface an in-band
227
+ // rejection — ingest answers 200 even when it refuses events (#1403). The
228
+ // health probe sends an empty batch, so a rejection here signals the server
229
+ // is refusing well-formed authenticated requests, not a per-event issue.
230
+ const text = await response.text();
276
231
  if (!response.ok) {
277
232
  throw new Error(`Armature ingest returned HTTP ${response.status}`);
278
233
  }
234
+ try {
235
+ const parsed = JSON.parse(text || "{}");
236
+ if (Array.isArray(parsed.rejected) && parsed.rejected.length > 0) {
237
+ const reasons = Array.from(new Set(parsed.rejected
238
+ .map((item) => (isRecord(item) && typeof item.reason === "string" ? item.reason : null))
239
+ .filter((reason) => Boolean(reason))));
240
+ throw new Error(`Armature ingest refused the health probe: ${parsed.rejected.length} event(s) rejected`
241
+ + (reasons.length > 0 ? ` (${reasons.join(", ")})` : ""));
242
+ }
243
+ }
244
+ catch (error) {
245
+ if (error instanceof Error && error.message.startsWith("Armature ingest refused"))
246
+ throw error;
247
+ // A non-JSON 200 body is not a rejection signal; reachability already passed.
248
+ }
279
249
  }
280
250
  finally {
281
251
  clearTimeout(timer);
282
252
  }
283
253
  };
254
+ // The tool-wrapping remediation must name the API of the SDK the doctor
255
+ // actually detected — telling a Go customer to "register tools inside
256
+ // withMcpAnalytics" (a TypeScript-only helper) sends them in circles,
257
+ // especially when they are already using an Armature recorder (the
258
+ // documented Go hooks-only shape: NewRecorder + WithHooks). `language`
259
+ // is the SDK detected by detectLocalSdks; undefined falls back to a
260
+ // cross-language phrasing.
261
+ const wrapApiFor = (language) => {
262
+ switch (language) {
263
+ case "go":
264
+ return "InstrumentTool / InstrumentToolWithConfig";
265
+ case "python":
266
+ return "instrument_fastmcp (or an Armature recorder)";
267
+ case "typescript":
268
+ return "withMcpAnalytics (or an Armature recorder)";
269
+ default:
270
+ return "the SDK's tool instrumentation (InstrumentTool / withMcpAnalytics / instrument_fastmcp)";
271
+ }
272
+ };
284
273
  const pass = (id, label, detail) => ({
285
274
  id, label, detail, status: "pass",
286
275
  });
@@ -292,8 +281,12 @@ const fail = (id, label, detail, remediation) => ({
292
281
  });
293
282
  export const runDoctor = async (options, dependencies = { inspectMcp, detectLocalSdks, verifyIngest }, environment = process.env) => {
294
283
  const checks = [];
284
+ // Remember the detected SDK so the wrapping check can phrase its fix in
285
+ // that language's API (the first detected wins if several coexist).
286
+ let detectedLanguage;
295
287
  try {
296
288
  const sdks = await dependencies.detectLocalSdks(options.cwd);
289
+ detectedLanguage = sdks[0]?.language;
297
290
  if (sdks.length === 0) {
298
291
  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."));
299
292
  }
@@ -317,12 +310,14 @@ export const runDoctor = async (options, dependencies = { inspectMcp, detectLoca
317
310
  if (!options.expectCapture) {
318
311
  const exposed = coverage.current.length + coverage.legacy.length;
319
312
  checks.push(exposed === 0
320
- ? pass("tool-wrapping", "Telemetry capture", "No Armature telemetry fields are advertised, as requested.")
313
+ ? pass("tool-wrapping", "Telemetry capture", "No Armature telemetry fields are advertised, as requested. "
314
+ + `Tool-call and session analytics still flow; capturing user_intent/agent_thinking requires wrapping tools with ${wrapApiFor(detectedLanguage)}.`)
321
315
  : warn("tool-wrapping", "Telemetry capture", `${exposed}/${coverage.total} tools still advertise Armature telemetry fields.`, "Confirm captureTelemetry=false is applied before tools are registered."));
322
316
  }
323
317
  else if (coverage.missing.length > 0) {
324
318
  const sample = coverage.missing.slice(0, 5).join(", ");
325
- 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."));
319
+ 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 with ${wrapApiFor(detectedLanguage)}. `
320
+ + "If this server intentionally uses hooks-only capture (an Armature recorder + hooks, no per-tool wrapping), tool-call and session analytics still flow — re-run with --capture off to treat unwrapped tools as expected and keep exit 0."));
326
321
  }
327
322
  else if (coverage.legacy.length > 0) {
328
323
  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."));
@@ -344,20 +339,15 @@ export const runDoctor = async (options, dependencies = { inspectMcp, detectLoca
344
339
  ? "Start the MCP server, verify the URL/auth headers, and run the doctor again."
345
340
  : "Run the server command directly once, fix startup errors, then run the doctor again."));
346
341
  }
347
- const apiKey = environment.ANALYTICS_INGEST_API_KEY;
348
- const endpoint = environment.ANALYTICS_INGEST_URL || DEFAULT_INGEST_URL;
349
- const regionalCheck = regionalConfigurationCheck(options.target, endpoint, apiKey);
350
- checks.push(regionalCheck);
351
342
  if (options.skipIngest) {
352
343
  checks.push(warn("ingest-auth", "Armature ingest", "Skipped by --skip-ingest; no network request was made."));
353
344
  }
354
345
  else {
346
+ const apiKey = environment.ANALYTICS_INGEST_API_KEY;
347
+ const endpoint = environment.ANALYTICS_INGEST_URL || DEFAULT_INGEST_URL;
355
348
  if (!apiKey) {
356
349
  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."));
357
350
  }
358
- else if (regionalCheck.status === "fail") {
359
- checks.push(fail("ingest-auth", "Armature ingest", "Skipped the authenticated health probe because the regional configuration is inconsistent.", "Correct the regional mismatch, then run the doctor again."));
360
- }
361
351
  else {
362
352
  try {
363
353
  await dependencies.verifyIngest(endpoint, apiKey, options.timeoutMs);
@@ -6,42 +6,43 @@ export declare const defaultMcpAnalyticsConfig: {
6
6
  timeoutMs: number;
7
7
  };
8
8
  };
9
- export declare const DEFAULT_INGEST_MAX_ATTEMPTS = 2;
10
- export declare const DEFAULT_INGEST_RETRY_DELAY_MS = 100;
11
- export declare class IngestDeliveryError extends Error {
12
- readonly code: string;
13
- readonly status?: number;
14
- readonly retryable: boolean;
15
- readonly attempts: number;
16
- constructor(message: string, options: {
17
- code: string;
18
- status?: number;
19
- retryable?: boolean;
20
- attempts: number;
21
- cause?: unknown;
22
- });
23
- }
24
9
  export declare const resolveEndpointUrl: (config: McpAnalyticsConfig) => string;
25
10
  export declare const resolveApiKey: (config: McpAnalyticsConfig) => string | undefined;
26
11
  export declare const resolveActorSeed: (config: McpAnalyticsConfig, input: ActorIdResolverInput) => Promise<string>;
27
12
  /** Resolve the optional caller-provided identifier without interpreting it. */
28
13
  export declare const resolveActorIdentifier: (config: McpAnalyticsConfig, input: ActorIdResolverInput) => Promise<string | undefined>;
29
- export declare const postTelemetryEvent: (batch: AnalyticsIngestBatch, config?: McpAnalyticsConfig) => Promise<{
30
- skipped: boolean;
31
- reason: string;
32
- ok?: undefined;
33
- status?: undefined;
34
- attempts?: undefined;
35
- } | {
14
+ type IngestRejection = {
15
+ event_id?: string | null;
16
+ reason?: string;
17
+ };
18
+ export type IngestResult = {
36
19
  skipped: boolean;
37
- ok: boolean;
38
- status: number;
39
- attempts: number;
40
- reason?: undefined;
41
- }>;
20
+ ok?: boolean;
21
+ reason?: string;
22
+ status?: number;
23
+ accepted?: number;
24
+ rejected?: IngestRejection[];
25
+ duplicateCount?: number;
26
+ };
27
+ /**
28
+ * Ingest answers HTTP 200 even when it refuses events in the response body
29
+ * (validation, quota, schema drift — `rejected` non-empty, or everything
30
+ * refused with nothing accepted). A producer that checks only the status code
31
+ * treats that as delivered and never fires `onError` (#1403). This carries the
32
+ * refusal so the emit path can surface it through the normal error channel.
33
+ */
34
+ export declare class IngestRejectedError extends Error {
35
+ readonly rejected: IngestRejection[];
36
+ readonly accepted: number;
37
+ constructor(rejected: IngestRejection[], accepted: number);
38
+ }
39
+ export declare const describeIngestRejection: (result: IngestResult, eventCount: number) => IngestRejectedError | null;
40
+ export declare const postTelemetryEvent: (batch: AnalyticsIngestBatch, config?: McpAnalyticsConfig) => Promise<IngestResult>;
41
+ export declare const postAndCheck: (batch: AnalyticsIngestBatch, config: McpAnalyticsConfig) => Promise<void>;
42
42
  export declare const reportEmitError: (error: unknown, batch: AnalyticsIngestBatch, config: McpAnalyticsConfig) => void;
43
43
  export declare const emitTelemetryEvent: (batch: AnalyticsIngestBatch, config?: McpAnalyticsConfig) => Promise<void>;
44
44
  export declare const createFlushableEmitter: (config: McpAnalyticsConfig) => {
45
45
  emitBatch: (batch: AnalyticsIngestBatch) => Promise<void>;
46
46
  flush: () => Promise<void>;
47
47
  };
48
+ export {};
package/dist/esm/emit.js CHANGED
@@ -3,42 +3,9 @@ export const defaultMcpAnalyticsConfig = {
3
3
  armature: {
4
4
  endpointUrl: "https://app.armature.tech/api/mcp-analytics/ingest",
5
5
  enabled: true,
6
- timeoutMs: 5_000,
6
+ timeoutMs: 500,
7
7
  },
8
8
  };
9
- export const DEFAULT_INGEST_MAX_ATTEMPTS = 2;
10
- export const DEFAULT_INGEST_RETRY_DELAY_MS = 100;
11
- export class IngestDeliveryError extends Error {
12
- code;
13
- status;
14
- retryable;
15
- attempts;
16
- constructor(message, options) {
17
- super(message, options.cause === undefined ? undefined : { cause: options.cause });
18
- this.name = "IngestDeliveryError";
19
- this.code = options.code;
20
- this.status = options.status;
21
- this.retryable = options.retryable === true;
22
- this.attempts = options.attempts;
23
- }
24
- }
25
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
26
- const responseErrorCode = async (response) => {
27
- const fallback = `ingest_http_${response.status}`;
28
- const text = (await response.text()).slice(0, 4_096);
29
- try {
30
- const payload = JSON.parse(text);
31
- const candidate = typeof payload.error?.code === "string"
32
- ? payload.error.code
33
- : typeof payload.errorCode === "string"
34
- ? payload.errorCode
35
- : fallback;
36
- return /^[a-z0-9][a-z0-9_:-]{0,99}$/i.test(candidate) ? candidate : fallback;
37
- }
38
- catch {
39
- return fallback;
40
- }
41
- };
42
9
  export const resolveEndpointUrl = (config) => {
43
10
  return config.armature?.endpointUrl ??
44
11
  readEnv("ANALYTICS_INGEST_URL") ??
@@ -80,6 +47,39 @@ export const resolveActorIdentifier = async (config, input) => {
80
47
  ? value
81
48
  : undefined;
82
49
  };
50
+ /**
51
+ * Ingest answers HTTP 200 even when it refuses events in the response body
52
+ * (validation, quota, schema drift — `rejected` non-empty, or everything
53
+ * refused with nothing accepted). A producer that checks only the status code
54
+ * treats that as delivered and never fires `onError` (#1403). This carries the
55
+ * refusal so the emit path can surface it through the normal error channel.
56
+ */
57
+ export class IngestRejectedError extends Error {
58
+ rejected;
59
+ accepted;
60
+ constructor(rejected, accepted) {
61
+ const reasons = Array.from(new Set(rejected.map((item) => item?.reason).filter((r) => Boolean(r))));
62
+ const detail = reasons.length > 0 ? ` (${reasons.join(", ")})` : "";
63
+ super(`Armature ingest rejected ${rejected.length} event(s)${detail}`);
64
+ this.name = "IngestRejectedError";
65
+ this.rejected = rejected;
66
+ this.accepted = accepted;
67
+ }
68
+ }
69
+ // A 200 that refuses events in-body: any explicit rejection, or nothing
70
+ // accepted from a non-empty batch. Server-side dedup counts as accepted, so a
71
+ // benign session_init re-delivery does NOT trip this.
72
+ export const describeIngestRejection = (result, eventCount) => {
73
+ if (result.skipped)
74
+ return null;
75
+ const rejected = Array.isArray(result.rejected) ? result.rejected : [];
76
+ const accepted = typeof result.accepted === "number" ? result.accepted : undefined;
77
+ if (rejected.length > 0)
78
+ return new IngestRejectedError(rejected, accepted ?? 0);
79
+ if (accepted === 0 && eventCount > 0)
80
+ return new IngestRejectedError([], 0);
81
+ return null;
82
+ };
83
83
  export const postTelemetryEvent = async (batch, config = defaultMcpAnalyticsConfig) => {
84
84
  const endpointUrl = resolveEndpointUrl(config);
85
85
  const apiKey = resolveApiKey(config);
@@ -87,56 +87,55 @@ export const postTelemetryEvent = async (batch, config = defaultMcpAnalyticsConf
87
87
  return { skipped: true, reason: "ingest_config_missing" };
88
88
  }
89
89
  const body = JSON.stringify(batch);
90
- const timeoutMs = config.armature?.timeoutMs ?? defaultMcpAnalyticsConfig.armature.timeoutMs;
91
- for (let attempt = 1; attempt <= DEFAULT_INGEST_MAX_ATTEMPTS; attempt += 1) {
92
- const controller = new AbortController();
93
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
94
- try {
95
- const response = await fetch(endpointUrl, {
96
- method: "POST",
97
- headers: {
98
- "Content-Type": "application/json",
99
- Authorization: `Bearer ${apiKey}`,
100
- },
101
- body,
102
- signal: controller.signal,
103
- });
104
- if (response.ok) {
105
- return { skipped: false, ok: true, status: response.status, attempts: attempt };
106
- }
107
- const retryable = response.status === 429 || response.status >= 500;
108
- const code = await responseErrorCode(response);
109
- if (retryable && attempt < DEFAULT_INGEST_MAX_ATTEMPTS) {
110
- await sleep(DEFAULT_INGEST_RETRY_DELAY_MS);
111
- continue;
112
- }
113
- throw new IngestDeliveryError(`Armature ingest failed with HTTP ${response.status} (${code})`, { code, status: response.status, retryable, attempts: attempt });
90
+ const controller = new AbortController();
91
+ const timeout = setTimeout(() => controller.abort(), config.armature?.timeoutMs ?? defaultMcpAnalyticsConfig.armature.timeoutMs);
92
+ try {
93
+ const response = await fetch(endpointUrl, {
94
+ method: "POST",
95
+ headers: {
96
+ "Content-Type": "application/json",
97
+ Authorization: `Bearer ${apiKey}`,
98
+ },
99
+ body,
100
+ signal: controller.signal,
101
+ });
102
+ const text = await response.text();
103
+ if (!response.ok) {
104
+ throw new Error(`Armature ingest failed with ${response.status}: ${text}`);
114
105
  }
115
- catch (error) {
116
- if (error instanceof IngestDeliveryError)
117
- throw error;
118
- const timedOut = error?.name === "AbortError";
119
- if (attempt < DEFAULT_INGEST_MAX_ATTEMPTS) {
120
- await sleep(DEFAULT_INGEST_RETRY_DELAY_MS);
121
- continue;
122
- }
123
- throw new IngestDeliveryError(timedOut
124
- ? `Armature ingest timed out after ${timeoutMs}ms`
125
- : "Armature ingest connection failed", {
126
- code: timedOut ? "ingest_timeout" : "ingest_connection_failed",
127
- retryable: true,
128
- attempts: attempt,
129
- cause: error,
130
- });
106
+ // The body carries in-band rejection/dedup even on 200; parse it so the
107
+ // emit path can raise on refused events (#1403). A non-JSON body just
108
+ // means we cannot observe rejections, not a delivery failure.
109
+ let parsed = {};
110
+ try {
111
+ parsed = text ? JSON.parse(text) : {};
131
112
  }
132
- finally {
133
- clearTimeout(timeout);
113
+ catch {
114
+ parsed = {};
134
115
  }
116
+ return {
117
+ skipped: false,
118
+ ok: true,
119
+ status: response.status,
120
+ accepted: typeof parsed.accepted === "number" ? parsed.accepted : undefined,
121
+ rejected: Array.isArray(parsed.rejected) ? parsed.rejected : [],
122
+ duplicateCount: typeof parsed.duplicate_count === "number" ? parsed.duplicate_count : undefined,
123
+ };
124
+ }
125
+ finally {
126
+ clearTimeout(timeout);
135
127
  }
136
- throw new IngestDeliveryError("Armature ingest delivery failed", {
137
- code: "ingest_delivery_failed",
138
- attempts: DEFAULT_INGEST_MAX_ATTEMPTS,
139
- });
128
+ };
129
+ // The default network emit for every delivery path (privacy queue, flushable
130
+ // emitter, one-shot emit): POST, then raise on in-body rejection so the caller's
131
+ // try/catch routes it to `onError`, just like a transport failure. This MUST be
132
+ // the shared default so the recorder's real path (the privacy queue) also
133
+ // surfaces rejections (#1403).
134
+ export const postAndCheck = async (batch, config) => {
135
+ const result = await postTelemetryEvent(batch, config);
136
+ const rejection = describeIngestRejection(result, batch.events.length);
137
+ if (rejection)
138
+ throw rejection;
140
139
  };
141
140
  export const reportEmitError = (error, batch, config) => {
142
141
  const onError = config.armature?.onError;
@@ -152,9 +151,7 @@ export const emitTelemetryEvent = (batch, config = defaultMcpAnalyticsConfig) =>
152
151
  return Promise.resolve();
153
152
  }
154
153
  const emit = config.armature?.emit ??
155
- (async (telemetryBatch) => {
156
- await postTelemetryEvent(telemetryBatch, config);
157
- });
154
+ ((telemetryBatch) => postAndCheck(telemetryBatch, config));
158
155
  const run = async () => {
159
156
  try {
160
157
  await emit(batch);
@@ -178,9 +175,7 @@ export const createFlushableEmitter = (config) => {
178
175
  return Promise.resolve();
179
176
  }
180
177
  const emit = config.armature?.emit ??
181
- (async (telemetryBatch) => {
182
- await postTelemetryEvent(telemetryBatch, config);
183
- });
178
+ ((telemetryBatch) => postAndCheck(telemetryBatch, config));
184
179
  const run = async () => {
185
180
  try {
186
181
  await emit(batch);
@@ -64,7 +64,7 @@ export declare const buildSessionInitBatch: ({ actorId, sessionId, startedAt, ex
64
64
  identityEvent?: AnalyticsIngestEvent;
65
65
  }) => AnalyticsIngestBatch | null;
66
66
  export declare const normalizeSessionId: (eventSessionId: string | undefined, extra: RequestExtra | undefined) => string | undefined;
67
- export declare const normalizeRequestId: (eventRequestId: string | undefined) => string;
67
+ export declare const normalizeRequestId: (eventRequestId: string | undefined, sessionId?: string) => string;
68
68
  export declare const normalizeStartedAt: ({ startedAt, durationMs, finishedAtMs, }: {
69
69
  startedAt?: string | Date | number;
70
70
  durationMs?: number;
@@ -282,10 +282,25 @@ export const normalizeSessionId = (eventSessionId, extra) => {
282
282
  // counter (0, 1, 2, …) that restarts on reconnect, across stateless gateway
283
283
  // instances, etc., so two unrelated tool calls routinely share `extra.requestId`
284
284
  // and would collide on `event_id` — making ingest dedupe the second call away.
285
- // An explicit caller-supplied id still wins (it's a deliberate idempotency key);
286
- // otherwise we mint a fresh uuid, matching the prototype-patch path in server.ts.
287
- export const normalizeRequestId = (eventRequestId) => {
288
- return eventRequestId ?? randomUUID();
285
+ //
286
+ // When no id is supplied we mint a fresh uuid (matching the prototype-patch path
287
+ // in server.ts), which is globally unique and needs no further scoping. A
288
+ // caller-supplied id is treated as a deliberate idempotency key, but is scoped
289
+ // by the resolved session id when one is known: `${sessionId}#${id}`. That keeps
290
+ // within-session idempotency (a genuine retry reusing the same id de-dups) while
291
+ // making a hazardous transport counter reused across concurrent conversations
292
+ // collision-free — two sessions that both send request id "5" hash to different
293
+ // `event_id`s. See the cross-SDK "Event identity and idempotency" section of
294
+ // packages/TELEMETRY-CONTRACT.md.
295
+ export const normalizeRequestId = (eventRequestId, sessionId) => {
296
+ // `== null` also mints for a `null` an untyped JS caller may pass, matching
297
+ // the previous `?? randomUUID()`; a degenerate `null` must never seed a hash.
298
+ // An empty string is equally degenerate — it would collapse every such call
299
+ // into one fixed `${sessionId}#` seed and collide on event_id — so it mints
300
+ // too, matching the Python (`if not event_request_id`) and Go (`== ""`) SDKs.
301
+ if (eventRequestId == null || eventRequestId === "")
302
+ return randomUUID();
303
+ return sessionId ? `${sessionId}#${eventRequestId}` : eventRequestId;
289
304
  };
290
305
  export const normalizeStartedAt = ({ startedAt, durationMs, finishedAtMs, }) => {
291
306
  if (startedAt instanceof Date)
@@ -4,7 +4,7 @@ export { BASE64_REMOVED_PLACEHOLDER, BINARY_REMOVED_PLACEHOLDER, prepareForPrevi
4
4
  export { normalizeSensitiveFieldName, redactSecretsInString, redactSecretsInValue, SECRET_PATTERN_RULES, SENSITIVE_FIELD_NAMES, type SecretPatternRule, } from "./redact-secrets.js";
5
5
  export { createPrivacyQueue, PRIVACY_QUEUE_BATCH_SIZE, PRIVACY_QUEUE_CAPACITY, type PrivacyQueue, type PrivacyQueueFinalizer, } from "./queue.js";
6
6
  export { buildActorId, buildActorIdentityEvent, buildEventId, buildSessionInitEvent, buildToolCallEvent, finalizeToolCallEvent, normalizeSessionId, type BuildToolCallEventInput, } from "./events.js";
7
- export { DEFAULT_INGEST_MAX_ATTEMPTS, DEFAULT_INGEST_RETRY_DELAY_MS, defaultMcpAnalyticsConfig, emitTelemetryEvent, IngestDeliveryError, postTelemetryEvent, reportEmitError, } from "./emit.js";
7
+ export { defaultMcpAnalyticsConfig, emitTelemetryEvent, IngestRejectedError, postTelemetryEvent, reportEmitError, } from "./emit.js";
8
8
  export { createAnalyticsRecorder } from "./recorder.js";
9
9
  export { buildStatelessSessionId, parseStatelessSessionClientInfo, resolveStatelessHttpSession, type StatelessHttpSession, } from "./stateless-http.js";
10
10
  export { createMcpAnalyticsServer, withMcpAnalytics } from "./server.js";
package/dist/esm/index.js CHANGED
@@ -3,7 +3,7 @@ export { BASE64_REMOVED_PLACEHOLDER, BINARY_REMOVED_PLACEHOLDER, prepareForPrevi
3
3
  export { normalizeSensitiveFieldName, redactSecretsInString, redactSecretsInValue, SECRET_PATTERN_RULES, SENSITIVE_FIELD_NAMES, } from "./redact-secrets.js";
4
4
  export { createPrivacyQueue, PRIVACY_QUEUE_BATCH_SIZE, PRIVACY_QUEUE_CAPACITY, } from "./queue.js";
5
5
  export { buildActorId, buildActorIdentityEvent, buildEventId, buildSessionInitEvent, buildToolCallEvent, finalizeToolCallEvent, normalizeSessionId, } from "./events.js";
6
- export { DEFAULT_INGEST_MAX_ATTEMPTS, DEFAULT_INGEST_RETRY_DELAY_MS, defaultMcpAnalyticsConfig, emitTelemetryEvent, IngestDeliveryError, postTelemetryEvent, reportEmitError, } from "./emit.js";
6
+ export { defaultMcpAnalyticsConfig, emitTelemetryEvent, IngestRejectedError, postTelemetryEvent, reportEmitError, } from "./emit.js";
7
7
  export { createAnalyticsRecorder } from "./recorder.js";
8
8
  export { buildStatelessSessionId, parseStatelessSessionClientInfo, resolveStatelessHttpSession, } from "./stateless-http.js";
9
9
  export { createMcpAnalyticsServer, withMcpAnalytics } from "./server.js";
package/dist/esm/queue.js CHANGED
@@ -1,4 +1,4 @@
1
- import { postTelemetryEvent, reportEmitError, } from "./emit.js";
1
+ import { postAndCheck, reportEmitError, } from "./emit.js";
2
2
  import { readEnv, SCHEMA_VERSION } from "./utils.js";
3
3
  export const PRIVACY_QUEUE_CAPACITY = 1_000;
4
4
  export const PRIVACY_QUEUE_BATCH_SIZE = 20;
@@ -23,9 +23,7 @@ export const createPrivacyQueue = (config) => {
23
23
  }
24
24
  const emit = async (batch) => {
25
25
  const emitter = config.armature?.emit
26
- ?? (async (value) => {
27
- await postTelemetryEvent(value, config);
28
- });
26
+ ?? ((value) => postAndCheck(value, config));
29
27
  try {
30
28
  await emitter(batch);
31
29
  }
@@ -174,8 +174,8 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
174
174
  durationMs,
175
175
  finishedAtMs,
176
176
  });
177
- const requestId = normalizeRequestId(event.requestId);
178
177
  const sessionId = resolveSessionId(event);
178
+ const requestId = normalizeRequestId(event.requestId, sessionId);
179
179
  const errorMessage = event.error === undefined
180
180
  ? undefined
181
181
  : event.error instanceof Error
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@armature-tech/mcp-analytics",
3
- "version": "0.6.25",
3
+ "version": "0.6.27",
4
4
  "type": "module",
5
5
  "description": "MCP analytics wrapper SDK that instruments MCP tool declarations with telemetry.",
6
6
  "license": "Apache-2.0",