@armature-tech/mcp-analytics 0.6.28 → 0.6.30
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 +40 -16
- package/SKILL.md +27 -10
- package/dist/cjs/cli.js +1 -0
- package/dist/cjs/doctor.d.ts +4 -0
- package/dist/cjs/doctor.js +58 -3
- package/dist/cjs/emit.d.ts +16 -0
- package/dist/cjs/emit.js +101 -36
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +4 -1
- package/dist/cjs/mastra.d.ts +5 -3
- package/dist/cjs/mastra.js +12 -7
- package/dist/cjs/recorder.js +5 -1
- package/dist/cjs/request-capability.d.ts +1 -0
- package/dist/cjs/request-capability.js +10 -2
- package/dist/cjs/server.js +12 -3
- package/dist/cjs/stateless-http.js +1 -1
- package/dist/esm/cli.js +1 -0
- package/dist/esm/doctor.d.ts +4 -0
- package/dist/esm/doctor.js +55 -2
- package/dist/esm/emit.d.ts +16 -0
- package/dist/esm/emit.js +99 -35
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/mastra.d.ts +5 -3
- package/dist/esm/mastra.js +13 -8
- package/dist/esm/recorder.js +6 -2
- package/dist/esm/request-capability.d.ts +1 -0
- package/dist/esm/request-capability.js +8 -1
- package/dist/esm/server.js +13 -4
- package/dist/esm/stateless-http.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -20,14 +20,26 @@ MCP SDK 1.29 or newer is required when your tools use Zod 4 raw-shape
|
|
|
20
20
|
schemas. MCP SDK 1.20 accepts the package but silently drops fields from those
|
|
21
21
|
schemas, including Armature's telemetry field.
|
|
22
22
|
|
|
23
|
-
### 2. Add your ingest
|
|
23
|
+
### 2. Add your regional ingest configuration
|
|
24
24
|
|
|
25
|
-
Create a server in the
|
|
25
|
+
Create a server in the Armature dashboard for your account's region, then copy
|
|
26
|
+
**both** generated environment variables into your server environment:
|
|
26
27
|
|
|
27
28
|
~~~bash
|
|
28
29
|
export ANALYTICS_INGEST_API_KEY="..."
|
|
30
|
+
export ANALYTICS_INGEST_URL="https://app.armature.tech/api/mcp-analytics/ingest" # US
|
|
29
31
|
~~~
|
|
30
32
|
|
|
33
|
+
For an EU account, `ANALYTICS_INGEST_URL` is required and must be:
|
|
34
|
+
|
|
35
|
+
~~~bash
|
|
36
|
+
export ANALYTICS_INGEST_URL="https://eu.armature.tech/api/mcp-analytics/ingest"
|
|
37
|
+
~~~
|
|
38
|
+
|
|
39
|
+
The URL may be omitted only for US accounts because the SDK defaults to the US
|
|
40
|
+
endpoint. Keeping the generated URL explicit is recommended and makes the
|
|
41
|
+
deployment region unambiguous.
|
|
42
|
+
|
|
31
43
|
### Verify the installation locally
|
|
32
44
|
|
|
33
45
|
Run the doctor against the same environment and MCP server you plan to deploy:
|
|
@@ -47,7 +59,8 @@ every tool exposes Armature's telemetry contract, and checks the existing
|
|
|
47
59
|
`ANALYTICS_INGEST_API_KEY` with an empty authenticated batch. The probe creates
|
|
48
60
|
no session and sends no tool arguments, responses, or user content. Add
|
|
49
61
|
`--skip-ingest` for a fully offline check, or `--json` for a support-ready
|
|
50
|
-
machine-readable report.
|
|
62
|
+
machine-readable report. It also compares marked `ami_us_` / `ami_eu_` keys
|
|
63
|
+
with the ingest and MCP URLs, and will not send the probe when they disagree.
|
|
51
64
|
|
|
52
65
|
### 3. Instrument your MCP server
|
|
53
66
|
|
|
@@ -208,7 +221,9 @@ The full integration playbook is in [SKILL.md](SKILL.md).
|
|
|
208
221
|
|
|
209
222
|
## Configuration
|
|
210
223
|
|
|
211
|
-
|
|
224
|
+
Every server needs **ANALYTICS_INGEST_API_KEY**. EU servers must also set
|
|
225
|
+
**ANALYTICS_INGEST_URL**; US servers may rely on the US default. Operational
|
|
226
|
+
controls are available when you need them:
|
|
212
227
|
|
|
213
228
|
~~~ts
|
|
214
229
|
type McpAnalyticsConfig = {
|
|
@@ -235,13 +250,13 @@ type McpAnalyticsConfig = {
|
|
|
235
250
|
|
|
236
251
|
| Option | Default | Purpose |
|
|
237
252
|
| --- | --- | --- |
|
|
238
|
-
| **endpointUrl** | Armature cloud | Override the ingestion endpoint |
|
|
253
|
+
| **endpointUrl** | US Armature cloud | Override the ingestion endpoint; use `https://eu.armature.tech/api/mcp-analytics/ingest` for EU |
|
|
239
254
|
| **apiKey** | **ANALYTICS_INGEST_API_KEY** | Authenticate events and identify the MCP server |
|
|
240
255
|
| **actorId** | Derived from request auth | Supply a stable user or tenant seed |
|
|
241
256
|
| **actorIdentifier** | None | Store a caller-provided identifier verbatim |
|
|
242
257
|
| **enabled** | **true** | Enable or disable instrumentation |
|
|
243
258
|
| **delivery** | **"background"** | Use **"await"** for serverless or short-lived processes |
|
|
244
|
-
| **timeoutMs** | **
|
|
259
|
+
| **timeoutMs** | **5000** | Set the timeout for each delivery attempt |
|
|
245
260
|
| **emit** | Network emitter | Replace delivery for tests or custom pipelines |
|
|
246
261
|
| **onError** | None | Observe delivery failures |
|
|
247
262
|
| **captureTelemetry** | **true** | Disable conversation-derived telemetry entirely (see below) |
|
|
@@ -250,21 +265,28 @@ type McpAnalyticsConfig = {
|
|
|
250
265
|
| **redactEvent** | None | Mutate or drop the prepared whole tool-call event |
|
|
251
266
|
| **schedule** | None | Register background work with a serverless lifecycle primitive |
|
|
252
267
|
| **telemetryFieldMap** | None | Export existing argument fields as telemetry (see below) |
|
|
253
|
-
| **requestCapability** | **
|
|
268
|
+
| **requestCapability** | **true** | Inject `request_capability` so agents can report an unmet tool need; set `false` to disable |
|
|
269
|
+
|
|
270
|
+
Network failures, timeouts, `429`, and `5xx` responses are retried once after
|
|
271
|
+
100 ms (two attempts total). Other `4xx` responses are not retried.
|
|
272
|
+
`IngestDeliveryError` exposes a payload-free `code`, `status`, `retryable`, and
|
|
273
|
+
`attempts` through `onError`; telemetry delivery remains fail-open by default.
|
|
254
274
|
|
|
255
275
|
### Capability requests
|
|
256
276
|
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
277
|
+
The SDK-owned `request_capability` tool is added to the advertised tool list by
|
|
278
|
+
default. The tool accepts one required `capability` string and uses this
|
|
279
|
+
description exactly:
|
|
260
280
|
|
|
261
281
|
> Request a capability that is not provided by the currently available tools. Use this when a capability is required to complete the user’s request and no existing tool can perform it.
|
|
262
282
|
|
|
263
283
|
Calls are recorded through the normal analytics pipeline and feed Armature's
|
|
264
|
-
unmet-demand signals.
|
|
265
|
-
**enabled: false** or no API key/custom **emit** delivery is
|
|
266
|
-
|
|
267
|
-
customer-defined tool with the same name
|
|
284
|
+
unmet-demand signals. Set **requestCapability: false** to disable it. It is also
|
|
285
|
+
suppressed when **enabled: false** or no API key/custom **emit** delivery is
|
|
286
|
+
configured. When you explicitly set **requestCapability: true**, the name is
|
|
287
|
+
reserved: rename a customer-defined tool with the same name first. When it is on
|
|
288
|
+
merely by default, a customer tool of the same name takes precedence and the SDK
|
|
289
|
+
skips its own injection instead of failing.
|
|
268
290
|
|
|
269
291
|
```mermaid
|
|
270
292
|
sequenceDiagram
|
|
@@ -346,7 +368,7 @@ non-empty string no larger than 8 KiB. When **actorIdentifier** is absent,
|
|
|
346
368
|
| Variable | Purpose |
|
|
347
369
|
| --- | --- |
|
|
348
370
|
| **ANALYTICS_INGEST_API_KEY** | Armature ingest key |
|
|
349
|
-
| **ANALYTICS_INGEST_URL** | Optional
|
|
371
|
+
| **ANALYTICS_INGEST_URL** | Optional only for US, which defaults to `https://app.armature.tech/api/mcp-analytics/ingest`. Required for EU and must be `https://eu.armature.tech/api/mcp-analytics/ingest`. Preserve this variable when copying dashboard configuration. |
|
|
350
372
|
|
|
351
373
|
## Example
|
|
352
374
|
|
|
@@ -355,7 +377,9 @@ Run the complete stdio server in [examples/minimal](examples/minimal):
|
|
|
355
377
|
~~~bash
|
|
356
378
|
cd examples/minimal
|
|
357
379
|
npm install
|
|
358
|
-
ANALYTICS_INGEST_API_KEY="..."
|
|
380
|
+
ANALYTICS_INGEST_API_KEY="..." \
|
|
381
|
+
ANALYTICS_INGEST_URL="https://app.armature.tech/api/mcp-analytics/ingest" \
|
|
382
|
+
npm start
|
|
359
383
|
~~~
|
|
360
384
|
|
|
361
385
|
## Support
|
package/SKILL.md
CHANGED
|
@@ -53,22 +53,32 @@ If they aren't, install them too. Use the customer's package manager (check for
|
|
|
53
53
|
The package is published to the public npm registry — `npm install` works without any
|
|
54
54
|
`.npmrc` configuration.
|
|
55
55
|
|
|
56
|
-
## Step 3: Add the
|
|
56
|
+
## Step 3: Add the regional environment variables
|
|
57
57
|
|
|
58
|
-
The SDK needs one credential
|
|
58
|
+
The SDK needs one credential and an endpoint that matches the account region:
|
|
59
59
|
|
|
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
|
|
63
|
+
| `ANALYTICS_INGEST_URL` | Optional only for US, which defaults to `https://app.armature.tech/api/mcp-analytics/ingest`. Required for EU and must be `https://eu.armature.tech/api/mcp-analytics/ingest`. It may also target a local mock or staging environment. |
|
|
64
64
|
|
|
65
|
-
Add `ANALYTICS_INGEST_API_KEY`
|
|
66
|
-
`
|
|
67
|
-
|
|
65
|
+
Add `ANALYTICS_INGEST_API_KEY` and the region-appropriate
|
|
66
|
+
`ANALYTICS_INGEST_URL` to whatever env mechanism the project uses
|
|
67
|
+
(`.env.example`, `wrangler.toml`, `vercel.json`, fly secrets, k8s manifests).
|
|
68
|
+
When the Armature dashboard supplies a copied two-line configuration, preserve
|
|
69
|
+
both lines; never discard the URL for an EU account. Do **not** commit real
|
|
70
|
+
values; put placeholders in `.env.example` and tell the user where to paste the
|
|
71
|
+
real values. A hand-authored US configuration may omit the URL because the SDK
|
|
72
|
+
defaults to the US endpoint, but keeping it explicit is recommended.
|
|
68
73
|
|
|
69
74
|
If `ANALYTICS_INGEST_API_KEY` is missing at runtime, the SDK silently no-ops. That's intentional
|
|
70
75
|
for local dev — say so once, don't add guards.
|
|
71
76
|
|
|
77
|
+
The network emitter uses a 5-second timeout per attempt and at most two
|
|
78
|
+
attempts, separated by 100 ms. It retries only network failures, timeouts,
|
|
79
|
+
`429`, and `5xx`; other `4xx` responses are returned once as a structured
|
|
80
|
+
`IngestDeliveryError` through `onError` without breaking the host application.
|
|
81
|
+
|
|
72
82
|
## Step 4: Pick a delivery mode
|
|
73
83
|
|
|
74
84
|
The default is `delivery: "background"`, which queues sanitization, redaction,
|
|
@@ -110,6 +120,7 @@ const server = createMcpAnalyticsServer(
|
|
|
110
120
|
armature: {
|
|
111
121
|
// endpointUrl / apiKey default to env vars
|
|
112
122
|
delivery: "await", // or "background" — see Step 4
|
|
123
|
+
// request_capability is on by default; add `requestCapability: false` to disable (see Step 7).
|
|
113
124
|
},
|
|
114
125
|
},
|
|
115
126
|
);
|
|
@@ -402,7 +413,8 @@ npx @armature-tech/mcp-analytics doctor --url http://localhost:3000/mcp
|
|
|
402
413
|
Run it with the same `ANALYTICS_INGEST_API_KEY` and
|
|
403
414
|
`ANALYTICS_INGEST_URL` environment as the server. It verifies the MCP
|
|
404
415
|
handshake, every served tool's public wrapping contract, and ingest auth using
|
|
405
|
-
an empty content-free batch.
|
|
416
|
+
an empty content-free batch. It also rejects a marked key whose region does
|
|
417
|
+
not match the ingest or MCP URL without sending the key. Use `--skip-ingest` only when the user explicitly
|
|
406
418
|
wants an offline check. Include the doctor result in the handoff.
|
|
407
419
|
|
|
408
420
|
**Check 1 — Schema includes telemetry.** Spin up the server, ask it for `tools/list`, and
|
|
@@ -437,9 +449,14 @@ Tell the user, briefly:
|
|
|
437
449
|
|
|
438
450
|
- `delivery: "background"` drops batches in serverless. You picked `"await"` (or not — say which).
|
|
439
451
|
- The SDK no-ops silently if `ANALYTICS_INGEST_API_KEY` is missing. Set it in prod.
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
452
|
+
- Confirm where both regional environment variables are configured; the URL is required for EU.
|
|
453
|
+
- The SDK adds a `request_capability` tool (on by default) so the agent can report a capability the
|
|
454
|
+
current tools can't satisfy — this is what surfaces "unmet demand" use cases in Armature.
|
|
455
|
+
It's recommended, so leave it on. Briefly tell the user it's enabled and offer to turn it off:
|
|
456
|
+
set `requestCapability: false` in the `armature` config if they'd rather not expose it.
|
|
457
|
+
|
|
458
|
+
Don't pad with anything else. End with one line: what you changed and what the
|
|
459
|
+
user needs to do (paste the generated key and regional URL, deploy).
|
|
443
460
|
|
|
444
461
|
## What NOT to do
|
|
445
462
|
|
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"
|
package/dist/cjs/doctor.d.ts
CHANGED
|
@@ -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 {};
|
package/dist/cjs/doctor.js
CHANGED
|
@@ -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 {
|
|
@@ -348,15 +398,20 @@ const runDoctor = async (options, dependencies = { inspectMcp: exports.inspectMc
|
|
|
348
398
|
? "Start the MCP server, verify the URL/auth headers, and run the doctor again."
|
|
349
399
|
: "Run the server command directly once, fix startup errors, then run the doctor again."));
|
|
350
400
|
}
|
|
401
|
+
const apiKey = environment.ANALYTICS_INGEST_API_KEY;
|
|
402
|
+
const endpoint = environment.ANALYTICS_INGEST_URL || DEFAULT_INGEST_URL;
|
|
403
|
+
const regionalCheck = regionalConfigurationCheck(options.target, endpoint, apiKey);
|
|
404
|
+
checks.push(regionalCheck);
|
|
351
405
|
if (options.skipIngest) {
|
|
352
406
|
checks.push(warn("ingest-auth", "Armature ingest", "Skipped by --skip-ingest; no network request was made."));
|
|
353
407
|
}
|
|
354
408
|
else {
|
|
355
|
-
const apiKey = environment.ANALYTICS_INGEST_API_KEY;
|
|
356
|
-
const endpoint = environment.ANALYTICS_INGEST_URL || DEFAULT_INGEST_URL;
|
|
357
409
|
if (!apiKey) {
|
|
358
410
|
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."));
|
|
359
411
|
}
|
|
412
|
+
else if (regionalCheck.status === "fail") {
|
|
413
|
+
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."));
|
|
414
|
+
}
|
|
360
415
|
else {
|
|
361
416
|
try {
|
|
362
417
|
await dependencies.verifyIngest(endpoint, apiKey, options.timeoutMs);
|
package/dist/cjs/emit.d.ts
CHANGED
|
@@ -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>;
|
|
@@ -20,6 +35,7 @@ export type IngestResult = {
|
|
|
20
35
|
ok?: boolean;
|
|
21
36
|
reason?: string;
|
|
22
37
|
status?: number;
|
|
38
|
+
attempts?: number;
|
|
23
39
|
accepted?: number;
|
|
24
40
|
rejected?: IngestRejection[];
|
|
25
41
|
duplicateCount?: number;
|
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.postAndCheck = exports.postTelemetryEvent = exports.describeIngestRejection = exports.IngestRejectedError = 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.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:
|
|
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") ??
|
|
@@ -96,44 +130,75 @@ const postTelemetryEvent = async (batch, config = exports.defaultMcpAnalyticsCon
|
|
|
96
130
|
return { skipped: true, reason: "ingest_config_missing" };
|
|
97
131
|
}
|
|
98
132
|
const body = JSON.stringify(batch);
|
|
99
|
-
const
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
const
|
|
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}`);
|
|
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 = {};
|
|
133
|
+
const timeoutMs = config.armature?.timeoutMs ?? exports.defaultMcpAnalyticsConfig.armature.timeoutMs;
|
|
134
|
+
for (let attempt = 1; attempt <= exports.DEFAULT_INGEST_MAX_ATTEMPTS; attempt += 1) {
|
|
135
|
+
const controller = new AbortController();
|
|
136
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
119
137
|
try {
|
|
120
|
-
|
|
138
|
+
const response = await fetch(endpointUrl, {
|
|
139
|
+
method: "POST",
|
|
140
|
+
headers: {
|
|
141
|
+
"Content-Type": "application/json",
|
|
142
|
+
Authorization: `Bearer ${apiKey}`,
|
|
143
|
+
},
|
|
144
|
+
body,
|
|
145
|
+
signal: controller.signal,
|
|
146
|
+
});
|
|
147
|
+
if (!response.ok) {
|
|
148
|
+
const retryable = response.status === 429 || response.status >= 500;
|
|
149
|
+
const code = await responseErrorCode(response);
|
|
150
|
+
if (retryable && attempt < exports.DEFAULT_INGEST_MAX_ATTEMPTS) {
|
|
151
|
+
await sleep(exports.DEFAULT_INGEST_RETRY_DELAY_MS);
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
throw new IngestDeliveryError(`Armature ingest failed with HTTP ${response.status} (${code})`, { code, status: response.status, retryable, attempts: attempt });
|
|
155
|
+
}
|
|
156
|
+
const text = await response.text();
|
|
157
|
+
// Ingest can report in-band rejection/dedup on a successful status. A
|
|
158
|
+
// non-JSON body means rejections are unobservable, not that delivery
|
|
159
|
+
// failed.
|
|
160
|
+
let parsed = {};
|
|
161
|
+
try {
|
|
162
|
+
parsed = text ? JSON.parse(text) : {};
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
parsed = {};
|
|
166
|
+
}
|
|
167
|
+
return {
|
|
168
|
+
skipped: false,
|
|
169
|
+
ok: true,
|
|
170
|
+
status: response.status,
|
|
171
|
+
attempts: attempt,
|
|
172
|
+
accepted: typeof parsed.accepted === "number" ? parsed.accepted : undefined,
|
|
173
|
+
rejected: Array.isArray(parsed.rejected) ? parsed.rejected : [],
|
|
174
|
+
duplicateCount: typeof parsed.duplicate_count === "number" ? parsed.duplicate_count : undefined,
|
|
175
|
+
};
|
|
121
176
|
}
|
|
122
|
-
catch {
|
|
123
|
-
|
|
177
|
+
catch (error) {
|
|
178
|
+
if (error instanceof IngestDeliveryError)
|
|
179
|
+
throw error;
|
|
180
|
+
const timedOut = error?.name === "AbortError";
|
|
181
|
+
if (attempt < exports.DEFAULT_INGEST_MAX_ATTEMPTS) {
|
|
182
|
+
await sleep(exports.DEFAULT_INGEST_RETRY_DELAY_MS);
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
throw new IngestDeliveryError(timedOut
|
|
186
|
+
? `Armature ingest timed out after ${timeoutMs}ms`
|
|
187
|
+
: "Armature ingest connection failed", {
|
|
188
|
+
code: timedOut ? "ingest_timeout" : "ingest_connection_failed",
|
|
189
|
+
retryable: true,
|
|
190
|
+
attempts: attempt,
|
|
191
|
+
cause: error,
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
finally {
|
|
195
|
+
clearTimeout(timeout);
|
|
124
196
|
}
|
|
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);
|
|
136
197
|
}
|
|
198
|
+
throw new IngestDeliveryError("Armature ingest delivery failed", {
|
|
199
|
+
code: "ingest_delivery_failed",
|
|
200
|
+
attempts: exports.DEFAULT_INGEST_MAX_ATTEMPTS,
|
|
201
|
+
});
|
|
137
202
|
};
|
|
138
203
|
exports.postTelemetryEvent = postTelemetryEvent;
|
|
139
204
|
// The default network emit for every delivery path (privacy queue, flushable
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -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, IngestRejectedError, postTelemetryEvent, reportEmitError, } from "./emit.js";
|
|
7
|
+
export { DEFAULT_INGEST_MAX_ATTEMPTS, DEFAULT_INGEST_RETRY_DELAY_MS, defaultMcpAnalyticsConfig, emitTelemetryEvent, IngestDeliveryError, 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.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;
|
|
3
|
+
exports.instrumentMcpServerTools = exports.withMcpAnalytics = exports.createMcpAnalyticsServer = exports.resolveStatelessHttpSession = exports.parseStatelessSessionClientInfo = exports.buildStatelessSessionId = exports.createAnalyticsRecorder = exports.reportEmitError = exports.postTelemetryEvent = exports.IngestRejectedError = 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, "IngestRejectedError", { enumerable: true, get: function () { return emit_js_1.IngestRejectedError; } });
|
|
44
47
|
Object.defineProperty(exports, "postTelemetryEvent", { enumerable: true, get: function () { return emit_js_1.postTelemetryEvent; } });
|
|
45
48
|
Object.defineProperty(exports, "reportEmitError", { enumerable: true, get: function () { return emit_js_1.reportEmitError; } });
|
package/dist/cjs/mastra.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { AnalyticsRecorder, InternalMcpAnalyticsConfig, McpAnalyticsConfig, RequestExtra } from "./types.js";
|
|
2
|
+
import { REQUEST_CAPABILITY_TOOL_NAME } from "./request-capability.js";
|
|
2
3
|
export type MastraToolExecute = (inputData: any, context?: any) => unknown | Promise<unknown>;
|
|
3
4
|
export type MastraTool = {
|
|
4
5
|
id?: string;
|
|
@@ -9,17 +10,18 @@ export type MastraTool = {
|
|
|
9
10
|
execute?: MastraToolExecute;
|
|
10
11
|
};
|
|
11
12
|
export type MastraToolMap = Record<string, MastraTool>;
|
|
13
|
+
export type WithRequestCapability<T> = T & Partial<Record<typeof REQUEST_CAPABILITY_TOOL_NAME, MastraTool>>;
|
|
12
14
|
export type MastraAdapterOptions = McpAnalyticsConfig & {
|
|
13
15
|
resolveExtra?: (mastraContext: unknown) => RequestExtra | undefined;
|
|
14
16
|
};
|
|
15
17
|
export declare const defaultMastraResolveExtra: (mastraContext: unknown) => RequestExtra | undefined;
|
|
16
18
|
export declare const wrapMastraToolsWithRecorder: <T extends MastraToolMap>(tools: T, recorder: AnalyticsRecorder, config?: InternalMcpAnalyticsConfig, options?: {
|
|
17
19
|
resolveExtra?: MastraAdapterOptions["resolveExtra"];
|
|
18
|
-
}) => T
|
|
19
|
-
export declare const wrapMastraTools: <T extends MastraToolMap>(tools: T, options?: MastraAdapterOptions) => T
|
|
20
|
+
}) => WithRequestCapability<T>;
|
|
21
|
+
export declare const wrapMastraTools: <T extends MastraToolMap>(tools: T, options?: MastraAdapterOptions) => WithRequestCapability<T>;
|
|
20
22
|
export type MastraAnalytics = {
|
|
21
23
|
recorder: AnalyticsRecorder;
|
|
22
|
-
wrapTools: <T extends MastraToolMap>(tools: T) => T
|
|
24
|
+
wrapTools: <T extends MastraToolMap>(tools: T) => WithRequestCapability<T>;
|
|
23
25
|
flush: () => Promise<void>;
|
|
24
26
|
};
|
|
25
27
|
export declare const createMastraAnalytics: (options?: MastraAdapterOptions) => MastraAnalytics;
|
package/dist/cjs/mastra.js
CHANGED
|
@@ -143,19 +143,24 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
|
|
|
143
143
|
// passes the constraint without a cast.
|
|
144
144
|
const wrapMastraToolsWithRecorder = (tools, recorder, config = {}, options = {}) => {
|
|
145
145
|
const out = {};
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
146
|
+
// The recorder is the source of truth for whether request_capability exists:
|
|
147
|
+
// the high-level wrapMastraTools builds it from the same config, and direct
|
|
148
|
+
// callers may pass a lean wrap-time config that omits the delivery sink. Now
|
|
149
|
+
// that the tool is on by default, re-deriving enablement from that lean
|
|
150
|
+
// config would spuriously disagree with a recorder that has it.
|
|
151
|
+
const requestCapabilityEnabled = recorder.hasTool(request_capability_js_1.REQUEST_CAPABILITY_TOOL_NAME);
|
|
152
|
+
const requestCapabilityCollision = requestCapabilityEnabled
|
|
151
153
|
&& Object.entries(tools).some(([key, tool]) => key === request_capability_js_1.REQUEST_CAPABILITY_TOOL_NAME
|
|
152
|
-
|| tool.id === request_capability_js_1.REQUEST_CAPABILITY_TOOL_NAME)
|
|
154
|
+
|| tool.id === request_capability_js_1.REQUEST_CAPABILITY_TOOL_NAME);
|
|
155
|
+
// A customer tool of the same name is reserved only when the caller
|
|
156
|
+
// explicitly opted in; when on by default it wins and the SDK skips its own.
|
|
157
|
+
if (requestCapabilityCollision && (0, request_capability_js_1.isRequestCapabilityExplicit)(config)) {
|
|
153
158
|
throw new Error(`Tool name "${request_capability_js_1.REQUEST_CAPABILITY_TOOL_NAME}" is reserved while armature.requestCapability is enabled.`);
|
|
154
159
|
}
|
|
155
160
|
for (const [key, tool] of Object.entries(tools)) {
|
|
156
161
|
out[key] = wrapOneTool(key, tool, recorder, config, options.resolveExtra);
|
|
157
162
|
}
|
|
158
|
-
if (requestCapabilityEnabled) {
|
|
163
|
+
if (requestCapabilityEnabled && !requestCapabilityCollision) {
|
|
159
164
|
out[request_capability_js_1.REQUEST_CAPABILITY_TOOL_NAME] = {
|
|
160
165
|
id: request_capability_js_1.REQUEST_CAPABILITY_TOOL_NAME,
|
|
161
166
|
description: request_capability_js_1.REQUEST_CAPABILITY_DESCRIPTION,
|
package/dist/cjs/recorder.js
CHANGED
|
@@ -357,7 +357,11 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
|
|
|
357
357
|
};
|
|
358
358
|
const tool = (registration, handler) => {
|
|
359
359
|
if ((0, request_capability_js_1.isRequestCapabilityEnabled)(config)
|
|
360
|
-
&& registration.name === request_capability_js_1.REQUEST_CAPABILITY_TOOL_NAME
|
|
360
|
+
&& registration.name === request_capability_js_1.REQUEST_CAPABILITY_TOOL_NAME
|
|
361
|
+
&& (0, request_capability_js_1.isRequestCapabilityExplicit)(config)) {
|
|
362
|
+
// Reserved only when the caller explicitly opted in. When the tool is on
|
|
363
|
+
// merely by default, a customer tool of the same name takes precedence:
|
|
364
|
+
// fall through so this registration overwrites the SDK-owned entry.
|
|
361
365
|
throw new Error(`Tool name "${request_capability_js_1.REQUEST_CAPABILITY_TOOL_NAME}" is reserved while armature.requestCapability is enabled.`);
|
|
362
366
|
}
|
|
363
367
|
registeredTools.set(registration.name, {
|
|
@@ -9,4 +9,5 @@ export declare const REQUEST_CAPABILITY_ZOD_SHAPE: {
|
|
|
9
9
|
capability: z.ZodString;
|
|
10
10
|
};
|
|
11
11
|
export declare const isRequestCapabilityEnabled: (config: McpAnalyticsConfig) => boolean;
|
|
12
|
+
export declare const isRequestCapabilityExplicit: (config: McpAnalyticsConfig) => boolean;
|
|
12
13
|
export declare const handleRequestCapability: (args: unknown) => CallToolResult;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.handleRequestCapability = exports.isRequestCapabilityEnabled = exports.REQUEST_CAPABILITY_ZOD_SHAPE = exports.REQUEST_CAPABILITY_INPUT_SCHEMA = exports.REQUEST_CAPABILITY_ARGUMENT_DESCRIPTION = exports.REQUEST_CAPABILITY_DESCRIPTION = exports.REQUEST_CAPABILITY_TOOL_NAME = void 0;
|
|
3
|
+
exports.handleRequestCapability = exports.isRequestCapabilityExplicit = exports.isRequestCapabilityEnabled = exports.REQUEST_CAPABILITY_ZOD_SHAPE = exports.REQUEST_CAPABILITY_INPUT_SCHEMA = exports.REQUEST_CAPABILITY_ARGUMENT_DESCRIPTION = exports.REQUEST_CAPABILITY_DESCRIPTION = exports.REQUEST_CAPABILITY_TOOL_NAME = void 0;
|
|
4
4
|
const zod_1 = require("zod");
|
|
5
5
|
const emit_js_1 = require("./emit.js");
|
|
6
6
|
const utils_js_1 = require("./utils.js");
|
|
@@ -29,10 +29,18 @@ exports.REQUEST_CAPABILITY_ZOD_SHAPE = {
|
|
|
29
29
|
.max(1000)
|
|
30
30
|
.describe(exports.REQUEST_CAPABILITY_ARGUMENT_DESCRIPTION),
|
|
31
31
|
};
|
|
32
|
-
const isRequestCapabilityEnabled = (config) => config.armature?.requestCapability
|
|
32
|
+
const isRequestCapabilityEnabled = (config) => config.armature?.requestCapability !== false
|
|
33
33
|
&& config.armature?.enabled !== false
|
|
34
34
|
&& (typeof config.armature?.emit === "function" || Boolean((0, emit_js_1.resolveApiKey)(config)));
|
|
35
35
|
exports.isRequestCapabilityEnabled = isRequestCapabilityEnabled;
|
|
36
|
+
// True only when the caller explicitly opted in (requestCapability: true).
|
|
37
|
+
// Injection is governed by isRequestCapabilityEnabled (on unless explicitly
|
|
38
|
+
// disabled); the reserved-name and server-shape guards key off this stricter
|
|
39
|
+
// check instead, so a server that is only on-by-default skips injection
|
|
40
|
+
// quietly on a collision or an incompatible factory result rather than
|
|
41
|
+
// throwing and breaking an existing integration on upgrade.
|
|
42
|
+
const isRequestCapabilityExplicit = (config) => config.armature?.requestCapability === true;
|
|
43
|
+
exports.isRequestCapabilityExplicit = isRequestCapabilityExplicit;
|
|
36
44
|
const handleRequestCapability = (args) => {
|
|
37
45
|
if (!(0, utils_js_1.isRecord)(args)
|
|
38
46
|
|| typeof args.capability !== "string"
|
package/dist/cjs/server.js
CHANGED
|
@@ -161,17 +161,26 @@ const withMcpAnalytics = (config, createServer) => {
|
|
|
161
161
|
// registers it once without adding telemetry fields or mutating its exact
|
|
162
162
|
// description.
|
|
163
163
|
if ((0, request_capability_js_1.isRequestCapabilityEnabled)(config) && !(result instanceof mcp_js_1.McpServer)) {
|
|
164
|
-
|
|
164
|
+
// Only a hard error when the caller explicitly opted in. A server that is
|
|
165
|
+
// request_capability-on merely by default and doesn't return an McpServer
|
|
166
|
+
// silently skips injection instead of breaking on upgrade.
|
|
167
|
+
if ((0, request_capability_js_1.isRequestCapabilityExplicit)(config)) {
|
|
168
|
+
throw new Error("armature.requestCapability requires the server factory to return an McpServer instance.");
|
|
169
|
+
}
|
|
165
170
|
}
|
|
166
171
|
if ((0, request_capability_js_1.isRequestCapabilityEnabled)(config) && result instanceof mcp_js_1.McpServer) {
|
|
167
172
|
try {
|
|
168
173
|
recorder.attachToMcpServer(result);
|
|
169
174
|
}
|
|
170
175
|
catch (error) {
|
|
171
|
-
|
|
176
|
+
const collision = error instanceof Error && /already registered/i.test(error.message);
|
|
177
|
+
// A pre-existing tool of the same name is reserved only when the caller
|
|
178
|
+
// explicitly opted in; on-by-default yields to the customer's tool.
|
|
179
|
+
if (collision && (0, request_capability_js_1.isRequestCapabilityExplicit)(config)) {
|
|
172
180
|
throw new Error('Tool name "request_capability" is reserved while armature.requestCapability is enabled.', { cause: error });
|
|
173
181
|
}
|
|
174
|
-
|
|
182
|
+
if (!collision)
|
|
183
|
+
throw error;
|
|
175
184
|
}
|
|
176
185
|
}
|
|
177
186
|
return { result, recorder };
|
|
@@ -28,7 +28,7 @@ const utils_js_1 = require("./utils.js");
|
|
|
28
28
|
// });
|
|
29
29
|
// await analytics.dispatch(name, args, { ctx, ...session.dispatchContext });
|
|
30
30
|
const SESSION_ID_RE = /^mcp_([A-Za-z0-9.-]+)_v_([A-Za-z0-9.-]*)_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
|
|
31
|
-
const SESSION_SEED_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-
|
|
31
|
+
const SESSION_SEED_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
32
32
|
const ANONYMOUS_NAME = "unknown";
|
|
33
33
|
const slugPart = (value, fallback) => {
|
|
34
34
|
const slug = String(value ?? "")
|
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"
|
package/dist/esm/doctor.d.ts
CHANGED
|
@@ -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 {};
|
package/dist/esm/doctor.js
CHANGED
|
@@ -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 {
|
|
@@ -339,15 +387,20 @@ export const runDoctor = async (options, dependencies = { inspectMcp, detectLoca
|
|
|
339
387
|
? "Start the MCP server, verify the URL/auth headers, and run the doctor again."
|
|
340
388
|
: "Run the server command directly once, fix startup errors, then run the doctor again."));
|
|
341
389
|
}
|
|
390
|
+
const apiKey = environment.ANALYTICS_INGEST_API_KEY;
|
|
391
|
+
const endpoint = environment.ANALYTICS_INGEST_URL || DEFAULT_INGEST_URL;
|
|
392
|
+
const regionalCheck = regionalConfigurationCheck(options.target, endpoint, apiKey);
|
|
393
|
+
checks.push(regionalCheck);
|
|
342
394
|
if (options.skipIngest) {
|
|
343
395
|
checks.push(warn("ingest-auth", "Armature ingest", "Skipped by --skip-ingest; no network request was made."));
|
|
344
396
|
}
|
|
345
397
|
else {
|
|
346
|
-
const apiKey = environment.ANALYTICS_INGEST_API_KEY;
|
|
347
|
-
const endpoint = environment.ANALYTICS_INGEST_URL || DEFAULT_INGEST_URL;
|
|
348
398
|
if (!apiKey) {
|
|
349
399
|
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."));
|
|
350
400
|
}
|
|
401
|
+
else if (regionalCheck.status === "fail") {
|
|
402
|
+
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."));
|
|
403
|
+
}
|
|
351
404
|
else {
|
|
352
405
|
try {
|
|
353
406
|
await dependencies.verifyIngest(endpoint, apiKey, options.timeoutMs);
|
package/dist/esm/emit.d.ts
CHANGED
|
@@ -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>;
|
|
@@ -20,6 +35,7 @@ export type IngestResult = {
|
|
|
20
35
|
ok?: boolean;
|
|
21
36
|
reason?: string;
|
|
22
37
|
status?: number;
|
|
38
|
+
attempts?: number;
|
|
23
39
|
accepted?: number;
|
|
24
40
|
rejected?: IngestRejection[];
|
|
25
41
|
duplicateCount?: number;
|
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:
|
|
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") ??
|
|
@@ -87,44 +120,75 @@ export const postTelemetryEvent = async (batch, config = defaultMcpAnalyticsConf
|
|
|
87
120
|
return { skipped: true, reason: "ingest_config_missing" };
|
|
88
121
|
}
|
|
89
122
|
const body = JSON.stringify(batch);
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
const
|
|
94
|
-
method: "POST",
|
|
95
|
-
headers: {
|
|
96
|
-
"Content-Type": "application/json",
|
|
97
|
-
Authorization: `Bearer ${apiKey}`,
|
|
98
|
-
},
|
|
99
|
-
body,
|
|
100
|
-
signal: controller.signal,
|
|
101
|
-
});
|
|
102
|
-
const text = await response.text();
|
|
103
|
-
if (!response.ok) {
|
|
104
|
-
throw new Error(`Armature ingest failed with ${response.status}: ${text}`);
|
|
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 = {};
|
|
123
|
+
const timeoutMs = config.armature?.timeoutMs ?? defaultMcpAnalyticsConfig.armature.timeoutMs;
|
|
124
|
+
for (let attempt = 1; attempt <= DEFAULT_INGEST_MAX_ATTEMPTS; attempt += 1) {
|
|
125
|
+
const controller = new AbortController();
|
|
126
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
110
127
|
try {
|
|
111
|
-
|
|
128
|
+
const response = await fetch(endpointUrl, {
|
|
129
|
+
method: "POST",
|
|
130
|
+
headers: {
|
|
131
|
+
"Content-Type": "application/json",
|
|
132
|
+
Authorization: `Bearer ${apiKey}`,
|
|
133
|
+
},
|
|
134
|
+
body,
|
|
135
|
+
signal: controller.signal,
|
|
136
|
+
});
|
|
137
|
+
if (!response.ok) {
|
|
138
|
+
const retryable = response.status === 429 || response.status >= 500;
|
|
139
|
+
const code = await responseErrorCode(response);
|
|
140
|
+
if (retryable && attempt < DEFAULT_INGEST_MAX_ATTEMPTS) {
|
|
141
|
+
await sleep(DEFAULT_INGEST_RETRY_DELAY_MS);
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
throw new IngestDeliveryError(`Armature ingest failed with HTTP ${response.status} (${code})`, { code, status: response.status, retryable, attempts: attempt });
|
|
145
|
+
}
|
|
146
|
+
const text = await response.text();
|
|
147
|
+
// Ingest can report in-band rejection/dedup on a successful status. A
|
|
148
|
+
// non-JSON body means rejections are unobservable, not that delivery
|
|
149
|
+
// failed.
|
|
150
|
+
let parsed = {};
|
|
151
|
+
try {
|
|
152
|
+
parsed = text ? JSON.parse(text) : {};
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
parsed = {};
|
|
156
|
+
}
|
|
157
|
+
return {
|
|
158
|
+
skipped: false,
|
|
159
|
+
ok: true,
|
|
160
|
+
status: response.status,
|
|
161
|
+
attempts: attempt,
|
|
162
|
+
accepted: typeof parsed.accepted === "number" ? parsed.accepted : undefined,
|
|
163
|
+
rejected: Array.isArray(parsed.rejected) ? parsed.rejected : [],
|
|
164
|
+
duplicateCount: typeof parsed.duplicate_count === "number" ? parsed.duplicate_count : undefined,
|
|
165
|
+
};
|
|
112
166
|
}
|
|
113
|
-
catch {
|
|
114
|
-
|
|
167
|
+
catch (error) {
|
|
168
|
+
if (error instanceof IngestDeliveryError)
|
|
169
|
+
throw error;
|
|
170
|
+
const timedOut = error?.name === "AbortError";
|
|
171
|
+
if (attempt < DEFAULT_INGEST_MAX_ATTEMPTS) {
|
|
172
|
+
await sleep(DEFAULT_INGEST_RETRY_DELAY_MS);
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
throw new IngestDeliveryError(timedOut
|
|
176
|
+
? `Armature ingest timed out after ${timeoutMs}ms`
|
|
177
|
+
: "Armature ingest connection failed", {
|
|
178
|
+
code: timedOut ? "ingest_timeout" : "ingest_connection_failed",
|
|
179
|
+
retryable: true,
|
|
180
|
+
attempts: attempt,
|
|
181
|
+
cause: error,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
finally {
|
|
185
|
+
clearTimeout(timeout);
|
|
115
186
|
}
|
|
116
|
-
return {
|
|
117
|
-
skipped: false,
|
|
118
|
-
ok: true,
|
|
119
|
-
status: response.status,
|
|
120
|
-
accepted: typeof parsed.accepted === "number" ? parsed.accepted : undefined,
|
|
121
|
-
rejected: Array.isArray(parsed.rejected) ? parsed.rejected : [],
|
|
122
|
-
duplicateCount: typeof parsed.duplicate_count === "number" ? parsed.duplicate_count : undefined,
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
finally {
|
|
126
|
-
clearTimeout(timeout);
|
|
127
187
|
}
|
|
188
|
+
throw new IngestDeliveryError("Armature ingest delivery failed", {
|
|
189
|
+
code: "ingest_delivery_failed",
|
|
190
|
+
attempts: DEFAULT_INGEST_MAX_ATTEMPTS,
|
|
191
|
+
});
|
|
128
192
|
};
|
|
129
193
|
// The default network emit for every delivery path (privacy queue, flushable
|
|
130
194
|
// emitter, one-shot emit): POST, then raise on in-body rejection so the caller's
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -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, IngestRejectedError, postTelemetryEvent, reportEmitError, } from "./emit.js";
|
|
7
|
+
export { DEFAULT_INGEST_MAX_ATTEMPTS, DEFAULT_INGEST_RETRY_DELAY_MS, defaultMcpAnalyticsConfig, emitTelemetryEvent, IngestDeliveryError, 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, IngestRejectedError, postTelemetryEvent, reportEmitError, } from "./emit.js";
|
|
6
|
+
export { DEFAULT_INGEST_MAX_ATTEMPTS, DEFAULT_INGEST_RETRY_DELAY_MS, defaultMcpAnalyticsConfig, emitTelemetryEvent, IngestDeliveryError, 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/mastra.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { AnalyticsRecorder, InternalMcpAnalyticsConfig, McpAnalyticsConfig, RequestExtra } from "./types.js";
|
|
2
|
+
import { REQUEST_CAPABILITY_TOOL_NAME } from "./request-capability.js";
|
|
2
3
|
export type MastraToolExecute = (inputData: any, context?: any) => unknown | Promise<unknown>;
|
|
3
4
|
export type MastraTool = {
|
|
4
5
|
id?: string;
|
|
@@ -9,17 +10,18 @@ export type MastraTool = {
|
|
|
9
10
|
execute?: MastraToolExecute;
|
|
10
11
|
};
|
|
11
12
|
export type MastraToolMap = Record<string, MastraTool>;
|
|
13
|
+
export type WithRequestCapability<T> = T & Partial<Record<typeof REQUEST_CAPABILITY_TOOL_NAME, MastraTool>>;
|
|
12
14
|
export type MastraAdapterOptions = McpAnalyticsConfig & {
|
|
13
15
|
resolveExtra?: (mastraContext: unknown) => RequestExtra | undefined;
|
|
14
16
|
};
|
|
15
17
|
export declare const defaultMastraResolveExtra: (mastraContext: unknown) => RequestExtra | undefined;
|
|
16
18
|
export declare const wrapMastraToolsWithRecorder: <T extends MastraToolMap>(tools: T, recorder: AnalyticsRecorder, config?: InternalMcpAnalyticsConfig, options?: {
|
|
17
19
|
resolveExtra?: MastraAdapterOptions["resolveExtra"];
|
|
18
|
-
}) => T
|
|
19
|
-
export declare const wrapMastraTools: <T extends MastraToolMap>(tools: T, options?: MastraAdapterOptions) => T
|
|
20
|
+
}) => WithRequestCapability<T>;
|
|
21
|
+
export declare const wrapMastraTools: <T extends MastraToolMap>(tools: T, options?: MastraAdapterOptions) => WithRequestCapability<T>;
|
|
20
22
|
export type MastraAnalytics = {
|
|
21
23
|
recorder: AnalyticsRecorder;
|
|
22
|
-
wrapTools: <T extends MastraToolMap>(tools: T) => T
|
|
24
|
+
wrapTools: <T extends MastraToolMap>(tools: T) => WithRequestCapability<T>;
|
|
23
25
|
flush: () => Promise<void>;
|
|
24
26
|
};
|
|
25
27
|
export declare const createMastraAnalytics: (options?: MastraAdapterOptions) => MastraAnalytics;
|
package/dist/esm/mastra.js
CHANGED
|
@@ -2,7 +2,7 @@ import { createAnalyticsRecorder } from "./recorder.js";
|
|
|
2
2
|
import { planToolTelemetry } from "./schema.js";
|
|
3
3
|
import { isRecord } from "./utils.js";
|
|
4
4
|
import { z } from "zod";
|
|
5
|
-
import {
|
|
5
|
+
import { isRequestCapabilityExplicit, REQUEST_CAPABILITY_ARGUMENT_DESCRIPTION, REQUEST_CAPABILITY_DESCRIPTION, REQUEST_CAPABILITY_TOOL_NAME, } from "./request-capability.js";
|
|
6
6
|
const readMcpExtra = (mastraContext) => {
|
|
7
7
|
if (!isRecord(mastraContext))
|
|
8
8
|
return undefined;
|
|
@@ -139,19 +139,24 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
|
|
|
139
139
|
// passes the constraint without a cast.
|
|
140
140
|
export const wrapMastraToolsWithRecorder = (tools, recorder, config = {}, options = {}) => {
|
|
141
141
|
const out = {};
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
142
|
+
// The recorder is the source of truth for whether request_capability exists:
|
|
143
|
+
// the high-level wrapMastraTools builds it from the same config, and direct
|
|
144
|
+
// callers may pass a lean wrap-time config that omits the delivery sink. Now
|
|
145
|
+
// that the tool is on by default, re-deriving enablement from that lean
|
|
146
|
+
// config would spuriously disagree with a recorder that has it.
|
|
147
|
+
const requestCapabilityEnabled = recorder.hasTool(REQUEST_CAPABILITY_TOOL_NAME);
|
|
148
|
+
const requestCapabilityCollision = requestCapabilityEnabled
|
|
147
149
|
&& Object.entries(tools).some(([key, tool]) => key === REQUEST_CAPABILITY_TOOL_NAME
|
|
148
|
-
|| tool.id === REQUEST_CAPABILITY_TOOL_NAME)
|
|
150
|
+
|| tool.id === REQUEST_CAPABILITY_TOOL_NAME);
|
|
151
|
+
// A customer tool of the same name is reserved only when the caller
|
|
152
|
+
// explicitly opted in; when on by default it wins and the SDK skips its own.
|
|
153
|
+
if (requestCapabilityCollision && isRequestCapabilityExplicit(config)) {
|
|
149
154
|
throw new Error(`Tool name "${REQUEST_CAPABILITY_TOOL_NAME}" is reserved while armature.requestCapability is enabled.`);
|
|
150
155
|
}
|
|
151
156
|
for (const [key, tool] of Object.entries(tools)) {
|
|
152
157
|
out[key] = wrapOneTool(key, tool, recorder, config, options.resolveExtra);
|
|
153
158
|
}
|
|
154
|
-
if (requestCapabilityEnabled) {
|
|
159
|
+
if (requestCapabilityEnabled && !requestCapabilityCollision) {
|
|
155
160
|
out[REQUEST_CAPABILITY_TOOL_NAME] = {
|
|
156
161
|
id: REQUEST_CAPABILITY_TOOL_NAME,
|
|
157
162
|
description: REQUEST_CAPABILITY_DESCRIPTION,
|
package/dist/esm/recorder.js
CHANGED
|
@@ -6,7 +6,7 @@ import { createBoundedKeySet, deriveToolResultError, headerValue, isJsonObjectSc
|
|
|
6
6
|
import { processScopedSessionId } from "./stdio-session.js";
|
|
7
7
|
import { getClientInfoForSessionId, installClientInfoCapture, } from "./client-info-cache.js";
|
|
8
8
|
import { parseStatelessSessionClientInfo } from "./stateless-http.js";
|
|
9
|
-
import { handleRequestCapability, isRequestCapabilityEnabled, REQUEST_CAPABILITY_DESCRIPTION, REQUEST_CAPABILITY_INPUT_SCHEMA, REQUEST_CAPABILITY_TOOL_NAME, REQUEST_CAPABILITY_ZOD_SHAPE, } from "./request-capability.js";
|
|
9
|
+
import { handleRequestCapability, isRequestCapabilityEnabled, isRequestCapabilityExplicit, REQUEST_CAPABILITY_DESCRIPTION, REQUEST_CAPABILITY_INPUT_SCHEMA, REQUEST_CAPABILITY_TOOL_NAME, REQUEST_CAPABILITY_ZOD_SHAPE, } from "./request-capability.js";
|
|
10
10
|
import { createPrivacyQueue } from "./queue.js";
|
|
11
11
|
const nudgeTelemetryDescriptions = (schema) => {
|
|
12
12
|
if (!isJsonObjectSchema(schema))
|
|
@@ -354,7 +354,11 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
|
|
|
354
354
|
};
|
|
355
355
|
const tool = (registration, handler) => {
|
|
356
356
|
if (isRequestCapabilityEnabled(config)
|
|
357
|
-
&& registration.name === REQUEST_CAPABILITY_TOOL_NAME
|
|
357
|
+
&& registration.name === REQUEST_CAPABILITY_TOOL_NAME
|
|
358
|
+
&& isRequestCapabilityExplicit(config)) {
|
|
359
|
+
// Reserved only when the caller explicitly opted in. When the tool is on
|
|
360
|
+
// merely by default, a customer tool of the same name takes precedence:
|
|
361
|
+
// fall through so this registration overwrites the SDK-owned entry.
|
|
358
362
|
throw new Error(`Tool name "${REQUEST_CAPABILITY_TOOL_NAME}" is reserved while armature.requestCapability is enabled.`);
|
|
359
363
|
}
|
|
360
364
|
registeredTools.set(registration.name, {
|
|
@@ -9,4 +9,5 @@ export declare const REQUEST_CAPABILITY_ZOD_SHAPE: {
|
|
|
9
9
|
capability: z.ZodString;
|
|
10
10
|
};
|
|
11
11
|
export declare const isRequestCapabilityEnabled: (config: McpAnalyticsConfig) => boolean;
|
|
12
|
+
export declare const isRequestCapabilityExplicit: (config: McpAnalyticsConfig) => boolean;
|
|
12
13
|
export declare const handleRequestCapability: (args: unknown) => CallToolResult;
|
|
@@ -26,9 +26,16 @@ export const REQUEST_CAPABILITY_ZOD_SHAPE = {
|
|
|
26
26
|
.max(1000)
|
|
27
27
|
.describe(REQUEST_CAPABILITY_ARGUMENT_DESCRIPTION),
|
|
28
28
|
};
|
|
29
|
-
export const isRequestCapabilityEnabled = (config) => config.armature?.requestCapability
|
|
29
|
+
export const isRequestCapabilityEnabled = (config) => config.armature?.requestCapability !== false
|
|
30
30
|
&& config.armature?.enabled !== false
|
|
31
31
|
&& (typeof config.armature?.emit === "function" || Boolean(resolveApiKey(config)));
|
|
32
|
+
// True only when the caller explicitly opted in (requestCapability: true).
|
|
33
|
+
// Injection is governed by isRequestCapabilityEnabled (on unless explicitly
|
|
34
|
+
// disabled); the reserved-name and server-shape guards key off this stricter
|
|
35
|
+
// check instead, so a server that is only on-by-default skips injection
|
|
36
|
+
// quietly on a collision or an incompatible factory result rather than
|
|
37
|
+
// throwing and breaking an existing integration on upgrade.
|
|
38
|
+
export const isRequestCapabilityExplicit = (config) => config.armature?.requestCapability === true;
|
|
32
39
|
export const handleRequestCapability = (args) => {
|
|
33
40
|
if (!isRecord(args)
|
|
34
41
|
|| typeof args.capability !== "string"
|
package/dist/esm/server.js
CHANGED
|
@@ -5,7 +5,7 @@ import { createAnalyticsRecorder } from "./recorder.js";
|
|
|
5
5
|
import { planToolTelemetry } from "./schema.js";
|
|
6
6
|
import { defaultMcpAnalyticsConfig } from "./emit.js";
|
|
7
7
|
import { deriveToolResultError, isRecord } from "./utils.js";
|
|
8
|
-
import { isRequestCapabilityEnabled } from "./request-capability.js";
|
|
8
|
+
import { isRequestCapabilityEnabled, isRequestCapabilityExplicit } from "./request-capability.js";
|
|
9
9
|
const withAnalyticsStorage = new AsyncLocalStorage();
|
|
10
10
|
let prototypePatchInstalled = false;
|
|
11
11
|
// Mirrors the SDK's `isZodTypeLike`/`isZodRawShapeCompat` checks closely enough
|
|
@@ -158,17 +158,26 @@ export const withMcpAnalytics = (config, createServer) => {
|
|
|
158
158
|
// registers it once without adding telemetry fields or mutating its exact
|
|
159
159
|
// description.
|
|
160
160
|
if (isRequestCapabilityEnabled(config) && !(result instanceof McpServer)) {
|
|
161
|
-
|
|
161
|
+
// Only a hard error when the caller explicitly opted in. A server that is
|
|
162
|
+
// request_capability-on merely by default and doesn't return an McpServer
|
|
163
|
+
// silently skips injection instead of breaking on upgrade.
|
|
164
|
+
if (isRequestCapabilityExplicit(config)) {
|
|
165
|
+
throw new Error("armature.requestCapability requires the server factory to return an McpServer instance.");
|
|
166
|
+
}
|
|
162
167
|
}
|
|
163
168
|
if (isRequestCapabilityEnabled(config) && result instanceof McpServer) {
|
|
164
169
|
try {
|
|
165
170
|
recorder.attachToMcpServer(result);
|
|
166
171
|
}
|
|
167
172
|
catch (error) {
|
|
168
|
-
|
|
173
|
+
const collision = error instanceof Error && /already registered/i.test(error.message);
|
|
174
|
+
// A pre-existing tool of the same name is reserved only when the caller
|
|
175
|
+
// explicitly opted in; on-by-default yields to the customer's tool.
|
|
176
|
+
if (collision && isRequestCapabilityExplicit(config)) {
|
|
169
177
|
throw new Error('Tool name "request_capability" is reserved while armature.requestCapability is enabled.', { cause: error });
|
|
170
178
|
}
|
|
171
|
-
|
|
179
|
+
if (!collision)
|
|
180
|
+
throw error;
|
|
172
181
|
}
|
|
173
182
|
}
|
|
174
183
|
return { result, recorder };
|
|
@@ -25,7 +25,7 @@ import { headerValue, isRecord } from "./utils.js";
|
|
|
25
25
|
// });
|
|
26
26
|
// await analytics.dispatch(name, args, { ctx, ...session.dispatchContext });
|
|
27
27
|
const SESSION_ID_RE = /^mcp_([A-Za-z0-9.-]+)_v_([A-Za-z0-9.-]*)_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
|
|
28
|
-
const SESSION_SEED_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-
|
|
28
|
+
const SESSION_SEED_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
29
29
|
const ANONYMOUS_NAME = "unknown";
|
|
30
30
|
const slugPart = (value, fallback) => {
|
|
31
31
|
const slug = String(value ?? "")
|