@armature-tech/mcp-analytics 0.6.24 → 0.6.25

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,7 +47,8 @@ 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.
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.
51
52
 
52
53
  ### 3. Instrument your MCP server
53
54
 
@@ -235,13 +236,13 @@ type McpAnalyticsConfig = {
235
236
 
236
237
  | Option | Default | Purpose |
237
238
  | --- | --- | --- |
238
- | **endpointUrl** | Armature cloud | Override the ingestion endpoint |
239
+ | **endpointUrl** | US Armature cloud | Override the ingestion endpoint; use `https://eu.armature.tech/api/mcp-analytics/ingest` for EU |
239
240
  | **apiKey** | **ANALYTICS_INGEST_API_KEY** | Authenticate events and identify the MCP server |
240
241
  | **actorId** | Derived from request auth | Supply a stable user or tenant seed |
241
242
  | **actorIdentifier** | None | Store a caller-provided identifier verbatim |
242
243
  | **enabled** | **true** | Enable or disable instrumentation |
243
244
  | **delivery** | **"background"** | Use **"await"** for serverless or short-lived processes |
244
- | **timeoutMs** | **500** | Set the delivery timeout |
245
+ | **timeoutMs** | **5000** | Set the timeout for each delivery attempt |
245
246
  | **emit** | Network emitter | Replace delivery for tests or custom pipelines |
246
247
  | **onError** | None | Observe delivery failures |
247
248
  | **captureTelemetry** | **true** | Disable conversation-derived telemetry entirely (see below) |
@@ -252,6 +253,11 @@ type McpAnalyticsConfig = {
252
253
  | **telemetryFieldMap** | None | Export existing argument fields as telemetry (see below) |
253
254
  | **requestCapability** | **false** | Inject `request_capability` so agents can report an unmet tool need |
254
255
 
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
+
255
261
  ### Capability requests
256
262
 
257
263
  Set **requestCapability: true** to add an SDK-owned `request_capability` tool
@@ -346,7 +352,7 @@ non-empty string no larger than 8 KiB. When **actorIdentifier** is absent,
346
352
  | Variable | Purpose |
347
353
  | --- | --- |
348
354
  | **ANALYTICS_INGEST_API_KEY** | Armature ingest key |
349
- | **ANALYTICS_INGEST_URL** | Optional ingestion endpoint override |
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` |
350
356
 
351
357
  ## Example
352
358
 
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. 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. |
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. |
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,6 +69,11 @@ 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
+
72
77
  ## Step 4: Pick a delivery mode
73
78
 
74
79
  The default is `delivery: "background"`, which queues sanitization, redaction,
@@ -402,7 +407,8 @@ npx @armature-tech/mcp-analytics doctor --url http://localhost:3000/mcp
402
407
  Run it with the same `ANALYTICS_INGEST_API_KEY` and
403
408
  `ANALYTICS_INGEST_URL` environment as the server. It verifies the MCP
404
409
  handshake, every served tool's public wrapping contract, and ingest auth using
405
- an empty content-free batch. Use `--skip-ingest` only when the user explicitly
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
406
412
  wants an offline check. Include the doctor result in the handoff.
407
413
 
408
414
  **Check 1 — Schema includes telemetry.** Spin up the server, ask it for `tools/list`, and
package/dist/cjs/cli.js CHANGED
@@ -13,6 +13,7 @@ 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"
16
17
  + " - the existing ingest endpoint accepts the configured key\n"
17
18
  + "\n"
18
19
  + "Options:\n"
@@ -1,3 +1,4 @@
1
+ type DeploymentRegion = "us" | "eu";
1
2
  export type DoctorStatus = "pass" | "warn" | "fail";
2
3
  export type DoctorCheck = {
3
4
  id: string;
@@ -48,6 +49,8 @@ export type DoctorDependencies = {
48
49
  detectLocalSdks: (cwd: string) => Promise<LocalSdk[]>;
49
50
  verifyIngest: (endpoint: string, apiKey: string, timeoutMs: number) => Promise<void>;
50
51
  };
52
+ export declare const regionFromIngestKey: (apiKey: string | undefined) => DeploymentRegion | undefined;
53
+ export declare const regionFromArmatureUrl: (rawUrl: string | undefined) => DeploymentRegion | undefined;
51
54
  export declare const inspectMcp: (options: DoctorOptions) => Promise<McpInspection>;
52
55
  export declare const classifyToolInstrumentation: (tool: DoctorTool) => "current" | "legacy" | "owned" | "missing";
53
56
  export declare const isSdkOwnedCapabilityTool: (tool: DoctorTool) => boolean;
@@ -63,3 +66,4 @@ export declare const detectLocalSdks: (cwd: string) => Promise<LocalSdk[]>;
63
66
  export declare const verifyIngest: (endpoint: string, apiKey: string, timeoutMs: number) => Promise<void>;
64
67
  export declare const runDoctor: (options: DoctorOptions, dependencies?: DoctorDependencies, environment?: NodeJS.ProcessEnv) => Promise<DoctorReport>;
65
68
  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 = void 0;
3
+ exports.defaultDoctorOptions = exports.runDoctor = exports.verifyIngest = exports.detectLocalSdks = exports.inspectToolCoverage = exports.isSdkOwnedCapabilityTool = exports.classifyToolInstrumentation = exports.inspectMcp = exports.regionFromArmatureUrl = exports.regionFromIngestKey = 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,6 +20,56 @@ 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
+ };
23
73
  const withTimeout = async (promise, timeoutMs, label) => {
24
74
  let timer;
25
75
  try {
@@ -305,15 +355,20 @@ const runDoctor = async (options, dependencies = { inspectMcp: exports.inspectMc
305
355
  ? "Start the MCP server, verify the URL/auth headers, and run the doctor again."
306
356
  : "Run the server command directly once, fix startup errors, then run the doctor again."));
307
357
  }
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);
308
362
  if (options.skipIngest) {
309
363
  checks.push(warn("ingest-auth", "Armature ingest", "Skipped by --skip-ingest; no network request was made."));
310
364
  }
311
365
  else {
312
- const apiKey = environment.ANALYTICS_INGEST_API_KEY;
313
- const endpoint = environment.ANALYTICS_INGEST_URL || DEFAULT_INGEST_URL;
314
366
  if (!apiKey) {
315
367
  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."));
316
368
  }
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
+ }
317
372
  else {
318
373
  try {
319
374
  await dependencies.verifyIngest(endpoint, apiKey, options.timeoutMs);
@@ -6,6 +6,21 @@ 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
+ }
9
24
  export declare const resolveEndpointUrl: (config: McpAnalyticsConfig) => string;
10
25
  export declare const resolveApiKey: (config: McpAnalyticsConfig) => string | undefined;
11
26
  export declare const resolveActorSeed: (config: McpAnalyticsConfig, input: ActorIdResolverInput) => Promise<string>;
@@ -16,10 +31,12 @@ export declare const postTelemetryEvent: (batch: AnalyticsIngestBatch, config?:
16
31
  reason: string;
17
32
  ok?: undefined;
18
33
  status?: undefined;
34
+ attempts?: undefined;
19
35
  } | {
20
36
  skipped: boolean;
21
37
  ok: boolean;
22
38
  status: number;
39
+ attempts: number;
23
40
  reason?: undefined;
24
41
  }>;
25
42
  export declare const reportEmitError: (error: unknown, batch: AnalyticsIngestBatch, config: McpAnalyticsConfig) => void;
package/dist/cjs/emit.js CHANGED
@@ -1,14 +1,48 @@
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.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;
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: 500,
9
+ timeoutMs: 5_000,
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
+ };
12
46
  const resolveEndpointUrl = (config) => {
13
47
  return config.armature?.endpointUrl ??
14
48
  (0, utils_js_1.readEnv)("ANALYTICS_INGEST_URL") ??
@@ -61,26 +95,56 @@ const postTelemetryEvent = async (batch, config = exports.defaultMcpAnalyticsCon
61
95
  return { skipped: true, reason: "ingest_config_missing" };
62
96
  }
63
97
  const body = JSON.stringify(batch);
64
- const controller = new AbortController();
65
- const timeout = setTimeout(() => controller.abort(), config.armature?.timeoutMs ?? exports.defaultMcpAnalyticsConfig.armature.timeoutMs);
66
- try {
67
- const response = await fetch(endpointUrl, {
68
- method: "POST",
69
- headers: {
70
- "Content-Type": "application/json",
71
- Authorization: `Bearer ${apiKey}`,
72
- },
73
- body,
74
- signal: controller.signal,
75
- });
76
- if (!response.ok) {
77
- throw new Error(`Armature ingest failed with ${response.status}: ${await response.text()}`);
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 });
122
+ }
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
+ });
139
+ }
140
+ finally {
141
+ clearTimeout(timeout);
78
142
  }
79
- return { skipped: false, ok: true, status: response.status };
80
- }
81
- finally {
82
- clearTimeout(timeout);
83
143
  }
144
+ throw new IngestDeliveryError("Armature ingest delivery failed", {
145
+ code: "ingest_delivery_failed",
146
+ attempts: exports.DEFAULT_INGEST_MAX_ATTEMPTS,
147
+ });
84
148
  };
85
149
  exports.postTelemetryEvent = postTelemetryEvent;
86
150
  const reportEmitError = (error, batch, config) => {
@@ -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 { DEFAULT_INGEST_MAX_ATTEMPTS, DEFAULT_INGEST_RETRY_DELAY_MS, defaultMcpAnalyticsConfig, emitTelemetryEvent, IngestDeliveryError, 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.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;
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,8 +38,11 @@ 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; } });
41
43
  Object.defineProperty(exports, "defaultMcpAnalyticsConfig", { enumerable: true, get: function () { return emit_js_1.defaultMcpAnalyticsConfig; } });
42
44
  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
46
  Object.defineProperty(exports, "postTelemetryEvent", { enumerable: true, get: function () { return emit_js_1.postTelemetryEvent; } });
44
47
  Object.defineProperty(exports, "reportEmitError", { enumerable: true, get: function () { return emit_js_1.reportEmitError; } });
45
48
  var recorder_js_1 = require("./recorder.js");
package/dist/esm/cli.js CHANGED
@@ -11,6 +11,7 @@ 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"
14
15
  + " - the existing ingest endpoint accepts the configured key\n"
15
16
  + "\n"
16
17
  + "Options:\n"
@@ -1,3 +1,4 @@
1
+ type DeploymentRegion = "us" | "eu";
1
2
  export type DoctorStatus = "pass" | "warn" | "fail";
2
3
  export type DoctorCheck = {
3
4
  id: string;
@@ -48,6 +49,8 @@ export type DoctorDependencies = {
48
49
  detectLocalSdks: (cwd: string) => Promise<LocalSdk[]>;
49
50
  verifyIngest: (endpoint: string, apiKey: string, timeoutMs: number) => Promise<void>;
50
51
  };
52
+ export declare const regionFromIngestKey: (apiKey: string | undefined) => DeploymentRegion | undefined;
53
+ export declare const regionFromArmatureUrl: (rawUrl: string | undefined) => DeploymentRegion | undefined;
51
54
  export declare const inspectMcp: (options: DoctorOptions) => Promise<McpInspection>;
52
55
  export declare const classifyToolInstrumentation: (tool: DoctorTool) => "current" | "legacy" | "owned" | "missing";
53
56
  export declare const isSdkOwnedCapabilityTool: (tool: DoctorTool) => boolean;
@@ -63,3 +66,4 @@ export declare const detectLocalSdks: (cwd: string) => Promise<LocalSdk[]>;
63
66
  export declare const verifyIngest: (endpoint: string, apiKey: string, timeoutMs: number) => Promise<void>;
64
67
  export declare const runDoctor: (options: DoctorOptions, dependencies?: DoctorDependencies, environment?: NodeJS.ProcessEnv) => Promise<DoctorReport>;
65
68
  export declare const defaultDoctorOptions: (target: DoctorTarget) => DoctorOptions;
69
+ export {};
@@ -17,6 +17,54 @@ 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
+ };
20
68
  const withTimeout = async (promise, timeoutMs, label) => {
21
69
  let timer;
22
70
  try {
@@ -296,15 +344,20 @@ export const runDoctor = async (options, dependencies = { inspectMcp, detectLoca
296
344
  ? "Start the MCP server, verify the URL/auth headers, and run the doctor again."
297
345
  : "Run the server command directly once, fix startup errors, then run the doctor again."));
298
346
  }
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);
299
351
  if (options.skipIngest) {
300
352
  checks.push(warn("ingest-auth", "Armature ingest", "Skipped by --skip-ingest; no network request was made."));
301
353
  }
302
354
  else {
303
- const apiKey = environment.ANALYTICS_INGEST_API_KEY;
304
- const endpoint = environment.ANALYTICS_INGEST_URL || DEFAULT_INGEST_URL;
305
355
  if (!apiKey) {
306
356
  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."));
307
357
  }
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
+ }
308
361
  else {
309
362
  try {
310
363
  await dependencies.verifyIngest(endpoint, apiKey, options.timeoutMs);
@@ -6,6 +6,21 @@ 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
+ }
9
24
  export declare const resolveEndpointUrl: (config: McpAnalyticsConfig) => string;
10
25
  export declare const resolveApiKey: (config: McpAnalyticsConfig) => string | undefined;
11
26
  export declare const resolveActorSeed: (config: McpAnalyticsConfig, input: ActorIdResolverInput) => Promise<string>;
@@ -16,10 +31,12 @@ export declare const postTelemetryEvent: (batch: AnalyticsIngestBatch, config?:
16
31
  reason: string;
17
32
  ok?: undefined;
18
33
  status?: undefined;
34
+ attempts?: undefined;
19
35
  } | {
20
36
  skipped: boolean;
21
37
  ok: boolean;
22
38
  status: number;
39
+ attempts: number;
23
40
  reason?: undefined;
24
41
  }>;
25
42
  export declare const reportEmitError: (error: unknown, batch: AnalyticsIngestBatch, config: McpAnalyticsConfig) => void;
package/dist/esm/emit.js CHANGED
@@ -3,9 +3,42 @@ export const defaultMcpAnalyticsConfig = {
3
3
  armature: {
4
4
  endpointUrl: "https://app.armature.tech/api/mcp-analytics/ingest",
5
5
  enabled: true,
6
- timeoutMs: 500,
6
+ timeoutMs: 5_000,
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
+ };
9
42
  export const resolveEndpointUrl = (config) => {
10
43
  return config.armature?.endpointUrl ??
11
44
  readEnv("ANALYTICS_INGEST_URL") ??
@@ -54,26 +87,56 @@ export const postTelemetryEvent = async (batch, config = defaultMcpAnalyticsConf
54
87
  return { skipped: true, reason: "ingest_config_missing" };
55
88
  }
56
89
  const body = JSON.stringify(batch);
57
- const controller = new AbortController();
58
- const timeout = setTimeout(() => controller.abort(), config.armature?.timeoutMs ?? defaultMcpAnalyticsConfig.armature.timeoutMs);
59
- try {
60
- const response = await fetch(endpointUrl, {
61
- method: "POST",
62
- headers: {
63
- "Content-Type": "application/json",
64
- Authorization: `Bearer ${apiKey}`,
65
- },
66
- body,
67
- signal: controller.signal,
68
- });
69
- if (!response.ok) {
70
- throw new Error(`Armature ingest failed with ${response.status}: ${await response.text()}`);
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 });
114
+ }
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
+ });
131
+ }
132
+ finally {
133
+ clearTimeout(timeout);
71
134
  }
72
- return { skipped: false, ok: true, status: response.status };
73
- }
74
- finally {
75
- clearTimeout(timeout);
76
135
  }
136
+ throw new IngestDeliveryError("Armature ingest delivery failed", {
137
+ code: "ingest_delivery_failed",
138
+ attempts: DEFAULT_INGEST_MAX_ATTEMPTS,
139
+ });
77
140
  };
78
141
  export const reportEmitError = (error, batch, config) => {
79
142
  const onError = config.armature?.onError;
@@ -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 { DEFAULT_INGEST_MAX_ATTEMPTS, DEFAULT_INGEST_RETRY_DELAY_MS, defaultMcpAnalyticsConfig, emitTelemetryEvent, IngestDeliveryError, 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 { DEFAULT_INGEST_MAX_ATTEMPTS, DEFAULT_INGEST_RETRY_DELAY_MS, defaultMcpAnalyticsConfig, emitTelemetryEvent, IngestDeliveryError, 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@armature-tech/mcp-analytics",
3
- "version": "0.6.24",
3
+ "version": "0.6.25",
4
4
  "type": "module",
5
5
  "description": "MCP analytics wrapper SDK that instruments MCP tool declarations with telemetry.",
6
6
  "license": "Apache-2.0",