@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/README.md CHANGED
@@ -47,8 +47,7 @@ every tool exposes Armature's telemetry contract, and checks the existing
47
47
  `ANALYTICS_INGEST_API_KEY` with an empty authenticated batch. The probe creates
48
48
  no session and sends no tool arguments, responses, or user content. Add
49
49
  `--skip-ingest` for a fully offline check, or `--json` for a support-ready
50
- machine-readable report. It also compares marked `ami_us_` / `ami_eu_` keys
51
- with the ingest and MCP URLs, and will not send the probe when they disagree.
50
+ machine-readable report.
52
51
 
53
52
  ### 3. Instrument your MCP server
54
53
 
@@ -236,13 +235,13 @@ type McpAnalyticsConfig = {
236
235
 
237
236
  | Option | Default | Purpose |
238
237
  | --- | --- | --- |
239
- | **endpointUrl** | US Armature cloud | Override the ingestion endpoint; use `https://eu.armature.tech/api/mcp-analytics/ingest` for EU |
238
+ | **endpointUrl** | Armature cloud | Override the ingestion endpoint |
240
239
  | **apiKey** | **ANALYTICS_INGEST_API_KEY** | Authenticate events and identify the MCP server |
241
240
  | **actorId** | Derived from request auth | Supply a stable user or tenant seed |
242
241
  | **actorIdentifier** | None | Store a caller-provided identifier verbatim |
243
242
  | **enabled** | **true** | Enable or disable instrumentation |
244
243
  | **delivery** | **"background"** | Use **"await"** for serverless or short-lived processes |
245
- | **timeoutMs** | **5000** | Set the timeout for each delivery attempt |
244
+ | **timeoutMs** | **500** | Set the delivery timeout |
246
245
  | **emit** | Network emitter | Replace delivery for tests or custom pipelines |
247
246
  | **onError** | None | Observe delivery failures |
248
247
  | **captureTelemetry** | **true** | Disable conversation-derived telemetry entirely (see below) |
@@ -253,11 +252,6 @@ type McpAnalyticsConfig = {
253
252
  | **telemetryFieldMap** | None | Export existing argument fields as telemetry (see below) |
254
253
  | **requestCapability** | **false** | Inject `request_capability` so agents can report an unmet tool need |
255
254
 
256
- Network failures, timeouts, `429`, and `5xx` responses are retried once after
257
- 100 ms (two attempts total). Other `4xx` responses are not retried.
258
- `IngestDeliveryError` exposes a payload-free `code`, `status`, `retryable`, and
259
- `attempts` through `onError`; telemetry delivery remains fail-open by default.
260
-
261
255
  ### Capability requests
262
256
 
263
257
  Set **requestCapability: true** to add an SDK-owned `request_capability` tool
@@ -352,7 +346,7 @@ non-empty string no larger than 8 KiB. When **actorIdentifier** is absent,
352
346
  | Variable | Purpose |
353
347
  | --- | --- |
354
348
  | **ANALYTICS_INGEST_API_KEY** | Armature ingest key |
355
- | **ANALYTICS_INGEST_URL** | Optional endpoint override. US defaults to `https://app.armature.tech/api/mcp-analytics/ingest`; EU uses `https://eu.armature.tech/api/mcp-analytics/ingest` |
349
+ | **ANALYTICS_INGEST_URL** | Optional ingestion endpoint override |
356
350
 
357
351
  ## Example
358
352
 
package/SKILL.md CHANGED
@@ -60,7 +60,7 @@ The SDK needs one credential, plus an optional URL override:
60
60
  | Variable | What it is |
61
61
  | --- | --- |
62
62
  | `ANALYTICS_INGEST_API_KEY` | Your Armature API key (created in the dashboard). Identifies the MCP server and signs each batch. |
63
- | `ANALYTICS_INGEST_URL` | Optional. US defaults to `https://app.armature.tech/api/mcp-analytics/ingest`; set `https://eu.armature.tech/api/mcp-analytics/ingest` for EU. Override for a local mock or staging environment. |
63
+ | `ANALYTICS_INGEST_URL` | Optional. Defaults to the prod endpoint `https://app.armature.tech/api/mcp-analytics/ingest` (SDK ≥ 0.4.2). Override for a local mock or staging environment. On 0.4.1 and earlier the default was `http://127.0.0.1:8787/...` — if the customer is pinned to one of those, set this var explicitly in prod or telemetry silently goes nowhere. |
64
64
 
65
65
  Add `ANALYTICS_INGEST_API_KEY` to whatever env mechanism the project uses (`.env.example`,
66
66
  `wrangler.toml`, `vercel.json`, fly secrets, k8s manifests). Do **not** commit real values;
@@ -69,11 +69,6 @@ put a placeholder in `.env.example` and tell the user where to paste the real on
69
69
  If `ANALYTICS_INGEST_API_KEY` is missing at runtime, the SDK silently no-ops. That's intentional
70
70
  for local dev — say so once, don't add guards.
71
71
 
72
- The network emitter uses a 5-second timeout per attempt and at most two
73
- attempts, separated by 100 ms. It retries only network failures, timeouts,
74
- `429`, and `5xx`; other `4xx` responses are returned once as a structured
75
- `IngestDeliveryError` through `onError` without breaking the host application.
76
-
77
72
  ## Step 4: Pick a delivery mode
78
73
 
79
74
  The default is `delivery: "background"`, which queues sanitization, redaction,
@@ -407,8 +402,7 @@ npx @armature-tech/mcp-analytics doctor --url http://localhost:3000/mcp
407
402
  Run it with the same `ANALYTICS_INGEST_API_KEY` and
408
403
  `ANALYTICS_INGEST_URL` environment as the server. It verifies the MCP
409
404
  handshake, every served tool's public wrapping contract, and ingest auth using
410
- an empty content-free batch. It also rejects a marked key whose region does
411
- not match the ingest or MCP URL without sending the key. Use `--skip-ingest` only when the user explicitly
405
+ an empty content-free batch. Use `--skip-ingest` only when the user explicitly
412
406
  wants an offline check. Include the doctor result in the handoff.
413
407
 
414
408
  **Check 1 — Schema includes telemetry.** Spin up the server, ask it for `tools/list`, and
package/dist/cjs/cli.js CHANGED
@@ -13,7 +13,6 @@ const usage = "Armature MCP analytics doctor\n"
13
13
  + " - the local project declares an Armature SDK dependency\n"
14
14
  + " - MCP initialize and tools/list succeed\n"
15
15
  + " - every served tool exposes the Armature telemetry contract\n"
16
- + " - marked ingest keys match the MCP and ingest endpoint regions\n"
17
16
  + " - the existing ingest endpoint accepts the configured key\n"
18
17
  + "\n"
19
18
  + "Options:\n"
@@ -24,7 +23,10 @@ const usage = "Armature MCP analytics doctor\n"
24
23
  + " --bearer-env <name> Read an HTTP bearer token from an environment variable\n"
25
24
  + " --cwd <path> Project directory for dependency detection and stdio spawn\n"
26
25
  + " --timeout <ms> Per-check timeout (default: 10000)\n"
27
- + " --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"
28
30
  + " --skip-ingest Do not send the empty authenticated ingest health probe\n"
29
31
  + " --json Print a machine-readable report\n"
30
32
  + " --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 {};
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.defaultDoctorOptions = exports.runDoctor = exports.verifyIngest = exports.detectLocalSdks = exports.inspectToolCoverage = exports.isSdkOwnedCapabilityTool = exports.classifyToolInstrumentation = exports.inspectMcp = exports.regionFromArmatureUrl = exports.regionFromIngestKey = void 0;
3
+ exports.defaultDoctorOptions = exports.runDoctor = exports.verifyIngest = exports.detectLocalSdks = exports.inspectToolCoverage = exports.isSdkOwnedCapabilityTool = exports.classifyToolInstrumentation = exports.inspectMcp = void 0;
4
4
  const promises_1 = require("node:fs/promises");
5
5
  const node_path_1 = require("node:path");
6
6
  const index_js_1 = require("@modelcontextprotocol/sdk/client/index.js");
@@ -20,56 +20,6 @@ const errorMessage = (error) => {
20
20
  return error.message;
21
21
  return String(error || "unknown error");
22
22
  };
23
- const regionLabel = (region) => region.toUpperCase();
24
- const regionFromIngestKey = (apiKey) => {
25
- if (!apiKey)
26
- return undefined;
27
- const marked = apiKey.match(/^ami_(us|eu)_/i)?.[1]?.toLowerCase();
28
- if (marked === "us" || marked === "eu")
29
- return marked;
30
- // Legacy unmarked keys remain US for backward compatibility.
31
- return /^ami_[a-z0-9]/i.test(apiKey) ? "us" : undefined;
32
- };
33
- exports.regionFromIngestKey = regionFromIngestKey;
34
- const regionFromArmatureUrl = (rawUrl) => {
35
- if (!rawUrl)
36
- return undefined;
37
- try {
38
- const hostname = new URL(rawUrl).hostname.toLowerCase();
39
- if (hostname === "eu.armature.tech"
40
- || hostname.endsWith(".eu.armature.tech"))
41
- return "eu";
42
- if (hostname === "app.armature.tech" || hostname === "mcp.armature.tech")
43
- return "us";
44
- }
45
- catch {
46
- return undefined;
47
- }
48
- return undefined;
49
- };
50
- exports.regionFromArmatureUrl = regionFromArmatureUrl;
51
- const regionalConfigurationCheck = (target, endpoint, apiKey) => {
52
- const sources = [
53
- { label: "ingest key", region: (0, exports.regionFromIngestKey)(apiKey) },
54
- { label: "ingest endpoint", region: (0, exports.regionFromArmatureUrl)(endpoint) },
55
- {
56
- label: "MCP target",
57
- region: target.kind === "http" ? (0, exports.regionFromArmatureUrl)(target.url) : undefined,
58
- },
59
- ];
60
- const recognized = sources.filter((source) => source.region !== undefined);
61
- const distinct = new Set(recognized.map((source) => source.region));
62
- if (distinct.size > 1) {
63
- 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.");
64
- }
65
- if (recognized.length >= 2) {
66
- const region = recognized[0]?.region;
67
- return pass("regional-configuration", "Regional configuration", `${recognized.map((source) => source.label).join(" and ")} agree on ${regionLabel(region)}.`);
68
- }
69
- return warn("regional-configuration", "Regional configuration", recognized.length === 1
70
- ? `Only the ${recognized[0]?.label} identifies a known Armature region.`
71
- : "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.");
72
- };
73
23
  const withTimeout = async (promise, timeoutMs, label) => {
74
24
  let timer;
75
25
  try {
@@ -280,18 +230,55 @@ const verifyIngest = async (endpoint, apiKey, timeoutMs) => {
280
230
  body: JSON.stringify({ schema_version: 1, events: [] }),
281
231
  signal: controller.signal,
282
232
  });
283
- // Drain the body so undici can release its pooled connection promptly and
284
- // the one-shot CLI does not appear to hang after printing the report.
285
- 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();
286
239
  if (!response.ok) {
287
240
  throw new Error(`Armature ingest returned HTTP ${response.status}`);
288
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
+ }
289
257
  }
290
258
  finally {
291
259
  clearTimeout(timer);
292
260
  }
293
261
  };
294
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
+ };
295
282
  const pass = (id, label, detail) => ({
296
283
  id, label, detail, status: "pass",
297
284
  });
