@armature-tech/mcp-analytics 0.6.26 → 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/cli.js CHANGED
@@ -23,7 +23,10 @@ const usage = "Armature MCP analytics doctor\n"
23
23
  + " --bearer-env <name> Read an HTTP bearer token from an environment variable\n"
24
24
  + " --cwd <path> Project directory for dependency detection and stdio spawn\n"
25
25
  + " --timeout <ms> Per-check timeout (default: 10000)\n"
26
- + " --capture <on|off> Expected telemetry capture state (default: on)\n"
26
+ + " --capture <on|off> Expected telemetry capture state (default: on).\n"
27
+ + " Use off for hooks-only or captureTelemetry=false\n"
28
+ + " servers, where tools are intentionally unwrapped\n"
29
+ + " (tool-call/session analytics still flow).\n"
27
30
  + " --skip-ingest Do not send the empty authenticated ingest health probe\n"
28
31
  + " --json Print a machine-readable report\n"
29
32
  + " --help Show this help\n"
@@ -230,18 +230,55 @@ const verifyIngest = async (endpoint, apiKey, timeoutMs) => {
230
230
  body: JSON.stringify({ schema_version: 1, events: [] }),
231
231
  signal: controller.signal,
232
232
  });
233
- // Drain the body so undici can release its pooled connection promptly and
234
- // the one-shot CLI does not appear to hang after printing the report.
235
- await response.arrayBuffer();
233
+ // Read the body so undici can release its pooled connection promptly (the
234
+ // one-shot CLI must not appear to hang) and so we can surface an in-band
235
+ // rejection — ingest answers 200 even when it refuses events (#1403). The
236
+ // health probe sends an empty batch, so a rejection here signals the server
237
+ // is refusing well-formed authenticated requests, not a per-event issue.
238
+ const text = await response.text();
236
239
  if (!response.ok) {
237
240
  throw new Error(`Armature ingest returned HTTP ${response.status}`);
238
241
  }
242
+ try {
243
+ const parsed = JSON.parse(text || "{}");
244
+ if (Array.isArray(parsed.rejected) && parsed.rejected.length > 0) {
245
+ const reasons = Array.from(new Set(parsed.rejected
246
+ .map((item) => (isRecord(item) && typeof item.reason === "string" ? item.reason : null))
247
+ .filter((reason) => Boolean(reason))));
248
+ throw new Error(`Armature ingest refused the health probe: ${parsed.rejected.length} event(s) rejected`
249
+ + (reasons.length > 0 ? ` (${reasons.join(", ")})` : ""));
250
+ }
251
+ }
252
+ catch (error) {
253
+ if (error instanceof Error && error.message.startsWith("Armature ingest refused"))
254
+ throw error;
255
+ // A non-JSON 200 body is not a rejection signal; reachability already passed.
256
+ }
239
257
  }
240
258
  finally {
241
259
  clearTimeout(timer);
242
260
  }
243
261
  };
244
262
  exports.verifyIngest = verifyIngest;
263
+ // The tool-wrapping remediation must name the API of the SDK the doctor
264
+ // actually detected — telling a Go customer to "register tools inside
265
+ // withMcpAnalytics" (a TypeScript-only helper) sends them in circles,
266
+ // especially when they are already using an Armature recorder (the
267
+ // documented Go hooks-only shape: NewRecorder + WithHooks). `language`
268
+ // is the SDK detected by detectLocalSdks; undefined falls back to a
269
+ // cross-language phrasing.
270
+ const wrapApiFor = (language) => {
271
+ switch (language) {
272
+ case "go":
273
+ return "InstrumentTool / InstrumentToolWithConfig";
274
+ case "python":
275
+ return "instrument_fastmcp (or an Armature recorder)";
276
+ case "typescript":
277
+ return "withMcpAnalytics (or an Armature recorder)";
278
+ default:
279
+ return "the SDK's tool instrumentation (InstrumentTool / withMcpAnalytics / instrument_fastmcp)";
280
+ }
281
+ };
245
282
  const pass = (id, label, detail) => ({
246
283
  id, label, detail, status: "pass",
247
284
  });
@@ -253,8 +290,12 @@ const fail = (id, label, detail, remediation) => ({
253
290
  });
254
291
  const runDoctor = async (options, dependencies = { inspectMcp: exports.inspectMcp, detectLocalSdks: exports.detectLocalSdks, verifyIngest: exports.verifyIngest }, environment = process.env) => {
255
292
  const checks = [];
293
+ // Remember the detected SDK so the wrapping check can phrase its fix in
294
+ // that language's API (the first detected wins if several coexist).
295
+ let detectedLanguage;
256
296
  try {
257
297
  const sdks = await dependencies.detectLocalSdks(options.cwd);
298
+ detectedLanguage = sdks[0]?.language;
258
299
  if (sdks.length === 0) {
259
300
  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."));
260
301
  }
@@ -278,12 +319,14 @@ const runDoctor = async (options, dependencies = { inspectMcp: exports.inspectMc
278
319
  if (!options.expectCapture) {
279
320
  const exposed = coverage.current.length + coverage.legacy.length;
280
321
  checks.push(exposed === 0
281
- ? pass("tool-wrapping", "Telemetry capture", "No Armature telemetry fields are advertised, as requested.")
322
+ ? pass("tool-wrapping", "Telemetry capture", "No Armature telemetry fields are advertised, as requested. "
323
+ + `Tool-call and session analytics still flow; capturing user_intent/agent_thinking requires wrapping tools with ${wrapApiFor(detectedLanguage)}.`)
282
324
  : warn("tool-wrapping", "Telemetry capture", `${exposed}/${coverage.total} tools still advertise Armature telemetry fields.`, "Confirm captureTelemetry=false is applied before tools are registered."));
283
325
  }
284
326
  else if (coverage.missing.length > 0) {
285
327
  const sample = coverage.missing.slice(0, 5).join(", ");
286
- 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."));
328
+ 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)}. `
329
+ + "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."));
287
330
  }
288
331
  else if (coverage.legacy.length > 0) {
289
332
  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."));
@@ -11,20 +11,38 @@ export declare const resolveApiKey: (config: McpAnalyticsConfig) => string | und
11
11
  export declare const resolveActorSeed: (config: McpAnalyticsConfig, input: ActorIdResolverInput) => Promise<string>;
12
12
  /** Resolve the optional caller-provided identifier without interpreting it. */
13
13
  export declare const resolveActorIdentifier: (config: McpAnalyticsConfig, input: ActorIdResolverInput) => Promise<string | undefined>;
14
- export declare const postTelemetryEvent: (batch: AnalyticsIngestBatch, config?: McpAnalyticsConfig) => Promise<{
15
- skipped: boolean;
16
- reason: string;
17
- ok?: undefined;
18
- status?: undefined;
19
- } | {
14
+ type IngestRejection = {
15
+ event_id?: string | null;
16
+ reason?: string;
17
+ };
18
+ export type IngestResult = {
20
19
  skipped: boolean;
21
- ok: boolean;
22
- status: number;
23
- reason?: undefined;
24
- }>;
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>;
25
42
  export declare const reportEmitError: (error: unknown, batch: AnalyticsIngestBatch, config: McpAnalyticsConfig) => void;
26
43
  export declare const emitTelemetryEvent: (batch: AnalyticsIngestBatch, config?: McpAnalyticsConfig) => Promise<void>;
27
44
  export declare const createFlushableEmitter: (config: McpAnalyticsConfig) => {
28
45
  emitBatch: (batch: AnalyticsIngestBatch) => Promise<void>;
29
46
  flush: () => Promise<void>;
30
47
  };
48
+ export {};
package/dist/cjs/emit.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createFlushableEmitter = exports.emitTelemetryEvent = exports.reportEmitError = exports.postTelemetryEvent = exports.resolveActorIdentifier = exports.resolveActorSeed = exports.resolveApiKey = exports.resolveEndpointUrl = exports.defaultMcpAnalyticsConfig = void 0;
3
+ exports.createFlushableEmitter = exports.emitTelemetryEvent = exports.reportEmitError = exports.postAndCheck = exports.postTelemetryEvent = exports.describeIngestRejection = exports.IngestRejectedError = exports.resolveActorIdentifier = exports.resolveActorSeed = exports.resolveApiKey = exports.resolveEndpointUrl = exports.defaultMcpAnalyticsConfig = void 0;
4
4
  const utils_js_1 = require("./utils.js");
5
5
  exports.defaultMcpAnalyticsConfig = {
6
6
  armature: {
@@ -54,6 +54,41 @@ const resolveActorIdentifier = async (config, input) => {
54
54
  : undefined;
55
55
  };
56
56
  exports.resolveActorIdentifier = resolveActorIdentifier;
57
+ /**
58
+ * Ingest answers HTTP 200 even when it refuses events in the response body
59
+ * (validation, quota, schema drift — `rejected` non-empty, or everything
60
+ * refused with nothing accepted). A producer that checks only the status code
61
+ * treats that as delivered and never fires `onError` (#1403). This carries the
62
+ * refusal so the emit path can surface it through the normal error channel.
63
+ */
64
+ class IngestRejectedError extends Error {
65
+ rejected;
66
+ accepted;
67
+ constructor(rejected, accepted) {
68
+ const reasons = Array.from(new Set(rejected.map((item) => item?.reason).filter((r) => Boolean(r))));
69
+ const detail = reasons.length > 0 ? ` (${reasons.join(", ")})` : "";
70
+ super(`Armature ingest rejected ${rejected.length} event(s)${detail}`);
71
+ this.name = "IngestRejectedError";
72
+ this.rejected = rejected;
73
+ this.accepted = accepted;
74
+ }
75
+ }
76
+ exports.IngestRejectedError = IngestRejectedError;
77
+ // A 200 that refuses events in-body: any explicit rejection, or nothing
78
+ // accepted from a non-empty batch. Server-side dedup counts as accepted, so a
79
+ // benign session_init re-delivery does NOT trip this.
80
+ const describeIngestRejection = (result, eventCount) => {
81
+ if (result.skipped)
82
+ return null;
83
+ const rejected = Array.isArray(result.rejected) ? result.rejected : [];
84
+ const accepted = typeof result.accepted === "number" ? result.accepted : undefined;
85
+ if (rejected.length > 0)
86
+ return new IngestRejectedError(rejected, accepted ?? 0);
87
+ if (accepted === 0 && eventCount > 0)
88
+ return new IngestRejectedError([], 0);
89
+ return null;
90
+ };
91
+ exports.describeIngestRejection = describeIngestRejection;
57
92
  const postTelemetryEvent = async (batch, config = exports.defaultMcpAnalyticsConfig) => {
58
93
  const endpointUrl = (0, exports.resolveEndpointUrl)(config);
59
94
  const apiKey = (0, exports.resolveApiKey)(config);
@@ -73,16 +108,46 @@ const postTelemetryEvent = async (batch, config = exports.defaultMcpAnalyticsCon
73
108
  body,
74
109
  signal: controller.signal,
75
110
  });
111
+ const text = await response.text();
76
112
  if (!response.ok) {
77
- throw new Error(`Armature ingest failed with ${response.status}: ${await response.text()}`);
113
+ throw new Error(`Armature ingest failed with ${response.status}: ${text}`);
114
+ }
115
+ // The body carries in-band rejection/dedup even on 200; parse it so the
116
+ // emit path can raise on refused events (#1403). A non-JSON body just
117
+ // means we cannot observe rejections, not a delivery failure.
118
+ let parsed = {};
119
+ try {
120
+ parsed = text ? JSON.parse(text) : {};
78
121
  }
79
- return { skipped: false, ok: true, status: response.status };
122
+ catch {
123
+ parsed = {};
124
+ }
125
+ return {
126
+ skipped: false,
127
+ ok: true,
128
+ status: response.status,
129
+ accepted: typeof parsed.accepted === "number" ? parsed.accepted : undefined,
130
+ rejected: Array.isArray(parsed.rejected) ? parsed.rejected : [],
131
+ duplicateCount: typeof parsed.duplicate_count === "number" ? parsed.duplicate_count : undefined,
132
+ };
80
133
  }
81
134
  finally {
82
135
  clearTimeout(timeout);
83
136
  }
84
137
  };
85
138
  exports.postTelemetryEvent = postTelemetryEvent;
139
+ // The default network emit for every delivery path (privacy queue, flushable
140
+ // emitter, one-shot emit): POST, then raise on in-body rejection so the caller's
141
+ // try/catch routes it to `onError`, just like a transport failure. This MUST be
142
+ // the shared default so the recorder's real path (the privacy queue) also
143
+ // surfaces rejections (#1403).
144
+ const postAndCheck = async (batch, config) => {
145
+ const result = await (0, exports.postTelemetryEvent)(batch, config);
146
+ const rejection = (0, exports.describeIngestRejection)(result, batch.events.length);
147
+ if (rejection)
148
+ throw rejection;
149
+ };
150
+ exports.postAndCheck = postAndCheck;
86
151
  const reportEmitError = (error, batch, config) => {
87
152
  const onError = config.armature?.onError;
88
153
  if (onError) {
@@ -98,9 +163,7 @@ const emitTelemetryEvent = (batch, config = exports.defaultMcpAnalyticsConfig) =
98
163
  return Promise.resolve();
99
164
  }
100
165
  const emit = config.armature?.emit ??
101
- (async (telemetryBatch) => {
102
- await (0, exports.postTelemetryEvent)(telemetryBatch, config);
103
- });
166
+ ((telemetryBatch) => (0, exports.postAndCheck)(telemetryBatch, config));
104
167
  const run = async () => {
105
168
  try {
106
169
  await emit(batch);
@@ -125,9 +188,7 @@ const createFlushableEmitter = (config) => {
125
188
  return Promise.resolve();
126
189
  }
127
190
  const emit = config.armature?.emit ??
128
- (async (telemetryBatch) => {
129
- await (0, exports.postTelemetryEvent)(telemetryBatch, config);
130
- });
191
+ ((telemetryBatch) => (0, exports.postAndCheck)(telemetryBatch, config));
131
192
  const run = async () => {
132
193
  try {
133
194
  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;
@@ -294,10 +294,25 @@ exports.normalizeSessionId = normalizeSessionId;
294
294
  // counter (0, 1, 2, …) that restarts on reconnect, across stateless gateway
295
295
  // instances, etc., so two unrelated tool calls routinely share `extra.requestId`
296
296
  // and would collide on `event_id` — making ingest dedupe the second call away.
297
- // An explicit caller-supplied id still wins (it's a deliberate idempotency key);
298
- // otherwise we mint a fresh uuid, matching the prototype-patch path in server.ts.
299
- const normalizeRequestId = (eventRequestId) => {
300
- return eventRequestId ?? (0, node_crypto_1.randomUUID)();
297
+ //
298
+ // When no id is supplied we mint a fresh uuid (matching the prototype-patch path
299
+ // in server.ts), which is globally unique and needs no further scoping. A
300
+ // caller-supplied id is treated as a deliberate idempotency key, but is scoped
301
+ // by the resolved session id when one is known: `${sessionId}#${id}`. That keeps
302
+ // within-session idempotency (a genuine retry reusing the same id de-dups) while
303
+ // making a hazardous transport counter reused across concurrent conversations
304
+ // collision-free — two sessions that both send request id "5" hash to different
305
+ // `event_id`s. See the cross-SDK "Event identity and idempotency" section of
306
+ // packages/TELEMETRY-CONTRACT.md.
307
+ const normalizeRequestId = (eventRequestId, sessionId) => {
308
+ // `== null` also mints for a `null` an untyped JS caller may pass, matching
309
+ // the previous `?? randomUUID()`; a degenerate `null` must never seed a hash.
310
+ // An empty string is equally degenerate — it would collapse every such call
311
+ // into one fixed `${sessionId}#` seed and collide on event_id — so it mints
312
+ // too, matching the Python (`if not event_request_id`) and Go (`== ""`) SDKs.
313
+ if (eventRequestId == null || eventRequestId === "")
314
+ return (0, node_crypto_1.randomUUID)();
315
+ return sessionId ? `${sessionId}#${eventRequestId}` : eventRequestId;
301
316
  };
302
317
  exports.normalizeRequestId = normalizeRequestId;
303
318
  const normalizeStartedAt = ({ startedAt, durationMs, finishedAtMs, }) => {
@@ -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 { defaultMcpAnalyticsConfig, emitTelemetryEvent, 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/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.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;
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; } });
@@ -40,6 +40,7 @@ Object.defineProperty(exports, "normalizeSessionId", { enumerable: true, get: fu
40
40
  var emit_js_1 = require("./emit.js");
41
41
  Object.defineProperty(exports, "defaultMcpAnalyticsConfig", { enumerable: true, get: function () { return emit_js_1.defaultMcpAnalyticsConfig; } });
42
42
  Object.defineProperty(exports, "emitTelemetryEvent", { enumerable: true, get: function () { return emit_js_1.emitTelemetryEvent; } });
43
+ Object.defineProperty(exports, "IngestRejectedError", { enumerable: true, get: function () { return emit_js_1.IngestRejectedError; } });
43
44
  Object.defineProperty(exports, "postTelemetryEvent", { enumerable: true, get: function () { return emit_js_1.postTelemetryEvent; } });
44
45
  Object.defineProperty(exports, "reportEmitError", { enumerable: true, get: function () { return emit_js_1.reportEmitError; } });
45
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
@@ -21,7 +21,10 @@ const usage = "Armature MCP analytics doctor\n"
21
21
  + " --bearer-env <name> Read an HTTP bearer token from an environment variable\n"
22
22
  + " --cwd <path> Project directory for dependency detection and stdio spawn\n"
23
23
  + " --timeout <ms> Per-check timeout (default: 10000)\n"
24
- + " --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"
25
28
  + " --skip-ingest Do not send the empty authenticated ingest health probe\n"
26
29
  + " --json Print a machine-readable report\n"
27
30
  + " --help Show this help\n"
@@ -222,17 +222,54 @@ export const verifyIngest = async (endpoint, apiKey, timeoutMs) => {
222
222
  body: JSON.stringify({ schema_version: 1, events: [] }),
223
223
  signal: controller.signal,
224
224
  });
225
- // Drain the body so undici can release its pooled connection promptly and
226
- // the one-shot CLI does not appear to hang after printing the report.
227
- 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();
228
231
  if (!response.ok) {
229
232
  throw new Error(`Armature ingest returned HTTP ${response.status}`);
230
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
+ }
231
249
  }
232
250
  finally {
233
251
  clearTimeout(timer);
234
252
  }
235
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
+ };
236
273
  const pass = (id, label, detail) => ({
237
274
  id, label, detail, status: "pass",
238
275
  });
@@ -244,8 +281,12 @@ const fail = (id, label, detail, remediation) => ({
244
281
  });
245
282
  export const runDoctor = async (options, dependencies = { inspectMcp, detectLocalSdks, verifyIngest }, environment = process.env) => {
246
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;
247
287
  try {
248
288
  const sdks = await dependencies.detectLocalSdks(options.cwd);
289
+ detectedLanguage = sdks[0]?.language;
249
290
  if (sdks.length === 0) {
250
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."));
251
292
  }
@@ -269,12 +310,14 @@ export const runDoctor = async (options, dependencies = { inspectMcp, detectLoca
269
310
  if (!options.expectCapture) {
270
311
  const exposed = coverage.current.length + coverage.legacy.length;
271
312
  checks.push(exposed === 0
272
- ? 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)}.`)
273
315
  : warn("tool-wrapping", "Telemetry capture", `${exposed}/${coverage.total} tools still advertise Armature telemetry fields.`, "Confirm captureTelemetry=false is applied before tools are registered."));
274
316
  }
275
317
  else if (coverage.missing.length > 0) {
276
318
  const sample = coverage.missing.slice(0, 5).join(", ");
277
- 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."));
278
321
  }
279
322
  else if (coverage.legacy.length > 0) {
280
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."));
@@ -11,20 +11,38 @@ export declare const resolveApiKey: (config: McpAnalyticsConfig) => string | und
11
11
  export declare const resolveActorSeed: (config: McpAnalyticsConfig, input: ActorIdResolverInput) => Promise<string>;
12
12
  /** Resolve the optional caller-provided identifier without interpreting it. */
13
13
  export declare const resolveActorIdentifier: (config: McpAnalyticsConfig, input: ActorIdResolverInput) => Promise<string | undefined>;
14
- export declare const postTelemetryEvent: (batch: AnalyticsIngestBatch, config?: McpAnalyticsConfig) => Promise<{
15
- skipped: boolean;
16
- reason: string;
17
- ok?: undefined;
18
- status?: undefined;
19
- } | {
14
+ type IngestRejection = {
15
+ event_id?: string | null;
16
+ reason?: string;
17
+ };
18
+ export type IngestResult = {
20
19
  skipped: boolean;
21
- ok: boolean;
22
- status: number;
23
- reason?: undefined;
24
- }>;
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>;
25
42
  export declare const reportEmitError: (error: unknown, batch: AnalyticsIngestBatch, config: McpAnalyticsConfig) => void;
26
43
  export declare const emitTelemetryEvent: (batch: AnalyticsIngestBatch, config?: McpAnalyticsConfig) => Promise<void>;
27
44
  export declare const createFlushableEmitter: (config: McpAnalyticsConfig) => {
28
45
  emitBatch: (batch: AnalyticsIngestBatch) => Promise<void>;
29
46
  flush: () => Promise<void>;
30
47
  };
48
+ export {};
package/dist/esm/emit.js CHANGED
@@ -47,6 +47,39 @@ export const resolveActorIdentifier = async (config, input) => {
47
47
  ? value
48
48
  : undefined;
49
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
+ };
50
83
  export const postTelemetryEvent = async (batch, config = defaultMcpAnalyticsConfig) => {
51
84
  const endpointUrl = resolveEndpointUrl(config);
52
85
  const apiKey = resolveApiKey(config);
@@ -66,15 +99,44 @@ export const postTelemetryEvent = async (batch, config = defaultMcpAnalyticsConf
66
99
  body,
67
100
  signal: controller.signal,
68
101
  });
102
+ const text = await response.text();
69
103
  if (!response.ok) {
70
- throw new Error(`Armature ingest failed with ${response.status}: ${await response.text()}`);
104
+ throw new Error(`Armature ingest failed with ${response.status}: ${text}`);
105
+ }
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) : {};
71
112
  }
72
- return { skipped: false, ok: true, status: response.status };
113
+ catch {
114
+ parsed = {};
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
+ };
73
124
  }
74
125
  finally {
75
126
  clearTimeout(timeout);
76
127
  }
77
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;
139
+ };
78
140
  export const reportEmitError = (error, batch, config) => {
79
141
  const onError = config.armature?.onError;
80
142
  if (onError) {
@@ -89,9 +151,7 @@ export const emitTelemetryEvent = (batch, config = defaultMcpAnalyticsConfig) =>
89
151
  return Promise.resolve();
90
152
  }
91
153
  const emit = config.armature?.emit ??
92
- (async (telemetryBatch) => {
93
- await postTelemetryEvent(telemetryBatch, config);
94
- });
154
+ ((telemetryBatch) => postAndCheck(telemetryBatch, config));
95
155
  const run = async () => {
96
156
  try {
97
157
  await emit(batch);
@@ -115,9 +175,7 @@ export const createFlushableEmitter = (config) => {
115
175
  return Promise.resolve();
116
176
  }
117
177
  const emit = config.armature?.emit ??
118
- (async (telemetryBatch) => {
119
- await postTelemetryEvent(telemetryBatch, config);
120
- });
178
+ ((telemetryBatch) => postAndCheck(telemetryBatch, config));
121
179
  const run = async () => {
122
180
  try {
123
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 { defaultMcpAnalyticsConfig, emitTelemetryEvent, 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 { defaultMcpAnalyticsConfig, emitTelemetryEvent, 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.26",
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",