@@ -303,8 +290,12 @@ const fail = (id, label, detail, remediation) => ({
303
290
  });
304
291
  const runDoctor = async (options, dependencies = { inspectMcp: exports.inspectMcp, detectLocalSdks: exports.detectLocalSdks, verifyIngest: exports.verifyIngest }, environment = process.env) => {
305
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;
306
296
  try {
307
297
  const sdks = await dependencies.detectLocalSdks(options.cwd);
298
+ detectedLanguage = sdks[0]?.language;
308
299
  if (sdks.length === 0) {
309
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."));
310
301
  }
@@ -328,12 +319,14 @@ const runDoctor = async (options, dependencies = { inspectMcp: exports.inspectMc
328
319
  if (!options.expectCapture) {
329
320
  const exposed = coverage.current.length + coverage.legacy.length;
330
321
  checks.push(exposed === 0
331
- ? 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)}.`)
332
324
  : warn("tool-wrapping", "Telemetry capture", `${exposed}/${coverage.total} tools still advertise Armature telemetry fields.`, "Confirm captureTelemetry=false is applied before tools are registered."));
333
325
  }
334
326
  else if (coverage.missing.length > 0) {
335
327
  const sample = coverage.missing.slice(0, 5).join(", ");
336
- 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."));
337
330
  }
338
331
  else if (coverage.legacy.length > 0) {
339
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."));
@@ -355,20 +348,15 @@ const runDoctor = async (options, dependencies = { inspectMcp: exports.inspectMc
355
348
  ? "Start the MCP server, verify the URL/auth headers, and run the doctor again."
356
349
  : "Run the server command directly once, fix startup errors, then run the doctor again."));
357
350
  }
358
- const apiKey = environment.ANALYTICS_INGEST_API_KEY;
359
- const endpoint = environment.ANALYTICS_INGEST_URL || DEFAULT_INGEST_URL;
360
- const regionalCheck = regionalConfigurationCheck(options.target, endpoint, apiKey);
361
- checks.push(regionalCheck);
362
351
  if (options.skipIngest) {
363
352
  checks.push(warn("ingest-auth", "Armature ingest", "Skipped by --skip-ingest; no network request was made."));
364
353
  }
365
354
  else {
355
+ const apiKey = environment.ANALYTICS_INGEST_API_KEY;
356
+ const endpoint = environment.ANALYTICS_INGEST_URL || DEFAULT_INGEST_URL;
366
357
  if (!apiKey) {
367
358
  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."));
368
359
  }
369
- else if (regionalCheck.status === "fail") {
370
- 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."));
371
- }
372
360
  else {
373
361
  try {
374
362
  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/cjs/emit.js CHANGED
@@ -1,48 +1,14 @@
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.IngestDeliveryError = exports.DEFAULT_INGEST_RETRY_DELAY_MS = exports.DEFAULT_INGEST_MAX_ATTEMPTS = 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: {
7
7
  endpointUrl: "https://app.armature.tech/api/mcp-analytics/ingest",
8
8
  enabled: true,
9
- timeoutMs: 5_000,
9
+ timeoutMs: 500,
10
10
  },
11
11
  };
12
- exports.DEFAULT_INGEST_MAX_ATTEMPTS = 2;
13
- exports.DEFAULT_INGEST_RETRY_DELAY_MS = 100;
14
- class IngestDeliveryError extends Error {
15
- code;
16
- status;
17
- retryable;
18
- attempts;
19
- constructor(message, options) {
20
- super(message, options.cause === undefined ? undefined : { cause: options.cause });
21
- this.name = "IngestDeliveryError";
22
- this.code = options.code;
23
- this.status = options.status;
24
- this.retryable = options.retryable === true;
25
- this.attempts = options.attempts;
26
- }
27
- }
28
- exports.IngestDeliveryError = IngestDeliveryError;
29
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
30
- const responseErrorCode = async (response) => {
31
- const fallback = `ingest_http_${response.status}`;
32
- const text = (await response.text()).slice(0, 4_096);
33
- try {
34
- const payload = JSON.parse(text);
35
- const candidate = typeof payload.error?.code === "string"
36
- ? payload.error.code
37
- : typeof payload.errorCode === "string"
38
- ? payload.errorCode
39
- : fallback;
40
- return /^[a-z0-9][a-z0-9_:-]{0,99}$/i.test(candidate) ? candidate : fallback;
41
- }
42
- catch {
43
- return fallback;
44
- }
45
- };
46
12
  const resolveEndpointUrl = (config) => {
47
13
  return config.armature?.endpointUrl ??
48
14
  (0, utils_js_1.readEnv)("ANALYTICS_INGEST_URL") ??
@@ -88,6 +54,41 @@ const resolveActorIdentifier = async (config, input) => {
88
54
  : undefined;
89
55
  };
90
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;
91
92
  const postTelemetryEvent = async (batch, config = exports.defaultMcpAnalyticsConfig) => {
92
93
  const endpointUrl = (0, exports.resolveEndpointUrl)(config);
93
94
  const apiKey = (0, exports.resolveApiKey)(config);
@@ -95,58 +96,58 @@ const postTelemetryEvent = async (batch, config = exports.defaultMcpAnalyticsCon
95
96
  return { skipped: true, reason: "ingest_config_missing" };
96
97
  }
97
98
  const body = JSON.stringify(batch);
98
- const timeoutMs = config.armature?.timeoutMs ?? exports.defaultMcpAnalyticsConfig.armature.timeoutMs;
99
- for (let attempt = 1; attempt <= exports.DEFAULT_INGEST_MAX_ATTEMPTS; attempt += 1) {
100
- const controller = new AbortController();
101
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
102
- try {
103
- const response = await fetch(endpointUrl, {
104
- method: "POST",
105
- headers: {
106
- "Content-Type": "application/json",
107
- Authorization: `Bearer ${apiKey}`,
108
- },
109
- body,
110
- signal: controller.signal,
111
- });
112
- if (response.ok) {
113
- return { skipped: false, ok: true, status: response.status, attempts: attempt };
114
- }
115
- const retryable = response.status === 429 || response.status >= 500;
116
- const code = await responseErrorCode(response);
117
- if (retryable && attempt < exports.DEFAULT_INGEST_MAX_ATTEMPTS) {
118
- await sleep(exports.DEFAULT_INGEST_RETRY_DELAY_MS);
119
- continue;
120
- }
121
- throw new IngestDeliveryError(`Armature ingest failed with HTTP ${response.status} (${code})`, { code, status: response.status, retryable, attempts: attempt });
99
+ const controller = new AbortController();
100
+ const timeout = setTimeout(() => controller.abort(), config.armature?.timeoutMs ?? exports.defaultMcpAnalyticsConfig.armature.timeoutMs);
101
+ try {
102
+ const response = await fetch(endpointUrl, {
103
+ method: "POST",
104
+ headers: {
105
+ "Content-Type": "application/json",
106
+ Authorization: `Bearer ${apiKey}`,
107
+ },
108
+ body,
109
+ signal: controller.signal,
110
+ });
111
+ const text = await response.text();
112
+ if (!response.ok) {
113
+ throw new Error(`Armature ingest failed with ${response.status}: ${text}`);
122
114
  }
123
- catch (error) {
124
- if (error instanceof IngestDeliveryError)
125
- throw error;
126
- const timedOut = error?.name === "AbortError";
127
- if (attempt < exports.DEFAULT_INGEST_MAX_ATTEMPTS) {
128
- await sleep(exports.DEFAULT_INGEST_RETRY_DELAY_MS);
129
- continue;
130
- }
131
- throw new IngestDeliveryError(timedOut
132
- ? `Armature ingest timed out after ${timeoutMs}ms`
133
- : "Armature ingest connection failed", {
134
- code: timedOut ? "ingest_timeout" : "ingest_connection_failed",
135
- retryable: true,
136
- attempts: attempt,
137
- cause: error,
138
- });
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) : {};
139
121
  }
140
- finally {
141
- clearTimeout(timeout);
122
+ catch {
123
+ parsed = {};
142
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
+ };
133
+ }
134
+ finally {
135
+ clearTimeout(timeout);
143
136
  }
144
- throw new IngestDeliveryError("Armature ingest delivery failed", {
145
- code: "ingest_delivery_failed",
146
- attempts: exports.DEFAULT_INGEST_MAX_ATTEMPTS,
147
- });
148
137
  };
149
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;
150
151
  const reportEmitError = (error, batch, config) => {
151
152
  const onError = config.armature?.onError;
152
153
  if (onError) {
@@ -162,9 +163,7 @@ const emitTelemetryEvent = (batch, config = exports.defaultMcpAnalyticsConfig) =
162
163
  return Promise.resolve();
163
164
  }
164
165
  const emit = config.armature?.emit ??
165
- (async (telemetryBatch) => {
166
- await (0, exports.postTelemetryEvent)(telemetryBatch, config);
167
- });
166
+ ((telemetryBatch) => (0, exports.postAndCheck)(telemetryBatch, config));
168
167
  const run = async () => {
169
168
  try {
170
169
  await emit(batch);
@@ -189,9 +188,7 @@ const createFlushableEmitter = (config) => {
189
188
  return Promise.resolve();
190
189
  }
191
190
  const emit = config.armature?.emit ??
192
- (async (telemetryBatch) => {
193
- await (0, exports.postTelemetryEvent)(telemetryBatch, config);
194
- });
191
+ ((telemetryBatch) => (0, exports.postAndCheck)(telemetryBatch, config));
195
192
  const run = async () => {
196
193
  try {
197
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 { 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";