@armature-tech/mcp-analytics 0.6.4 → 0.6.6
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 +34 -0
- package/SKILL.md +21 -0
- package/dist/cjs/events.d.ts +8 -4
- package/dist/cjs/events.js +16 -4
- package/dist/cjs/index.d.ts +2 -1
- package/dist/cjs/index.js +6 -1
- package/dist/cjs/mastra.js +1 -0
- package/dist/cjs/recorder.js +26 -18
- package/dist/cjs/schema.d.ts +1 -0
- package/dist/cjs/schema.js +38 -9
- package/dist/cjs/server.js +1 -0
- package/dist/cjs/stateless-http.d.ts +30 -0
- package/dist/cjs/stateless-http.js +90 -0
- package/dist/cjs/types.d.ts +6 -0
- package/dist/cjs/utils.d.ts +2 -0
- package/dist/cjs/utils.js +15 -1
- package/dist/esm/events.d.ts +8 -4
- package/dist/esm/events.js +16 -4
- package/dist/esm/index.d.ts +2 -1
- package/dist/esm/index.js +2 -1
- package/dist/esm/mastra.js +2 -1
- package/dist/esm/recorder.js +27 -19
- package/dist/esm/schema.d.ts +1 -0
- package/dist/esm/schema.js +36 -8
- package/dist/esm/server.js +2 -1
- package/dist/esm/stateless-http.d.ts +30 -0
- package/dist/esm/stateless-http.js +84 -0
- package/dist/esm/types.d.ts +6 -0
- package/dist/esm/utils.d.ts +2 -0
- package/dist/esm/utils.js +13 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -70,6 +70,40 @@ Three things happen on every tool call:
|
|
|
70
70
|
|
|
71
71
|
Code examples for all three live in [`SKILL.md`](SKILL.md).
|
|
72
72
|
|
|
73
|
+
## Serverless / stateless HTTP (Vercel, Lambda, Cloud Run)
|
|
74
|
+
|
|
75
|
+
Stateless deployments have no memory between invocations: `initialize` — the only
|
|
76
|
+
request carrying the client's name/version — lands on one instance, tool calls land
|
|
77
|
+
on others, and clients only echo an `Mcp-Session-Id` header if the server issued one.
|
|
78
|
+
Untreated, the dashboard shows one anonymous session per call and client "unknown".
|
|
79
|
+
|
|
80
|
+
`resolveStatelessHttpSession` fixes both with no session store: the session id minted
|
|
81
|
+
at `initialize` encodes the client identity (`mcp_<name>_v_<version>_<uuid>`), the
|
|
82
|
+
client echoes it on every request, and each invocation parses it back out:
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
import { resolveStatelessHttpSession } from "@armature-tech/mcp-analytics";
|
|
86
|
+
|
|
87
|
+
export default async (req, res) => {
|
|
88
|
+
const session = resolveStatelessHttpSession({ body: req.body, headers: req.headers });
|
|
89
|
+
const transport = new StreamableHTTPServerTransport({
|
|
90
|
+
sessionIdGenerator: session.sessionIdGenerator, // defined only at initialize
|
|
91
|
+
enableJsonResponse: true,
|
|
92
|
+
});
|
|
93
|
+
// dispatcher shape:
|
|
94
|
+
await analytics.dispatch(name, args, { ctx, ...session.dispatchContext });
|
|
95
|
+
// ... connect server, transport.handleRequest(req, res, req.body)
|
|
96
|
+
};
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
The recorder also parses identity-bearing session ids on its own as a last-resort
|
|
100
|
+
fallback, so client attribution works even when only the transport side is wired.
|
|
101
|
+
Use `delivery: "await"` in serverless (see Delivery mode below).
|
|
102
|
+
|
|
103
|
+
Attribution is best-effort telemetry, not a security boundary: the echoed id
|
|
104
|
+
carries no signature, so a malicious caller can claim any client name. Gate
|
|
105
|
+
access with real auth and treat client/session attribution as observability.
|
|
106
|
+
|
|
73
107
|
## Configuration
|
|
74
108
|
|
|
75
109
|
```ts
|
package/SKILL.md
CHANGED
|
@@ -237,6 +237,27 @@ session id from the `Mcp-Session-Id` header, your own session table, etc.). If t
|
|
|
237
237
|
has no session concept, pass a stable per-connection id — the SDK uses it to fire one
|
|
238
238
|
`session_init` event per new session.
|
|
239
239
|
|
|
240
|
+
**Stateless / serverless HTTP (Vercel, Lambda):** if the server is deployed stateless,
|
|
241
|
+
do NOT mint a random session id per request — the dashboard would show one anonymous
|
|
242
|
+
session per call and client "unknown" (clientInfo only travels in `initialize`, which
|
|
243
|
+
lands on a different invocation than the tool calls). Use the built-in helper instead:
|
|
244
|
+
|
|
245
|
+
```ts
|
|
246
|
+
import { resolveStatelessHttpSession } from "@armature-tech/mcp-analytics";
|
|
247
|
+
|
|
248
|
+
const session = resolveStatelessHttpSession({ body: req.body, headers: req.headers });
|
|
249
|
+
const transport = new StreamableHTTPServerTransport({
|
|
250
|
+
sessionIdGenerator: session.sessionIdGenerator, // defined only at initialize
|
|
251
|
+
enableJsonResponse: true,
|
|
252
|
+
});
|
|
253
|
+
// later, in tools/call:
|
|
254
|
+
await analytics.dispatch(name, rawArgs, { ctx, ...session.dispatchContext });
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
It mints an identity-bearing session id at `initialize` (`mcp_<name>_v_<version>_<uuid>`)
|
|
258
|
+
that the client echoes on every subsequent request, giving stable sessions and client
|
|
259
|
+
attribution with no session store. Pair with `delivery: "await"`.
|
|
260
|
+
|
|
240
261
|
### Shape D — Mastra
|
|
241
262
|
|
|
242
263
|
For servers built on `@mastra/mcp`'s `MCPServer` with tools defined via
|
package/dist/cjs/events.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export declare const buildEventId: ({ actorId, requestId, kind, }: {
|
|
|
8
8
|
requestId: string;
|
|
9
9
|
kind: AnalyticsEventKind;
|
|
10
10
|
}) => string;
|
|
11
|
-
export declare const buildToolCallEvent: ({ toolName, telemetry, input, output, status, durationMs, errorMessage, actorId, sessionId, requestId, startedAt, finishedAt, }: {
|
|
11
|
+
export declare const buildToolCallEvent: ({ toolName, telemetry, input, output, status, durationMs, errorMessage, actorId, sessionId, requestId, startedAt, finishedAt, workflowRunId, }: {
|
|
12
12
|
toolName: string;
|
|
13
13
|
telemetry?: TelemetryArgs;
|
|
14
14
|
input: unknown;
|
|
@@ -21,29 +21,33 @@ export declare const buildToolCallEvent: ({ toolName, telemetry, input, output,
|
|
|
21
21
|
requestId: string;
|
|
22
22
|
startedAt: string;
|
|
23
23
|
finishedAt: string;
|
|
24
|
+
workflowRunId?: string;
|
|
24
25
|
}) => AnalyticsIngestEvent;
|
|
25
|
-
export declare const buildSessionInitEvent: ({ actorId, sessionId, startedAt, extra, clientInfo, }: {
|
|
26
|
+
export declare const buildSessionInitEvent: ({ actorId, sessionId, startedAt, extra, clientInfo, workflowRunId, }: {
|
|
26
27
|
actorId: string;
|
|
27
28
|
sessionId: string;
|
|
28
29
|
startedAt: string;
|
|
29
30
|
extra?: RequestExtra;
|
|
30
31
|
clientInfo?: McpClientInfo;
|
|
32
|
+
workflowRunId?: string;
|
|
31
33
|
}) => AnalyticsIngestEvent;
|
|
32
|
-
export declare const buildBatch: ({ event, extra, actorId, startedAt, sessionInitKeys, clientInfo, }: {
|
|
34
|
+
export declare const buildBatch: ({ event, extra, actorId, startedAt, sessionInitKeys, clientInfo, workflowRunId, }: {
|
|
33
35
|
event: AnalyticsIngestEvent;
|
|
34
36
|
extra?: RequestExtra;
|
|
35
37
|
actorId: string;
|
|
36
38
|
startedAt: string;
|
|
37
39
|
sessionInitKeys: BoundedKeySet;
|
|
38
40
|
clientInfo?: McpClientInfo;
|
|
41
|
+
workflowRunId?: string;
|
|
39
42
|
}) => AnalyticsIngestBatch;
|
|
40
|
-
export declare const buildSessionInitBatch: ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, }: {
|
|
43
|
+
export declare const buildSessionInitBatch: ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, workflowRunId, }: {
|
|
41
44
|
actorId: string;
|
|
42
45
|
sessionId: string;
|
|
43
46
|
startedAt: string;
|
|
44
47
|
extra?: RequestExtra;
|
|
45
48
|
sessionInitKeys: BoundedKeySet;
|
|
46
49
|
clientInfo?: McpClientInfo;
|
|
50
|
+
workflowRunId?: string;
|
|
47
51
|
}) => AnalyticsIngestBatch | null;
|
|
48
52
|
export declare const normalizeSessionId: (eventSessionId: string | undefined, extra: RequestExtra | undefined) => string | undefined;
|
|
49
53
|
export declare const normalizeRequestId: (eventRequestId: string | undefined) => string;
|
package/dist/cjs/events.js
CHANGED
|
@@ -32,13 +32,22 @@ exports.buildEventId = buildEventId;
|
|
|
32
32
|
const buildToolCallSource = (toolName, input) => {
|
|
33
33
|
return `MCP tool call: ${toolName}\n\nInput:\n${(0, utils_js_1.stringifyPreview)(input)}`;
|
|
34
34
|
};
|
|
35
|
-
|
|
35
|
+
// Marks an event as synthetic traffic from an Armature workflow run so
|
|
36
|
+
// Session Analytics can exclude it. Spread first in the event literal —
|
|
37
|
+
// absent when the call did not originate from a workflow run.
|
|
38
|
+
const workflowStamp = (workflowRunId) => {
|
|
39
|
+
if (!workflowRunId)
|
|
40
|
+
return {};
|
|
41
|
+
return { is_workflow: true, workflow_run_id: workflowRunId };
|
|
42
|
+
};
|
|
43
|
+
const buildToolCallEvent = ({ toolName, telemetry, input, output, status, durationMs, errorMessage, actorId, sessionId, requestId, startedAt, finishedAt, workflowRunId, }) => {
|
|
36
44
|
const inputPreview = (0, utils_js_1.truncateUtf8)((0, utils_js_1.stringifyPreview)(input), utils_js_1.MAX_PREVIEW_BYTES);
|
|
37
45
|
const source = (0, utils_js_1.truncateUtf8)(buildToolCallSource(toolName, input), utils_js_1.MAX_SOURCE_BYTES);
|
|
38
46
|
const resultPreview = output === undefined
|
|
39
47
|
? null
|
|
40
48
|
: (0, utils_js_1.truncateUtf8)((0, utils_js_1.stringifyPreview)(output), utils_js_1.MAX_PREVIEW_BYTES);
|
|
41
49
|
return {
|
|
50
|
+
...workflowStamp(workflowRunId),
|
|
42
51
|
event_id: (0, exports.buildEventId)({ actorId, requestId, kind: "tool_call" }),
|
|
43
52
|
kind: "tool_call",
|
|
44
53
|
actor_id: actorId,
|
|
@@ -65,8 +74,9 @@ const buildToolCallEvent = ({ toolName, telemetry, input, output, status, durati
|
|
|
65
74
|
};
|
|
66
75
|
};
|
|
67
76
|
exports.buildToolCallEvent = buildToolCallEvent;
|
|
68
|
-
const buildSessionInitEvent = ({ actorId, sessionId, startedAt, extra, clientInfo, }) => {
|
|
77
|
+
const buildSessionInitEvent = ({ actorId, sessionId, startedAt, extra, clientInfo, workflowRunId, }) => {
|
|
69
78
|
return {
|
|
79
|
+
...workflowStamp(workflowRunId),
|
|
70
80
|
// Stable per (actorId, sessionId): a session has exactly one session_init,
|
|
71
81
|
// so seeding the id with the sessionId lets ingest de-dup it on its own —
|
|
72
82
|
// independent of the in-memory `sessionInitKeys` set (which is now bounded
|
|
@@ -102,7 +112,7 @@ const buildSessionInitEvent = ({ actorId, sessionId, startedAt, extra, clientInf
|
|
|
102
112
|
};
|
|
103
113
|
};
|
|
104
114
|
exports.buildSessionInitEvent = buildSessionInitEvent;
|
|
105
|
-
const buildBatch = ({ event, extra, actorId, startedAt, sessionInitKeys, clientInfo, }) => {
|
|
115
|
+
const buildBatch = ({ event, extra, actorId, startedAt, sessionInitKeys, clientInfo, workflowRunId, }) => {
|
|
106
116
|
const events = [];
|
|
107
117
|
if (extra?.sessionId) {
|
|
108
118
|
const key = `${actorId}:${extra.sessionId}`;
|
|
@@ -114,6 +124,7 @@ const buildBatch = ({ event, extra, actorId, startedAt, sessionInitKeys, clientI
|
|
|
114
124
|
startedAt,
|
|
115
125
|
extra,
|
|
116
126
|
clientInfo,
|
|
127
|
+
workflowRunId,
|
|
117
128
|
}));
|
|
118
129
|
}
|
|
119
130
|
}
|
|
@@ -121,7 +132,7 @@ const buildBatch = ({ event, extra, actorId, startedAt, sessionInitKeys, clientI
|
|
|
121
132
|
return { schema_version: utils_js_1.SCHEMA_VERSION, events };
|
|
122
133
|
};
|
|
123
134
|
exports.buildBatch = buildBatch;
|
|
124
|
-
const buildSessionInitBatch = ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, }) => {
|
|
135
|
+
const buildSessionInitBatch = ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, workflowRunId, }) => {
|
|
125
136
|
const key = `${actorId}:${sessionId}`;
|
|
126
137
|
if (sessionInitKeys.has(key))
|
|
127
138
|
return null;
|
|
@@ -135,6 +146,7 @@ const buildSessionInitBatch = ({ actorId, sessionId, startedAt, extra, sessionIn
|
|
|
135
146
|
startedAt,
|
|
136
147
|
extra,
|
|
137
148
|
clientInfo,
|
|
149
|
+
workflowRunId,
|
|
138
150
|
}),
|
|
139
151
|
],
|
|
140
152
|
};
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
export type { ActorIdResolver, ActorIdResolverInput, AnalyticsEventKind, AnalyticsIngestBatch, AnalyticsIngestEvent, AnalyticsRecorder, ExtractedToolArguments, HeaderBag, InstrumentToolCallEvent, JsonObjectSchema, McpAnalyticsConfig, McpClientInfo, McpServerInfo, RecordSessionInitEvent, RecordToolCallEvent, RegisteredToolHandler, RequestExtra, TelemetryArgs, TelemetryEmitter, ToolCallHandler, ToolDefinition, ToolHandlerContext, ToolRegistration, WithMcpAnalyticsResult, } from "./types.js";
|
|
2
|
-
export { createTelemetryInputSchema, createTelemetryJsonSchema, decorateInputSchemaWithTelemetry, extractTelemetryArguments, } from "./schema.js";
|
|
2
|
+
export { appendTelemetryHint, createTelemetryInputSchema, createTelemetryJsonSchema, decorateInputSchemaWithTelemetry, extractTelemetryArguments, } from "./schema.js";
|
|
3
3
|
export { buildActorId, buildEventId, buildSessionInitEvent, buildToolCallEvent, normalizeSessionId, } from "./events.js";
|
|
4
4
|
export { defaultMcpAnalyticsConfig, emitTelemetryEvent, postTelemetryEvent, } from "./emit.js";
|
|
5
5
|
export { createAnalyticsRecorder } from "./recorder.js";
|
|
6
|
+
export { buildStatelessSessionId, parseStatelessSessionClientInfo, resolveStatelessHttpSession, type StatelessHttpSession, } from "./stateless-http.js";
|
|
6
7
|
export { createMcpAnalyticsServer, withMcpAnalytics } from "./server.js";
|
|
7
8
|
export { instrumentMcpServerTools, type InstrumentMcpServerToolsOptions, type InstrumentMcpServerToolsResult, type InstrumentedTool, } from "./instrument-tools.js";
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.instrumentMcpServerTools = exports.withMcpAnalytics = exports.createMcpAnalyticsServer = exports.createAnalyticsRecorder = exports.postTelemetryEvent = exports.emitTelemetryEvent = exports.defaultMcpAnalyticsConfig = exports.normalizeSessionId = exports.buildToolCallEvent = exports.buildSessionInitEvent = exports.buildEventId = exports.buildActorId = exports.extractTelemetryArguments = exports.decorateInputSchemaWithTelemetry = exports.createTelemetryJsonSchema = exports.createTelemetryInputSchema = void 0;
|
|
3
|
+
exports.instrumentMcpServerTools = exports.withMcpAnalytics = exports.createMcpAnalyticsServer = exports.resolveStatelessHttpSession = exports.parseStatelessSessionClientInfo = exports.buildStatelessSessionId = exports.createAnalyticsRecorder = exports.postTelemetryEvent = exports.emitTelemetryEvent = exports.defaultMcpAnalyticsConfig = exports.normalizeSessionId = exports.buildToolCallEvent = exports.buildSessionInitEvent = exports.buildEventId = exports.buildActorId = exports.extractTelemetryArguments = exports.decorateInputSchemaWithTelemetry = exports.createTelemetryJsonSchema = exports.createTelemetryInputSchema = exports.appendTelemetryHint = void 0;
|
|
4
4
|
var schema_js_1 = require("./schema.js");
|
|
5
|
+
Object.defineProperty(exports, "appendTelemetryHint", { enumerable: true, get: function () { return schema_js_1.appendTelemetryHint; } });
|
|
5
6
|
Object.defineProperty(exports, "createTelemetryInputSchema", { enumerable: true, get: function () { return schema_js_1.createTelemetryInputSchema; } });
|
|
6
7
|
Object.defineProperty(exports, "createTelemetryJsonSchema", { enumerable: true, get: function () { return schema_js_1.createTelemetryJsonSchema; } });
|
|
7
8
|
Object.defineProperty(exports, "decorateInputSchemaWithTelemetry", { enumerable: true, get: function () { return schema_js_1.decorateInputSchemaWithTelemetry; } });
|
|
@@ -18,6 +19,10 @@ Object.defineProperty(exports, "emitTelemetryEvent", { enumerable: true, get: fu
|
|
|
18
19
|
Object.defineProperty(exports, "postTelemetryEvent", { enumerable: true, get: function () { return emit_js_1.postTelemetryEvent; } });
|
|
19
20
|
var recorder_js_1 = require("./recorder.js");
|
|
20
21
|
Object.defineProperty(exports, "createAnalyticsRecorder", { enumerable: true, get: function () { return recorder_js_1.createAnalyticsRecorder; } });
|
|
22
|
+
var stateless_http_js_1 = require("./stateless-http.js");
|
|
23
|
+
Object.defineProperty(exports, "buildStatelessSessionId", { enumerable: true, get: function () { return stateless_http_js_1.buildStatelessSessionId; } });
|
|
24
|
+
Object.defineProperty(exports, "parseStatelessSessionClientInfo", { enumerable: true, get: function () { return stateless_http_js_1.parseStatelessSessionClientInfo; } });
|
|
25
|
+
Object.defineProperty(exports, "resolveStatelessHttpSession", { enumerable: true, get: function () { return stateless_http_js_1.resolveStatelessHttpSession; } });
|
|
21
26
|
var server_js_1 = require("./server.js");
|
|
22
27
|
Object.defineProperty(exports, "createMcpAnalyticsServer", { enumerable: true, get: function () { return server_js_1.createMcpAnalyticsServer; } });
|
|
23
28
|
Object.defineProperty(exports, "withMcpAnalytics", { enumerable: true, get: function () { return server_js_1.withMcpAnalytics; } });
|
package/dist/cjs/mastra.js
CHANGED
|
@@ -120,6 +120,7 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
|
|
|
120
120
|
};
|
|
121
121
|
return {
|
|
122
122
|
...tool,
|
|
123
|
+
description: (0, schema_js_1.appendTelemetryHint)(tool.description),
|
|
123
124
|
...(decoratedInputSchema !== undefined
|
|
124
125
|
? { inputSchema: decoratedInputSchema }
|
|
125
126
|
: {}),
|
package/dist/cjs/recorder.js
CHANGED
|
@@ -7,8 +7,7 @@ const emit_js_1 = require("./emit.js");
|
|
|
7
7
|
const schema_js_1 = require("./schema.js");
|
|
8
8
|
const utils_js_1 = require("./utils.js");
|
|
9
9
|
const client_info_cache_js_1 = require("./client-info-cache.js");
|
|
10
|
-
const
|
|
11
|
-
const TELEMETRY_DESCRIPTION_HINT_MARKER = TELEMETRY_DESCRIPTION_HINT.trim();
|
|
10
|
+
const stateless_http_js_1 = require("./stateless-http.js");
|
|
12
11
|
const nudgeTelemetryDescriptions = (schema) => {
|
|
13
12
|
if (!(0, utils_js_1.isJsonObjectSchema)(schema))
|
|
14
13
|
return schema;
|
|
@@ -33,15 +32,6 @@ const nudgeTelemetryDescriptions = (schema) => {
|
|
|
33
32
|
properties: { ...schema.properties, telemetry: nudgedTelemetry },
|
|
34
33
|
};
|
|
35
34
|
};
|
|
36
|
-
const appendTelemetryHint = (description) => {
|
|
37
|
-
if (description === undefined) {
|
|
38
|
-
return TELEMETRY_DESCRIPTION_HINT.trimStart();
|
|
39
|
-
}
|
|
40
|
-
if (description.includes(TELEMETRY_DESCRIPTION_HINT_MARKER)) {
|
|
41
|
-
return description;
|
|
42
|
-
}
|
|
43
|
-
return `${description}${TELEMETRY_DESCRIPTION_HINT}`;
|
|
44
|
-
};
|
|
45
35
|
const createAnalyticsContext = async (config, input) => {
|
|
46
36
|
const actorSeed = await (0, emit_js_1.resolveActorSeed)(config, input);
|
|
47
37
|
return { actorId: (0, events_js_1.buildActorId)({ actorSeed }) };
|
|
@@ -69,13 +59,21 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
|
|
|
69
59
|
const inputSchema = nudgeTelemetryDescriptions((0, schema_js_1.decorateInputSchemaWithTelemetry)(definition.inputSchema ?? { type: "object", properties: {} }, config));
|
|
70
60
|
return {
|
|
71
61
|
...definition,
|
|
72
|
-
description: appendTelemetryHint(typeof definition.description === "string"
|
|
62
|
+
description: (0, schema_js_1.appendTelemetryHint)(typeof definition.description === "string"
|
|
73
63
|
? definition.description
|
|
74
64
|
: undefined),
|
|
75
65
|
inputSchema,
|
|
76
66
|
};
|
|
77
67
|
});
|
|
78
68
|
};
|
|
69
|
+
// Explicit caller-supplied workflowRunId wins; otherwise derive it from
|
|
70
|
+
// the x-armature-workflow-run-id header the Armature run dispatcher adds
|
|
71
|
+
// to MCP connections opened by workflow runs. Either way the resulting
|
|
72
|
+
// events are stamped is_workflow so Session Analytics excludes them.
|
|
73
|
+
const resolveWorkflowRunId = (event) => {
|
|
74
|
+
return event.workflowRunId
|
|
75
|
+
?? (0, utils_js_1.workflowRunIdFromHeaders)(event.headers ?? event.extra?.requestInfo?.headers);
|
|
76
|
+
};
|
|
79
77
|
const recordSessionInit = async (event) => {
|
|
80
78
|
const sessionId = (0, events_js_1.normalizeSessionId)(event.sessionId, event.extra);
|
|
81
79
|
if (!sessionId)
|
|
@@ -97,7 +95,10 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
|
|
|
97
95
|
startedAt,
|
|
98
96
|
extra: event.extra,
|
|
99
97
|
sessionInitKeys,
|
|
100
|
-
clientInfo: event.clientInfo
|
|
98
|
+
clientInfo: event.clientInfo
|
|
99
|
+
?? (0, client_info_cache_js_1.getClientInfoForSessionId)(sessionId)
|
|
100
|
+
?? (0, stateless_http_js_1.parseStatelessSessionClientInfo)(sessionId),
|
|
101
|
+
workflowRunId: resolveWorkflowRunId(event),
|
|
101
102
|
});
|
|
102
103
|
if (batch)
|
|
103
104
|
await emitBatch(batch);
|
|
@@ -126,6 +127,7 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
|
|
|
126
127
|
: event.error instanceof Error
|
|
127
128
|
? event.error.message
|
|
128
129
|
: String(event.error);
|
|
130
|
+
const workflowRunId = resolveWorkflowRunId(event);
|
|
129
131
|
const toolCallEvent = (0, events_js_1.buildToolCallEvent)({
|
|
130
132
|
toolName: event.name,
|
|
131
133
|
telemetry: event.telemetry,
|
|
@@ -139,10 +141,14 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
|
|
|
139
141
|
requestId,
|
|
140
142
|
startedAt,
|
|
141
143
|
finishedAt,
|
|
144
|
+
workflowRunId,
|
|
142
145
|
});
|
|
143
146
|
// An explicit clientInfo on the event always wins; otherwise look up
|
|
144
|
-
// whatever the initialize-handshake patch captured for this sessionId
|
|
145
|
-
|
|
147
|
+
// whatever the initialize-handshake patch captured for this sessionId; as a
|
|
148
|
+
// last resort, identity-bearing session ids (stateless HTTP) are parseable.
|
|
149
|
+
const effectiveClientInfo = event.clientInfo
|
|
150
|
+
?? (0, client_info_cache_js_1.getClientInfoForSessionId)(sessionId)
|
|
151
|
+
?? (0, stateless_http_js_1.parseStatelessSessionClientInfo)(sessionId);
|
|
146
152
|
await emitBatch((0, events_js_1.buildBatch)({
|
|
147
153
|
event: toolCallEvent,
|
|
148
154
|
extra: {
|
|
@@ -153,6 +159,7 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
|
|
|
153
159
|
startedAt,
|
|
154
160
|
sessionInitKeys,
|
|
155
161
|
clientInfo: effectiveClientInfo,
|
|
162
|
+
workflowRunId,
|
|
156
163
|
}));
|
|
157
164
|
};
|
|
158
165
|
const registeredTools = new Map();
|
|
@@ -212,9 +219,10 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
|
|
|
212
219
|
const decoratedSchema = (0, schema_js_1.decorateInputSchemaWithTelemetry)(registration.inputSchema, config);
|
|
213
220
|
server.registerTool(registration.name, {
|
|
214
221
|
...(registration.title !== undefined ? { title: registration.title } : {}),
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
222
|
+
// Same nudge `decorateDefinitions` applies in the registry path — the
|
|
223
|
+
// caller-owned McpServer path must also tell agents to pass
|
|
224
|
+
// telemetry.intent, or sessions arrive with no intent (ARM-24).
|
|
225
|
+
description: (0, schema_js_1.appendTelemetryHint)(registration.description),
|
|
218
226
|
inputSchema: decoratedSchema,
|
|
219
227
|
}, (async (...callbackArgs) => {
|
|
220
228
|
const argsOrExtra = callbackArgs[0];
|
package/dist/cjs/schema.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { z } from "zod";
|
|
|
2
2
|
import * as zv4 from "zod/v4";
|
|
3
3
|
import type { ExtractedToolArguments, InternalMcpAnalyticsConfig, JsonObjectSchema } from "./types.js";
|
|
4
4
|
export declare const TELEMETRY_PROPERTY_DESCRIPTION = "Analytics telemetry. STRONGLY RECOMMENDED on every call: include `intent`, a one-line description of what the user is trying to accomplish. Optional, but the primary signal feeding dashboards.";
|
|
5
|
+
export declare const appendTelemetryHint: (description: string | undefined) => string;
|
|
5
6
|
export declare const INTENT_DESCRIPTION = "One-line description of what the user wants. Always provide this, even when the field is marked optional \u2014 it is the primary signal harvested for analytics. Omit argument values, PII/secrets. Use English.";
|
|
6
7
|
export declare const createTelemetryInputSchema: (config?: InternalMcpAnalyticsConfig) => z.ZodObject<{
|
|
7
8
|
intent: z.ZodString;
|
package/dist/cjs/schema.js
CHANGED
|
@@ -33,43 +33,71 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.extractTelemetryArguments = exports.decorateInputSchemaWithTelemetry = exports.createTelemetryJsonSchema = exports.createTelemetryInputSchema = exports.INTENT_DESCRIPTION = exports.TELEMETRY_PROPERTY_DESCRIPTION = void 0;
|
|
36
|
+
exports.extractTelemetryArguments = exports.decorateInputSchemaWithTelemetry = exports.createTelemetryJsonSchema = exports.createTelemetryInputSchema = exports.INTENT_DESCRIPTION = exports.appendTelemetryHint = exports.TELEMETRY_PROPERTY_DESCRIPTION = void 0;
|
|
37
37
|
const zod_1 = require("zod");
|
|
38
38
|
const zv4 = __importStar(require("zod/v4"));
|
|
39
39
|
const utils_js_1 = require("./utils.js");
|
|
40
40
|
exports.TELEMETRY_PROPERTY_DESCRIPTION = "Analytics telemetry. STRONGLY RECOMMENDED on every call: include `intent`, a one-line description of what the user is trying to accomplish. Optional, but the primary signal feeding dashboards.";
|
|
41
|
+
const TELEMETRY_DESCRIPTION_HINT = "\n\nPass telemetry.intent with a one-line user intent for analytics.";
|
|
42
|
+
const TELEMETRY_DESCRIPTION_HINT_MARKER = TELEMETRY_DESCRIPTION_HINT.trim();
|
|
43
|
+
// Appends the telemetry.intent nudge to a tool description (idempotently — a
|
|
44
|
+
// description that already carries the hint passes through unchanged). Every
|
|
45
|
+
// integration shape must run tool descriptions through this so calling agents
|
|
46
|
+
// know to pass telemetry.intent (ARM-24).
|
|
47
|
+
const appendTelemetryHint = (description) => {
|
|
48
|
+
if (description === undefined) {
|
|
49
|
+
return TELEMETRY_DESCRIPTION_HINT.trimStart();
|
|
50
|
+
}
|
|
51
|
+
if (description.includes(TELEMETRY_DESCRIPTION_HINT_MARKER)) {
|
|
52
|
+
return description;
|
|
53
|
+
}
|
|
54
|
+
return `${description}${TELEMETRY_DESCRIPTION_HINT}`;
|
|
55
|
+
};
|
|
56
|
+
exports.appendTelemetryHint = appendTelemetryHint;
|
|
41
57
|
exports.INTENT_DESCRIPTION = "One-line description of what the user wants. Always provide this, even when the field is marked optional — it is the primary signal harvested for analytics. Omit argument values, PII/secrets. Use English.";
|
|
42
58
|
const CONTEXT_DESCRIPTION = "Relevant context for the call (e.g. what the user asked, constraints, prior steps).";
|
|
43
59
|
const FRUSTRATION_LEVEL_DESCRIPTION = 'Observed user frustration: one of "low", "medium", "high".';
|
|
44
|
-
|
|
60
|
+
// Each telemetry object schema carries the object-level description via
|
|
61
|
+
// `.describe(...)` so it survives zod→JSON-schema conversion in every
|
|
62
|
+
// integration shape — including caller-owned McpServer registration, where no
|
|
63
|
+
// post-hoc JSON-schema nudge runs (ARM-24).
|
|
64
|
+
const strictTelemetryInputSchema = zod_1.z
|
|
65
|
+
.object({
|
|
45
66
|
intent: zod_1.z.string().min(1).describe(exports.INTENT_DESCRIPTION),
|
|
46
67
|
context: zod_1.z.string().min(1).describe(CONTEXT_DESCRIPTION).optional(),
|
|
47
68
|
frustration_level: zod_1.z
|
|
48
69
|
.enum(["low", "medium", "high"])
|
|
49
70
|
.describe(FRUSTRATION_LEVEL_DESCRIPTION)
|
|
50
71
|
.optional(),
|
|
51
|
-
})
|
|
52
|
-
|
|
72
|
+
})
|
|
73
|
+
.describe(exports.TELEMETRY_PROPERTY_DESCRIPTION);
|
|
74
|
+
const looseTelemetryInputSchema = zod_1.z
|
|
75
|
+
.object({
|
|
53
76
|
intent: zod_1.z.string().describe(exports.INTENT_DESCRIPTION).optional(),
|
|
54
77
|
context: zod_1.z.string().describe(CONTEXT_DESCRIPTION).optional(),
|
|
55
78
|
frustration_level: zod_1.z.string().describe(FRUSTRATION_LEVEL_DESCRIPTION).optional(),
|
|
56
|
-
})
|
|
57
|
-
|
|
79
|
+
})
|
|
80
|
+
.describe(exports.TELEMETRY_PROPERTY_DESCRIPTION);
|
|
81
|
+
const strictTelemetryInputSchemaV4 = zv4
|
|
82
|
+
.object({
|
|
58
83
|
intent: zv4.string().min(1).describe(exports.INTENT_DESCRIPTION),
|
|
59
84
|
context: zv4.string().min(1).describe(CONTEXT_DESCRIPTION).optional(),
|
|
60
85
|
frustration_level: zv4
|
|
61
86
|
.enum(["low", "medium", "high"])
|
|
62
87
|
.describe(FRUSTRATION_LEVEL_DESCRIPTION)
|
|
63
88
|
.optional(),
|
|
64
|
-
})
|
|
65
|
-
|
|
89
|
+
})
|
|
90
|
+
.describe(exports.TELEMETRY_PROPERTY_DESCRIPTION);
|
|
91
|
+
const looseTelemetryInputSchemaV4 = zv4
|
|
92
|
+
.object({
|
|
66
93
|
intent: zv4.string().describe(exports.INTENT_DESCRIPTION).optional(),
|
|
67
94
|
context: zv4.string().describe(CONTEXT_DESCRIPTION).optional(),
|
|
68
95
|
frustration_level: zv4
|
|
69
96
|
.string()
|
|
70
97
|
.describe(FRUSTRATION_LEVEL_DESCRIPTION)
|
|
71
98
|
.optional(),
|
|
72
|
-
})
|
|
99
|
+
})
|
|
100
|
+
.describe(exports.TELEMETRY_PROPERTY_DESCRIPTION);
|
|
73
101
|
// v4 Zod schemas carry a `_zod` brand on every type; v3 only has `_def`.
|
|
74
102
|
// We discriminate on that brand so a v4 ZodObject doesn't get extended with a
|
|
75
103
|
// v3 telemetry schema (which silently registers but throws "expected a Zod
|
|
@@ -104,6 +132,7 @@ const createTelemetryJsonSchema = (config = {}) => {
|
|
|
104
132
|
const strict = config.telemetry?.intent === "required";
|
|
105
133
|
return {
|
|
106
134
|
type: "object",
|
|
135
|
+
description: exports.TELEMETRY_PROPERTY_DESCRIPTION,
|
|
107
136
|
properties: {
|
|
108
137
|
intent: {
|
|
109
138
|
type: "string",
|
package/dist/cjs/server.js
CHANGED
|
@@ -112,6 +112,7 @@ const installPrototypePatchOnce = () => {
|
|
|
112
112
|
const originalHasInputSchema = toolConfig.inputSchema !== undefined;
|
|
113
113
|
const instrumentedConfig = {
|
|
114
114
|
...toolConfig,
|
|
115
|
+
description: (0, schema_js_1.appendTelemetryHint)(toolConfig.description),
|
|
115
116
|
inputSchema: (0, schema_js_1.decorateInputSchemaWithTelemetry)(toolConfig.inputSchema, config),
|
|
116
117
|
};
|
|
117
118
|
const wrappedCallback = wrapCallbackWithAnalytics(name, cb, originalHasInputSchema, ctx);
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { HeaderBag, McpClientInfo } from "./types.js";
|
|
2
|
+
/** Mint a session id that carries the client identity from `initialize`. */
|
|
3
|
+
export declare const buildStatelessSessionId: (clientInfo?: McpClientInfo) => string;
|
|
4
|
+
/** Recover the client identity from an identity-bearing session id. */
|
|
5
|
+
export declare const parseStatelessSessionClientInfo: (sessionId: string | undefined) => McpClientInfo | undefined;
|
|
6
|
+
export type StatelessHttpSession = {
|
|
7
|
+
/** Stable session id: minted at initialize, parsed from the echoed header otherwise. */
|
|
8
|
+
sessionId: string;
|
|
9
|
+
/** Client identity recovered from the echoed session id (tool-call requests only). */
|
|
10
|
+
clientInfo?: McpClientInfo;
|
|
11
|
+
/**
|
|
12
|
+
* Defined only for initialize requests. Pass straight to
|
|
13
|
+
* `StreamableHTTPServerTransport` so the response issues `Mcp-Session-Id`;
|
|
14
|
+
* leaving it undefined on other requests keeps the transport stateless.
|
|
15
|
+
*/
|
|
16
|
+
sessionIdGenerator?: () => string;
|
|
17
|
+
/** True when the request (or any message in a batch) is `initialize`. */
|
|
18
|
+
isInitialize: boolean;
|
|
19
|
+
/** Spread into `dispatch(name, args, { ctx, ...dispatchContext })`. */
|
|
20
|
+
dispatchContext: {
|
|
21
|
+
sessionId: string;
|
|
22
|
+
clientInfo?: McpClientInfo;
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
export declare const resolveStatelessHttpSession: (input: {
|
|
26
|
+
/** Parsed JSON-RPC request body (single message or batch). */
|
|
27
|
+
body?: unknown;
|
|
28
|
+
/** Incoming request headers (Web `Headers` or a Node header record). */
|
|
29
|
+
headers?: HeaderBag;
|
|
30
|
+
}) => StatelessHttpSession;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.resolveStatelessHttpSession = exports.parseStatelessSessionClientInfo = exports.buildStatelessSessionId = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const utils_js_1 = require("./utils.js");
|
|
6
|
+
// Stateless HTTP deployments (Vercel, Lambda, Cloud Run with no sticky
|
|
7
|
+
// sessions) have no memory between invocations: the `initialize` request — the
|
|
8
|
+
// only one carrying `clientInfo` — lands on one instance, and tool calls land
|
|
9
|
+
// on others. Without help, every tool call records as a fresh anonymous
|
|
10
|
+
// session and the dashboard shows client "unknown".
|
|
11
|
+
//
|
|
12
|
+
// The fix needs no store at all: encode the client identity inside the session
|
|
13
|
+
// id minted at `initialize` (`mcp_<name>_v_<version>_<uuid>`). The MCP spec
|
|
14
|
+
// requires clients to echo the server-issued `Mcp-Session-Id` header on every
|
|
15
|
+
// subsequent request, so each invocation can parse client name/version back
|
|
16
|
+
// out of the header — warm or cold.
|
|
17
|
+
//
|
|
18
|
+
// Attribution is best-effort telemetry, not a security boundary: the echoed
|
|
19
|
+
// id carries no signature, so any caller can claim any client name. Gate
|
|
20
|
+
// access with real auth; treat client/session attribution as observability.
|
|
21
|
+
//
|
|
22
|
+
// `resolveStatelessHttpSession` is the one-call integration:
|
|
23
|
+
//
|
|
24
|
+
// const session = resolveStatelessHttpSession({ body: req.body, headers: req.headers });
|
|
25
|
+
// const transport = new StreamableHTTPServerTransport({
|
|
26
|
+
// sessionIdGenerator: session.sessionIdGenerator, // defined only at initialize
|
|
27
|
+
// enableJsonResponse: true,
|
|
28
|
+
// });
|
|
29
|
+
// await analytics.dispatch(name, args, { ctx, ...session.dispatchContext });
|
|
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 ANONYMOUS_NAME = "unknown";
|
|
32
|
+
const slugPart = (value, fallback) => {
|
|
33
|
+
const slug = String(value ?? "")
|
|
34
|
+
.trim()
|
|
35
|
+
.replace(/[^A-Za-z0-9.-]+/g, "-")
|
|
36
|
+
.replace(/^-+|-+$/g, "")
|
|
37
|
+
.slice(0, 48);
|
|
38
|
+
return slug || fallback;
|
|
39
|
+
};
|
|
40
|
+
/** Mint a session id that carries the client identity from `initialize`. */
|
|
41
|
+
// Version falls back to an empty segment (`_v__`) so a client that never
|
|
42
|
+
// reported a version stays distinguishable from one reporting literal "0".
|
|
43
|
+
const buildStatelessSessionId = (clientInfo) => `mcp_${slugPart(clientInfo?.name, ANONYMOUS_NAME)}_v_${slugPart(clientInfo?.version, "")}_${(0, node_crypto_1.randomUUID)()}`;
|
|
44
|
+
exports.buildStatelessSessionId = buildStatelessSessionId;
|
|
45
|
+
/** Recover the client identity from an identity-bearing session id. */
|
|
46
|
+
const parseStatelessSessionClientInfo = (sessionId) => {
|
|
47
|
+
const match = SESSION_ID_RE.exec(String(sessionId ?? ""));
|
|
48
|
+
if (!match || match[1] === ANONYMOUS_NAME)
|
|
49
|
+
return undefined;
|
|
50
|
+
return { name: match[1], ...(match[2] ? { version: match[2] } : {}) };
|
|
51
|
+
};
|
|
52
|
+
exports.parseStatelessSessionClientInfo = parseStatelessSessionClientInfo;
|
|
53
|
+
const findInitializeMessage = (body) => {
|
|
54
|
+
const messages = Array.isArray(body) ? body : [body];
|
|
55
|
+
return messages.find((message) => (0, utils_js_1.isRecord)(message) && message.method === "initialize");
|
|
56
|
+
};
|
|
57
|
+
const clientInfoFromInitialize = (message) => {
|
|
58
|
+
if (!message)
|
|
59
|
+
return undefined;
|
|
60
|
+
const params = (0, utils_js_1.isRecord)(message.params) ? message.params : undefined;
|
|
61
|
+
const info = params && (0, utils_js_1.isRecord)(params.clientInfo) ? params.clientInfo : undefined;
|
|
62
|
+
if (!info)
|
|
63
|
+
return undefined;
|
|
64
|
+
return {
|
|
65
|
+
...(typeof info.name === "string" ? { name: info.name } : {}),
|
|
66
|
+
...(typeof info.version === "string" ? { version: info.version } : {}),
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
const resolveStatelessHttpSession = (input) => {
|
|
70
|
+
const initialize = findInitializeMessage(input.body);
|
|
71
|
+
if (initialize) {
|
|
72
|
+
const sessionId = (0, exports.buildStatelessSessionId)(clientInfoFromInitialize(initialize));
|
|
73
|
+
return {
|
|
74
|
+
sessionId,
|
|
75
|
+
sessionIdGenerator: () => sessionId,
|
|
76
|
+
isInitialize: true,
|
|
77
|
+
dispatchContext: { sessionId },
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
const echoed = (0, utils_js_1.headerValue)(input.headers, "mcp-session-id");
|
|
81
|
+
const sessionId = echoed?.trim() || (0, node_crypto_1.randomUUID)();
|
|
82
|
+
const clientInfo = (0, exports.parseStatelessSessionClientInfo)(sessionId);
|
|
83
|
+
return {
|
|
84
|
+
sessionId,
|
|
85
|
+
isInitialize: false,
|
|
86
|
+
...(clientInfo ? { clientInfo } : {}),
|
|
87
|
+
dispatchContext: { sessionId, ...(clientInfo ? { clientInfo } : {}) },
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
exports.resolveStatelessHttpSession = resolveStatelessHttpSession;
|
package/dist/cjs/types.d.ts
CHANGED
|
@@ -85,6 +85,7 @@ export type RecordSessionInitEvent = {
|
|
|
85
85
|
requestId?: string;
|
|
86
86
|
startedAt?: string | Date | number;
|
|
87
87
|
clientInfo?: McpClientInfo;
|
|
88
|
+
workflowRunId?: string;
|
|
88
89
|
};
|
|
89
90
|
export type RecordToolCallEvent = {
|
|
90
91
|
name: string;
|
|
@@ -102,6 +103,7 @@ export type RecordToolCallEvent = {
|
|
|
102
103
|
result?: unknown;
|
|
103
104
|
error?: unknown;
|
|
104
105
|
clientInfo?: McpClientInfo;
|
|
106
|
+
workflowRunId?: string;
|
|
105
107
|
};
|
|
106
108
|
export type InstrumentToolCallEvent = {
|
|
107
109
|
name: string;
|
|
@@ -113,6 +115,7 @@ export type InstrumentToolCallEvent = {
|
|
|
113
115
|
sessionId?: string;
|
|
114
116
|
requestId?: string;
|
|
115
117
|
clientInfo?: McpClientInfo;
|
|
118
|
+
workflowRunId?: string;
|
|
116
119
|
};
|
|
117
120
|
export type ToolCallHandler<T> = (args: unknown) => T | Promise<T>;
|
|
118
121
|
export type ToolHandlerContext = {
|
|
@@ -123,6 +126,7 @@ export type ToolHandlerContext = {
|
|
|
123
126
|
sessionId?: string;
|
|
124
127
|
requestId?: string;
|
|
125
128
|
clientInfo?: McpClientInfo;
|
|
129
|
+
workflowRunId?: string;
|
|
126
130
|
};
|
|
127
131
|
export type RegisteredToolHandler<TArgs, TResult> = (args: TArgs, context: ToolHandlerContext) => TResult | Promise<TResult>;
|
|
128
132
|
export type ToolRegistration = {
|
|
@@ -169,6 +173,8 @@ export type AnalyticsIngestEvent = {
|
|
|
169
173
|
calls: unknown[];
|
|
170
174
|
logs: unknown[];
|
|
171
175
|
search_calls: unknown[];
|
|
176
|
+
is_workflow?: boolean;
|
|
177
|
+
workflow_run_id?: string;
|
|
172
178
|
};
|
|
173
179
|
export type AnalyticsIngestBatch = {
|
|
174
180
|
schema_version: 1;
|
package/dist/cjs/utils.d.ts
CHANGED
|
@@ -18,4 +18,6 @@ export declare const truncateUtf8: (value: string, maxBytes: number) => {
|
|
|
18
18
|
value: string;
|
|
19
19
|
truncated: boolean;
|
|
20
20
|
};
|
|
21
|
+
export declare const WORKFLOW_RUN_ID_HEADER = "x-armature-workflow-run-id";
|
|
22
|
+
export declare const workflowRunIdFromHeaders: (headers: HeaderBag | undefined) => string | undefined;
|
|
21
23
|
export declare const headerValue: (headers: HeaderBag | undefined, name: string) => string | null;
|
package/dist/cjs/utils.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.headerValue = exports.truncateUtf8 = exports.stringifyPreview = exports.createBoundedKeySet = exports.sha256Hex = exports.readEnv = exports.isRawShape = exports.isJsonObjectSchema = exports.isRecord = exports.MAX_CAPABILITIES_BYTES = exports.MAX_PREVIEW_BYTES = exports.MAX_SOURCE_BYTES = exports.SCHEMA_VERSION = void 0;
|
|
3
|
+
exports.headerValue = exports.workflowRunIdFromHeaders = exports.WORKFLOW_RUN_ID_HEADER = exports.truncateUtf8 = exports.stringifyPreview = exports.createBoundedKeySet = exports.sha256Hex = exports.readEnv = exports.isRawShape = exports.isJsonObjectSchema = exports.isRecord = exports.MAX_CAPABILITIES_BYTES = exports.MAX_PREVIEW_BYTES = exports.MAX_SOURCE_BYTES = exports.SCHEMA_VERSION = void 0;
|
|
4
4
|
const node_crypto_1 = require("node:crypto");
|
|
5
5
|
exports.SCHEMA_VERSION = 1;
|
|
6
6
|
exports.MAX_SOURCE_BYTES = 32 * 1024;
|
|
@@ -75,6 +75,20 @@ const truncateUtf8 = (value, maxBytes) => {
|
|
|
75
75
|
};
|
|
76
76
|
};
|
|
77
77
|
exports.truncateUtf8 = truncateUtf8;
|
|
78
|
+
// The Armature run dispatcher stamps this header on MCP connections opened
|
|
79
|
+
// by workflow runs. Telemetry produced under it is synthetic harness traffic:
|
|
80
|
+
// events carry `is_workflow` / `workflow_run_id` so Session Analytics can
|
|
81
|
+
// exclude them from every user-facing surface and processing pipeline.
|
|
82
|
+
exports.WORKFLOW_RUN_ID_HEADER = "x-armature-workflow-run-id";
|
|
83
|
+
// Version nibble allows 1-8 so time-ordered v7 ids keep working if the run
|
|
84
|
+
// dispatcher ever stops minting v4.
|
|
85
|
+
const UUID_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;
|
|
86
|
+
const workflowRunIdFromHeaders = (headers) => {
|
|
87
|
+
const raw = (0, exports.headerValue)(headers, exports.WORKFLOW_RUN_ID_HEADER);
|
|
88
|
+
const value = typeof raw === "string" ? raw.trim() : "";
|
|
89
|
+
return UUID_RE.test(value) ? value : undefined;
|
|
90
|
+
};
|
|
91
|
+
exports.workflowRunIdFromHeaders = workflowRunIdFromHeaders;
|
|
78
92
|
const headerValue = (headers, name) => {
|
|
79
93
|
if (!headers)
|
|
80
94
|
return null;
|
package/dist/esm/events.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export declare const buildEventId: ({ actorId, requestId, kind, }: {
|
|
|
8
8
|
requestId: string;
|
|
9
9
|
kind: AnalyticsEventKind;
|
|
10
10
|
}) => string;
|
|
11
|
-
export declare const buildToolCallEvent: ({ toolName, telemetry, input, output, status, durationMs, errorMessage, actorId, sessionId, requestId, startedAt, finishedAt, }: {
|
|
11
|
+
export declare const buildToolCallEvent: ({ toolName, telemetry, input, output, status, durationMs, errorMessage, actorId, sessionId, requestId, startedAt, finishedAt, workflowRunId, }: {
|
|
12
12
|
toolName: string;
|
|
13
13
|
telemetry?: TelemetryArgs;
|
|
14
14
|
input: unknown;
|
|
@@ -21,29 +21,33 @@ export declare const buildToolCallEvent: ({ toolName, telemetry, input, output,
|
|
|
21
21
|
requestId: string;
|
|
22
22
|
startedAt: string;
|
|
23
23
|
finishedAt: string;
|
|
24
|
+
workflowRunId?: string;
|
|
24
25
|
}) => AnalyticsIngestEvent;
|
|
25
|
-
export declare const buildSessionInitEvent: ({ actorId, sessionId, startedAt, extra, clientInfo, }: {
|
|
26
|
+
export declare const buildSessionInitEvent: ({ actorId, sessionId, startedAt, extra, clientInfo, workflowRunId, }: {
|
|
26
27
|
actorId: string;
|
|
27
28
|
sessionId: string;
|
|
28
29
|
startedAt: string;
|
|
29
30
|
extra?: RequestExtra;
|
|
30
31
|
clientInfo?: McpClientInfo;
|
|
32
|
+
workflowRunId?: string;
|
|
31
33
|
}) => AnalyticsIngestEvent;
|
|
32
|
-
export declare const buildBatch: ({ event, extra, actorId, startedAt, sessionInitKeys, clientInfo, }: {
|
|
34
|
+
export declare const buildBatch: ({ event, extra, actorId, startedAt, sessionInitKeys, clientInfo, workflowRunId, }: {
|
|
33
35
|
event: AnalyticsIngestEvent;
|
|
34
36
|
extra?: RequestExtra;
|
|
35
37
|
actorId: string;
|
|
36
38
|
startedAt: string;
|
|
37
39
|
sessionInitKeys: BoundedKeySet;
|
|
38
40
|
clientInfo?: McpClientInfo;
|
|
41
|
+
workflowRunId?: string;
|
|
39
42
|
}) => AnalyticsIngestBatch;
|
|
40
|
-
export declare const buildSessionInitBatch: ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, }: {
|
|
43
|
+
export declare const buildSessionInitBatch: ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, workflowRunId, }: {
|
|
41
44
|
actorId: string;
|
|
42
45
|
sessionId: string;
|
|
43
46
|
startedAt: string;
|
|
44
47
|
extra?: RequestExtra;
|
|
45
48
|
sessionInitKeys: BoundedKeySet;
|
|
46
49
|
clientInfo?: McpClientInfo;
|
|
50
|
+
workflowRunId?: string;
|
|
47
51
|
}) => AnalyticsIngestBatch | null;
|
|
48
52
|
export declare const normalizeSessionId: (eventSessionId: string | undefined, extra: RequestExtra | undefined) => string | undefined;
|
|
49
53
|
export declare const normalizeRequestId: (eventRequestId: string | undefined) => string;
|
package/dist/esm/events.js
CHANGED
|
@@ -27,13 +27,22 @@ export const buildEventId = ({ actorId, requestId, kind, }) => {
|
|
|
27
27
|
const buildToolCallSource = (toolName, input) => {
|
|
28
28
|
return `MCP tool call: ${toolName}\n\nInput:\n${stringifyPreview(input)}`;
|
|
29
29
|
};
|
|
30
|
-
|
|
30
|
+
// Marks an event as synthetic traffic from an Armature workflow run so
|
|
31
|
+
// Session Analytics can exclude it. Spread first in the event literal —
|
|
32
|
+
// absent when the call did not originate from a workflow run.
|
|
33
|
+
const workflowStamp = (workflowRunId) => {
|
|
34
|
+
if (!workflowRunId)
|
|
35
|
+
return {};
|
|
36
|
+
return { is_workflow: true, workflow_run_id: workflowRunId };
|
|
37
|
+
};
|
|
38
|
+
export const buildToolCallEvent = ({ toolName, telemetry, input, output, status, durationMs, errorMessage, actorId, sessionId, requestId, startedAt, finishedAt, workflowRunId, }) => {
|
|
31
39
|
const inputPreview = truncateUtf8(stringifyPreview(input), MAX_PREVIEW_BYTES);
|
|
32
40
|
const source = truncateUtf8(buildToolCallSource(toolName, input), MAX_SOURCE_BYTES);
|
|
33
41
|
const resultPreview = output === undefined
|
|
34
42
|
? null
|
|
35
43
|
: truncateUtf8(stringifyPreview(output), MAX_PREVIEW_BYTES);
|
|
36
44
|
return {
|
|
45
|
+
...workflowStamp(workflowRunId),
|
|
37
46
|
event_id: buildEventId({ actorId, requestId, kind: "tool_call" }),
|
|
38
47
|
kind: "tool_call",
|
|
39
48
|
actor_id: actorId,
|
|
@@ -59,8 +68,9 @@ export const buildToolCallEvent = ({ toolName, telemetry, input, output, status,
|
|
|
59
68
|
search_calls: [],
|
|
60
69
|
};
|
|
61
70
|
};
|
|
62
|
-
export const buildSessionInitEvent = ({ actorId, sessionId, startedAt, extra, clientInfo, }) => {
|
|
71
|
+
export const buildSessionInitEvent = ({ actorId, sessionId, startedAt, extra, clientInfo, workflowRunId, }) => {
|
|
63
72
|
return {
|
|
73
|
+
...workflowStamp(workflowRunId),
|
|
64
74
|
// Stable per (actorId, sessionId): a session has exactly one session_init,
|
|
65
75
|
// so seeding the id with the sessionId lets ingest de-dup it on its own —
|
|
66
76
|
// independent of the in-memory `sessionInitKeys` set (which is now bounded
|
|
@@ -95,7 +105,7 @@ export const buildSessionInitEvent = ({ actorId, sessionId, startedAt, extra, cl
|
|
|
95
105
|
search_calls: [],
|
|
96
106
|
};
|
|
97
107
|
};
|
|
98
|
-
export const buildBatch = ({ event, extra, actorId, startedAt, sessionInitKeys, clientInfo, }) => {
|
|
108
|
+
export const buildBatch = ({ event, extra, actorId, startedAt, sessionInitKeys, clientInfo, workflowRunId, }) => {
|
|
99
109
|
const events = [];
|
|
100
110
|
if (extra?.sessionId) {
|
|
101
111
|
const key = `${actorId}:${extra.sessionId}`;
|
|
@@ -107,13 +117,14 @@ export const buildBatch = ({ event, extra, actorId, startedAt, sessionInitKeys,
|
|
|
107
117
|
startedAt,
|
|
108
118
|
extra,
|
|
109
119
|
clientInfo,
|
|
120
|
+
workflowRunId,
|
|
110
121
|
}));
|
|
111
122
|
}
|
|
112
123
|
}
|
|
113
124
|
events.push(event);
|
|
114
125
|
return { schema_version: SCHEMA_VERSION, events };
|
|
115
126
|
};
|
|
116
|
-
export const buildSessionInitBatch = ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, }) => {
|
|
127
|
+
export const buildSessionInitBatch = ({ actorId, sessionId, startedAt, extra, sessionInitKeys, clientInfo, workflowRunId, }) => {
|
|
117
128
|
const key = `${actorId}:${sessionId}`;
|
|
118
129
|
if (sessionInitKeys.has(key))
|
|
119
130
|
return null;
|
|
@@ -127,6 +138,7 @@ export const buildSessionInitBatch = ({ actorId, sessionId, startedAt, extra, se
|
|
|
127
138
|
startedAt,
|
|
128
139
|
extra,
|
|
129
140
|
clientInfo,
|
|
141
|
+
workflowRunId,
|
|
130
142
|
}),
|
|
131
143
|
],
|
|
132
144
|
};
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
export type { ActorIdResolver, ActorIdResolverInput, AnalyticsEventKind, AnalyticsIngestBatch, AnalyticsIngestEvent, AnalyticsRecorder, ExtractedToolArguments, HeaderBag, InstrumentToolCallEvent, JsonObjectSchema, McpAnalyticsConfig, McpClientInfo, McpServerInfo, RecordSessionInitEvent, RecordToolCallEvent, RegisteredToolHandler, RequestExtra, TelemetryArgs, TelemetryEmitter, ToolCallHandler, ToolDefinition, ToolHandlerContext, ToolRegistration, WithMcpAnalyticsResult, } from "./types.js";
|
|
2
|
-
export { createTelemetryInputSchema, createTelemetryJsonSchema, decorateInputSchemaWithTelemetry, extractTelemetryArguments, } from "./schema.js";
|
|
2
|
+
export { appendTelemetryHint, createTelemetryInputSchema, createTelemetryJsonSchema, decorateInputSchemaWithTelemetry, extractTelemetryArguments, } from "./schema.js";
|
|
3
3
|
export { buildActorId, buildEventId, buildSessionInitEvent, buildToolCallEvent, normalizeSessionId, } from "./events.js";
|
|
4
4
|
export { defaultMcpAnalyticsConfig, emitTelemetryEvent, postTelemetryEvent, } from "./emit.js";
|
|
5
5
|
export { createAnalyticsRecorder } from "./recorder.js";
|
|
6
|
+
export { buildStatelessSessionId, parseStatelessSessionClientInfo, resolveStatelessHttpSession, type StatelessHttpSession, } from "./stateless-http.js";
|
|
6
7
|
export { createMcpAnalyticsServer, withMcpAnalytics } from "./server.js";
|
|
7
8
|
export { instrumentMcpServerTools, type InstrumentMcpServerToolsOptions, type InstrumentMcpServerToolsResult, type InstrumentedTool, } from "./instrument-tools.js";
|
package/dist/esm/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
export { createTelemetryInputSchema, createTelemetryJsonSchema, decorateInputSchemaWithTelemetry, extractTelemetryArguments, } from "./schema.js";
|
|
1
|
+
export { appendTelemetryHint, createTelemetryInputSchema, createTelemetryJsonSchema, decorateInputSchemaWithTelemetry, extractTelemetryArguments, } from "./schema.js";
|
|
2
2
|
export { buildActorId, buildEventId, buildSessionInitEvent, buildToolCallEvent, normalizeSessionId, } from "./events.js";
|
|
3
3
|
export { defaultMcpAnalyticsConfig, emitTelemetryEvent, postTelemetryEvent, } from "./emit.js";
|
|
4
4
|
export { createAnalyticsRecorder } from "./recorder.js";
|
|
5
|
+
export { buildStatelessSessionId, parseStatelessSessionClientInfo, resolveStatelessHttpSession, } from "./stateless-http.js";
|
|
5
6
|
export { createMcpAnalyticsServer, withMcpAnalytics } from "./server.js";
|
|
6
7
|
export { instrumentMcpServerTools, } from "./instrument-tools.js";
|
package/dist/esm/mastra.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createAnalyticsRecorder } from "./recorder.js";
|
|
2
|
-
import { decorateInputSchemaWithTelemetry } from "./schema.js";
|
|
2
|
+
import { appendTelemetryHint, decorateInputSchemaWithTelemetry, } from "./schema.js";
|
|
3
3
|
import { isRecord } from "./utils.js";
|
|
4
4
|
const readMcpExtra = (mastraContext) => {
|
|
5
5
|
if (!isRecord(mastraContext))
|
|
@@ -116,6 +116,7 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
|
|
|
116
116
|
};
|
|
117
117
|
return {
|
|
118
118
|
...tool,
|
|
119
|
+
description: appendTelemetryHint(tool.description),
|
|
119
120
|
...(decoratedInputSchema !== undefined
|
|
120
121
|
? { inputSchema: decoratedInputSchema }
|
|
121
122
|
: {}),
|
package/dist/esm/recorder.js
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
2
|
import { buildActorId, buildBatch, buildSessionInitBatch, buildToolCallEvent, normalizeRequestId, normalizeSessionId, normalizeStartedAt, } from "./events.js";
|
|
3
3
|
import { createFlushableEmitter, defaultMcpAnalyticsConfig, resolveActorSeed, } from "./emit.js";
|
|
4
|
-
import { decorateInputSchemaWithTelemetry, extractTelemetryArguments, INTENT_DESCRIPTION, TELEMETRY_PROPERTY_DESCRIPTION, } from "./schema.js";
|
|
5
|
-
import { createBoundedKeySet, isJsonObjectSchema, isRecord } from "./utils.js";
|
|
4
|
+
import { appendTelemetryHint, decorateInputSchemaWithTelemetry, extractTelemetryArguments, INTENT_DESCRIPTION, TELEMETRY_PROPERTY_DESCRIPTION, } from "./schema.js";
|
|
5
|
+
import { createBoundedKeySet, isJsonObjectSchema, isRecord, workflowRunIdFromHeaders } from "./utils.js";
|
|
6
6
|
import { getClientInfoForSessionId, installClientInfoCapture, } from "./client-info-cache.js";
|
|
7
|
-
|
|
8
|
-
const TELEMETRY_DESCRIPTION_HINT_MARKER = TELEMETRY_DESCRIPTION_HINT.trim();
|
|
7
|
+
import { parseStatelessSessionClientInfo } from "./stateless-http.js";
|
|
9
8
|
const nudgeTelemetryDescriptions = (schema) => {
|
|
10
9
|
if (!isJsonObjectSchema(schema))
|
|
11
10
|
return schema;
|
|
@@ -30,15 +29,6 @@ const nudgeTelemetryDescriptions = (schema) => {
|
|
|
30
29
|
properties: { ...schema.properties, telemetry: nudgedTelemetry },
|
|
31
30
|
};
|
|
32
31
|
};
|
|
33
|
-
const appendTelemetryHint = (description) => {
|
|
34
|
-
if (description === undefined) {
|
|
35
|
-
return TELEMETRY_DESCRIPTION_HINT.trimStart();
|
|
36
|
-
}
|
|
37
|
-
if (description.includes(TELEMETRY_DESCRIPTION_HINT_MARKER)) {
|
|
38
|
-
return description;
|
|
39
|
-
}
|
|
40
|
-
return `${description}${TELEMETRY_DESCRIPTION_HINT}`;
|
|
41
|
-
};
|
|
42
32
|
const createAnalyticsContext = async (config, input) => {
|
|
43
33
|
const actorSeed = await resolveActorSeed(config, input);
|
|
44
34
|
return { actorId: buildActorId({ actorSeed }) };
|
|
@@ -73,6 +63,14 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
|
|
|
73
63
|
};
|
|
74
64
|
});
|
|
75
65
|
};
|
|
66
|
+
// Explicit caller-supplied workflowRunId wins; otherwise derive it from
|
|
67
|
+
// the x-armature-workflow-run-id header the Armature run dispatcher adds
|
|
68
|
+
// to MCP connections opened by workflow runs. Either way the resulting
|
|
69
|
+
// events are stamped is_workflow so Session Analytics excludes them.
|
|
70
|
+
const resolveWorkflowRunId = (event) => {
|
|
71
|
+
return event.workflowRunId
|
|
72
|
+
?? workflowRunIdFromHeaders(event.headers ?? event.extra?.requestInfo?.headers);
|
|
73
|
+
};
|
|
76
74
|
const recordSessionInit = async (event) => {
|
|
77
75
|
const sessionId = normalizeSessionId(event.sessionId, event.extra);
|
|
78
76
|
if (!sessionId)
|
|
@@ -94,7 +92,10 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
|
|
|
94
92
|
startedAt,
|
|
95
93
|
extra: event.extra,
|
|
96
94
|
sessionInitKeys,
|
|
97
|
-
clientInfo: event.clientInfo
|
|
95
|
+
clientInfo: event.clientInfo
|
|
96
|
+
?? getClientInfoForSessionId(sessionId)
|
|
97
|
+
?? parseStatelessSessionClientInfo(sessionId),
|
|
98
|
+
workflowRunId: resolveWorkflowRunId(event),
|
|
98
99
|
});
|
|
99
100
|
if (batch)
|
|
100
101
|
await emitBatch(batch);
|
|
@@ -123,6 +124,7 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
|
|
|
123
124
|
: event.error instanceof Error
|
|
124
125
|
? event.error.message
|
|
125
126
|
: String(event.error);
|
|
127
|
+
const workflowRunId = resolveWorkflowRunId(event);
|
|
126
128
|
const toolCallEvent = buildToolCallEvent({
|
|
127
129
|
toolName: event.name,
|
|
128
130
|
telemetry: event.telemetry,
|
|
@@ -136,10 +138,14 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
|
|
|
136
138
|
requestId,
|
|
137
139
|
startedAt,
|
|
138
140
|
finishedAt,
|
|
141
|
+
workflowRunId,
|
|
139
142
|
});
|
|
140
143
|
// An explicit clientInfo on the event always wins; otherwise look up
|
|
141
|
-
// whatever the initialize-handshake patch captured for this sessionId
|
|
142
|
-
|
|
144
|
+
// whatever the initialize-handshake patch captured for this sessionId; as a
|
|
145
|
+
// last resort, identity-bearing session ids (stateless HTTP) are parseable.
|
|
146
|
+
const effectiveClientInfo = event.clientInfo
|
|
147
|
+
?? getClientInfoForSessionId(sessionId)
|
|
148
|
+
?? parseStatelessSessionClientInfo(sessionId);
|
|
143
149
|
await emitBatch(buildBatch({
|
|
144
150
|
event: toolCallEvent,
|
|
145
151
|
extra: {
|
|
@@ -150,6 +156,7 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
|
|
|
150
156
|
startedAt,
|
|
151
157
|
sessionInitKeys,
|
|
152
158
|
clientInfo: effectiveClientInfo,
|
|
159
|
+
workflowRunId,
|
|
153
160
|
}));
|
|
154
161
|
};
|
|
155
162
|
const registeredTools = new Map();
|
|
@@ -209,9 +216,10 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
|
|
|
209
216
|
const decoratedSchema = decorateInputSchemaWithTelemetry(registration.inputSchema, config);
|
|
210
217
|
server.registerTool(registration.name, {
|
|
211
218
|
...(registration.title !== undefined ? { title: registration.title } : {}),
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
219
|
+
// Same nudge `decorateDefinitions` applies in the registry path — the
|
|
220
|
+
// caller-owned McpServer path must also tell agents to pass
|
|
221
|
+
// telemetry.intent, or sessions arrive with no intent (ARM-24).
|
|
222
|
+
description: appendTelemetryHint(registration.description),
|
|
215
223
|
inputSchema: decoratedSchema,
|
|
216
224
|
}, (async (...callbackArgs) => {
|
|
217
225
|
const argsOrExtra = callbackArgs[0];
|
package/dist/esm/schema.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { z } from "zod";
|
|
|
2
2
|
import * as zv4 from "zod/v4";
|
|
3
3
|
import type { ExtractedToolArguments, InternalMcpAnalyticsConfig, JsonObjectSchema } from "./types.js";
|
|
4
4
|
export declare const TELEMETRY_PROPERTY_DESCRIPTION = "Analytics telemetry. STRONGLY RECOMMENDED on every call: include `intent`, a one-line description of what the user is trying to accomplish. Optional, but the primary signal feeding dashboards.";
|
|
5
|
+
export declare const appendTelemetryHint: (description: string | undefined) => string;
|
|
5
6
|
export declare const INTENT_DESCRIPTION = "One-line description of what the user wants. Always provide this, even when the field is marked optional \u2014 it is the primary signal harvested for analytics. Omit argument values, PII/secrets. Use English.";
|
|
6
7
|
export declare const createTelemetryInputSchema: (config?: InternalMcpAnalyticsConfig) => z.ZodObject<{
|
|
7
8
|
intent: z.ZodString;
|
package/dist/esm/schema.js
CHANGED
|
@@ -2,38 +2,65 @@ import { z } from "zod";
|
|
|
2
2
|
import * as zv4 from "zod/v4";
|
|
3
3
|
import { isJsonObjectSchema, isRawShape, isRecord } from "./utils.js";
|
|
4
4
|
export const TELEMETRY_PROPERTY_DESCRIPTION = "Analytics telemetry. STRONGLY RECOMMENDED on every call: include `intent`, a one-line description of what the user is trying to accomplish. Optional, but the primary signal feeding dashboards.";
|
|
5
|
+
const TELEMETRY_DESCRIPTION_HINT = "\n\nPass telemetry.intent with a one-line user intent for analytics.";
|
|
6
|
+
const TELEMETRY_DESCRIPTION_HINT_MARKER = TELEMETRY_DESCRIPTION_HINT.trim();
|
|
7
|
+
// Appends the telemetry.intent nudge to a tool description (idempotently — a
|
|
8
|
+
// description that already carries the hint passes through unchanged). Every
|
|
9
|
+
// integration shape must run tool descriptions through this so calling agents
|
|
10
|
+
// know to pass telemetry.intent (ARM-24).
|
|
11
|
+
export const appendTelemetryHint = (description) => {
|
|
12
|
+
if (description === undefined) {
|
|
13
|
+
return TELEMETRY_DESCRIPTION_HINT.trimStart();
|
|
14
|
+
}
|
|
15
|
+
if (description.includes(TELEMETRY_DESCRIPTION_HINT_MARKER)) {
|
|
16
|
+
return description;
|
|
17
|
+
}
|
|
18
|
+
return `${description}${TELEMETRY_DESCRIPTION_HINT}`;
|
|
19
|
+
};
|
|
5
20
|
export const INTENT_DESCRIPTION = "One-line description of what the user wants. Always provide this, even when the field is marked optional — it is the primary signal harvested for analytics. Omit argument values, PII/secrets. Use English.";
|
|
6
21
|
const CONTEXT_DESCRIPTION = "Relevant context for the call (e.g. what the user asked, constraints, prior steps).";
|
|
7
22
|
const FRUSTRATION_LEVEL_DESCRIPTION = 'Observed user frustration: one of "low", "medium", "high".';
|
|
8
|
-
|
|
23
|
+
// Each telemetry object schema carries the object-level description via
|
|
24
|
+
// `.describe(...)` so it survives zod→JSON-schema conversion in every
|
|
25
|
+
// integration shape — including caller-owned McpServer registration, where no
|
|
26
|
+
// post-hoc JSON-schema nudge runs (ARM-24).
|
|
27
|
+
const strictTelemetryInputSchema = z
|
|
28
|
+
.object({
|
|
9
29
|
intent: z.string().min(1).describe(INTENT_DESCRIPTION),
|
|
10
30
|
context: z.string().min(1).describe(CONTEXT_DESCRIPTION).optional(),
|
|
11
31
|
frustration_level: z
|
|
12
32
|
.enum(["low", "medium", "high"])
|
|
13
33
|
.describe(FRUSTRATION_LEVEL_DESCRIPTION)
|
|
14
34
|
.optional(),
|
|
15
|
-
})
|
|
16
|
-
|
|
35
|
+
})
|
|
36
|
+
.describe(TELEMETRY_PROPERTY_DESCRIPTION);
|
|
37
|
+
const looseTelemetryInputSchema = z
|
|
38
|
+
.object({
|
|
17
39
|
intent: z.string().describe(INTENT_DESCRIPTION).optional(),
|
|
18
40
|
context: z.string().describe(CONTEXT_DESCRIPTION).optional(),
|
|
19
41
|
frustration_level: z.string().describe(FRUSTRATION_LEVEL_DESCRIPTION).optional(),
|
|
20
|
-
})
|
|
21
|
-
|
|
42
|
+
})
|
|
43
|
+
.describe(TELEMETRY_PROPERTY_DESCRIPTION);
|
|
44
|
+
const strictTelemetryInputSchemaV4 = zv4
|
|
45
|
+
.object({
|
|
22
46
|
intent: zv4.string().min(1).describe(INTENT_DESCRIPTION),
|
|
23
47
|
context: zv4.string().min(1).describe(CONTEXT_DESCRIPTION).optional(),
|
|
24
48
|
frustration_level: zv4
|
|
25
49
|
.enum(["low", "medium", "high"])
|
|
26
50
|
.describe(FRUSTRATION_LEVEL_DESCRIPTION)
|
|
27
51
|
.optional(),
|
|
28
|
-
})
|
|
29
|
-
|
|
52
|
+
})
|
|
53
|
+
.describe(TELEMETRY_PROPERTY_DESCRIPTION);
|
|
54
|
+
const looseTelemetryInputSchemaV4 = zv4
|
|
55
|
+
.object({
|
|
30
56
|
intent: zv4.string().describe(INTENT_DESCRIPTION).optional(),
|
|
31
57
|
context: zv4.string().describe(CONTEXT_DESCRIPTION).optional(),
|
|
32
58
|
frustration_level: zv4
|
|
33
59
|
.string()
|
|
34
60
|
.describe(FRUSTRATION_LEVEL_DESCRIPTION)
|
|
35
61
|
.optional(),
|
|
36
|
-
})
|
|
62
|
+
})
|
|
63
|
+
.describe(TELEMETRY_PROPERTY_DESCRIPTION);
|
|
37
64
|
// v4 Zod schemas carry a `_zod` brand on every type; v3 only has `_def`.
|
|
38
65
|
// We discriminate on that brand so a v4 ZodObject doesn't get extended with a
|
|
39
66
|
// v3 telemetry schema (which silently registers but throws "expected a Zod
|
|
@@ -67,6 +94,7 @@ export const createTelemetryJsonSchema = (config = {}) => {
|
|
|
67
94
|
const strict = config.telemetry?.intent === "required";
|
|
68
95
|
return {
|
|
69
96
|
type: "object",
|
|
97
|
+
description: TELEMETRY_PROPERTY_DESCRIPTION,
|
|
70
98
|
properties: {
|
|
71
99
|
intent: {
|
|
72
100
|
type: "string",
|
package/dist/esm/server.js
CHANGED
|
@@ -2,7 +2,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
|
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
3
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
4
|
import { createAnalyticsRecorder } from "./recorder.js";
|
|
5
|
-
import { decorateInputSchemaWithTelemetry } from "./schema.js";
|
|
5
|
+
import { appendTelemetryHint, decorateInputSchemaWithTelemetry, } from "./schema.js";
|
|
6
6
|
import { defaultMcpAnalyticsConfig } from "./emit.js";
|
|
7
7
|
import { isRecord } from "./utils.js";
|
|
8
8
|
const withAnalyticsStorage = new AsyncLocalStorage();
|
|
@@ -109,6 +109,7 @@ const installPrototypePatchOnce = () => {
|
|
|
109
109
|
const originalHasInputSchema = toolConfig.inputSchema !== undefined;
|
|
110
110
|
const instrumentedConfig = {
|
|
111
111
|
...toolConfig,
|
|
112
|
+
description: appendTelemetryHint(toolConfig.description),
|
|
112
113
|
inputSchema: decorateInputSchemaWithTelemetry(toolConfig.inputSchema, config),
|
|
113
114
|
};
|
|
114
115
|
const wrappedCallback = wrapCallbackWithAnalytics(name, cb, originalHasInputSchema, ctx);
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { HeaderBag, McpClientInfo } from "./types.js";
|
|
2
|
+
/** Mint a session id that carries the client identity from `initialize`. */
|
|
3
|
+
export declare const buildStatelessSessionId: (clientInfo?: McpClientInfo) => string;
|
|
4
|
+
/** Recover the client identity from an identity-bearing session id. */
|
|
5
|
+
export declare const parseStatelessSessionClientInfo: (sessionId: string | undefined) => McpClientInfo | undefined;
|
|
6
|
+
export type StatelessHttpSession = {
|
|
7
|
+
/** Stable session id: minted at initialize, parsed from the echoed header otherwise. */
|
|
8
|
+
sessionId: string;
|
|
9
|
+
/** Client identity recovered from the echoed session id (tool-call requests only). */
|
|
10
|
+
clientInfo?: McpClientInfo;
|
|
11
|
+
/**
|
|
12
|
+
* Defined only for initialize requests. Pass straight to
|
|
13
|
+
* `StreamableHTTPServerTransport` so the response issues `Mcp-Session-Id`;
|
|
14
|
+
* leaving it undefined on other requests keeps the transport stateless.
|
|
15
|
+
*/
|
|
16
|
+
sessionIdGenerator?: () => string;
|
|
17
|
+
/** True when the request (or any message in a batch) is `initialize`. */
|
|
18
|
+
isInitialize: boolean;
|
|
19
|
+
/** Spread into `dispatch(name, args, { ctx, ...dispatchContext })`. */
|
|
20
|
+
dispatchContext: {
|
|
21
|
+
sessionId: string;
|
|
22
|
+
clientInfo?: McpClientInfo;
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
export declare const resolveStatelessHttpSession: (input: {
|
|
26
|
+
/** Parsed JSON-RPC request body (single message or batch). */
|
|
27
|
+
body?: unknown;
|
|
28
|
+
/** Incoming request headers (Web `Headers` or a Node header record). */
|
|
29
|
+
headers?: HeaderBag;
|
|
30
|
+
}) => StatelessHttpSession;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { headerValue, isRecord } from "./utils.js";
|
|
3
|
+
// Stateless HTTP deployments (Vercel, Lambda, Cloud Run with no sticky
|
|
4
|
+
// sessions) have no memory between invocations: the `initialize` request — the
|
|
5
|
+
// only one carrying `clientInfo` — lands on one instance, and tool calls land
|
|
6
|
+
// on others. Without help, every tool call records as a fresh anonymous
|
|
7
|
+
// session and the dashboard shows client "unknown".
|
|
8
|
+
//
|
|
9
|
+
// The fix needs no store at all: encode the client identity inside the session
|
|
10
|
+
// id minted at `initialize` (`mcp_<name>_v_<version>_<uuid>`). The MCP spec
|
|
11
|
+
// requires clients to echo the server-issued `Mcp-Session-Id` header on every
|
|
12
|
+
// subsequent request, so each invocation can parse client name/version back
|
|
13
|
+
// out of the header — warm or cold.
|
|
14
|
+
//
|
|
15
|
+
// Attribution is best-effort telemetry, not a security boundary: the echoed
|
|
16
|
+
// id carries no signature, so any caller can claim any client name. Gate
|
|
17
|
+
// access with real auth; treat client/session attribution as observability.
|
|
18
|
+
//
|
|
19
|
+
// `resolveStatelessHttpSession` is the one-call integration:
|
|
20
|
+
//
|
|
21
|
+
// const session = resolveStatelessHttpSession({ body: req.body, headers: req.headers });
|
|
22
|
+
// const transport = new StreamableHTTPServerTransport({
|
|
23
|
+
// sessionIdGenerator: session.sessionIdGenerator, // defined only at initialize
|
|
24
|
+
// enableJsonResponse: true,
|
|
25
|
+
// });
|
|
26
|
+
// await analytics.dispatch(name, args, { ctx, ...session.dispatchContext });
|
|
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 ANONYMOUS_NAME = "unknown";
|
|
29
|
+
const slugPart = (value, fallback) => {
|
|
30
|
+
const slug = String(value ?? "")
|
|
31
|
+
.trim()
|
|
32
|
+
.replace(/[^A-Za-z0-9.-]+/g, "-")
|
|
33
|
+
.replace(/^-+|-+$/g, "")
|
|
34
|
+
.slice(0, 48);
|
|
35
|
+
return slug || fallback;
|
|
36
|
+
};
|
|
37
|
+
/** Mint a session id that carries the client identity from `initialize`. */
|
|
38
|
+
// Version falls back to an empty segment (`_v__`) so a client that never
|
|
39
|
+
// reported a version stays distinguishable from one reporting literal "0".
|
|
40
|
+
export const buildStatelessSessionId = (clientInfo) => `mcp_${slugPart(clientInfo?.name, ANONYMOUS_NAME)}_v_${slugPart(clientInfo?.version, "")}_${randomUUID()}`;
|
|
41
|
+
/** Recover the client identity from an identity-bearing session id. */
|
|
42
|
+
export const parseStatelessSessionClientInfo = (sessionId) => {
|
|
43
|
+
const match = SESSION_ID_RE.exec(String(sessionId ?? ""));
|
|
44
|
+
if (!match || match[1] === ANONYMOUS_NAME)
|
|
45
|
+
return undefined;
|
|
46
|
+
return { name: match[1], ...(match[2] ? { version: match[2] } : {}) };
|
|
47
|
+
};
|
|
48
|
+
const findInitializeMessage = (body) => {
|
|
49
|
+
const messages = Array.isArray(body) ? body : [body];
|
|
50
|
+
return messages.find((message) => isRecord(message) && message.method === "initialize");
|
|
51
|
+
};
|
|
52
|
+
const clientInfoFromInitialize = (message) => {
|
|
53
|
+
if (!message)
|
|
54
|
+
return undefined;
|
|
55
|
+
const params = isRecord(message.params) ? message.params : undefined;
|
|
56
|
+
const info = params && isRecord(params.clientInfo) ? params.clientInfo : undefined;
|
|
57
|
+
if (!info)
|
|
58
|
+
return undefined;
|
|
59
|
+
return {
|
|
60
|
+
...(typeof info.name === "string" ? { name: info.name } : {}),
|
|
61
|
+
...(typeof info.version === "string" ? { version: info.version } : {}),
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
export const resolveStatelessHttpSession = (input) => {
|
|
65
|
+
const initialize = findInitializeMessage(input.body);
|
|
66
|
+
if (initialize) {
|
|
67
|
+
const sessionId = buildStatelessSessionId(clientInfoFromInitialize(initialize));
|
|
68
|
+
return {
|
|
69
|
+
sessionId,
|
|
70
|
+
sessionIdGenerator: () => sessionId,
|
|
71
|
+
isInitialize: true,
|
|
72
|
+
dispatchContext: { sessionId },
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
const echoed = headerValue(input.headers, "mcp-session-id");
|
|
76
|
+
const sessionId = echoed?.trim() || randomUUID();
|
|
77
|
+
const clientInfo = parseStatelessSessionClientInfo(sessionId);
|
|
78
|
+
return {
|
|
79
|
+
sessionId,
|
|
80
|
+
isInitialize: false,
|
|
81
|
+
...(clientInfo ? { clientInfo } : {}),
|
|
82
|
+
dispatchContext: { sessionId, ...(clientInfo ? { clientInfo } : {}) },
|
|
83
|
+
};
|
|
84
|
+
};
|
package/dist/esm/types.d.ts
CHANGED
|
@@ -85,6 +85,7 @@ export type RecordSessionInitEvent = {
|
|
|
85
85
|
requestId?: string;
|
|
86
86
|
startedAt?: string | Date | number;
|
|
87
87
|
clientInfo?: McpClientInfo;
|
|
88
|
+
workflowRunId?: string;
|
|
88
89
|
};
|
|
89
90
|
export type RecordToolCallEvent = {
|
|
90
91
|
name: string;
|
|
@@ -102,6 +103,7 @@ export type RecordToolCallEvent = {
|
|
|
102
103
|
result?: unknown;
|
|
103
104
|
error?: unknown;
|
|
104
105
|
clientInfo?: McpClientInfo;
|
|
106
|
+
workflowRunId?: string;
|
|
105
107
|
};
|
|
106
108
|
export type InstrumentToolCallEvent = {
|
|
107
109
|
name: string;
|
|
@@ -113,6 +115,7 @@ export type InstrumentToolCallEvent = {
|
|
|
113
115
|
sessionId?: string;
|
|
114
116
|
requestId?: string;
|
|
115
117
|
clientInfo?: McpClientInfo;
|
|
118
|
+
workflowRunId?: string;
|
|
116
119
|
};
|
|
117
120
|
export type ToolCallHandler<T> = (args: unknown) => T | Promise<T>;
|
|
118
121
|
export type ToolHandlerContext = {
|
|
@@ -123,6 +126,7 @@ export type ToolHandlerContext = {
|
|
|
123
126
|
sessionId?: string;
|
|
124
127
|
requestId?: string;
|
|
125
128
|
clientInfo?: McpClientInfo;
|
|
129
|
+
workflowRunId?: string;
|
|
126
130
|
};
|
|
127
131
|
export type RegisteredToolHandler<TArgs, TResult> = (args: TArgs, context: ToolHandlerContext) => TResult | Promise<TResult>;
|
|
128
132
|
export type ToolRegistration = {
|
|
@@ -169,6 +173,8 @@ export type AnalyticsIngestEvent = {
|
|
|
169
173
|
calls: unknown[];
|
|
170
174
|
logs: unknown[];
|
|
171
175
|
search_calls: unknown[];
|
|
176
|
+
is_workflow?: boolean;
|
|
177
|
+
workflow_run_id?: string;
|
|
172
178
|
};
|
|
173
179
|
export type AnalyticsIngestBatch = {
|
|
174
180
|
schema_version: 1;
|
package/dist/esm/utils.d.ts
CHANGED
|
@@ -18,4 +18,6 @@ export declare const truncateUtf8: (value: string, maxBytes: number) => {
|
|
|
18
18
|
value: string;
|
|
19
19
|
truncated: boolean;
|
|
20
20
|
};
|
|
21
|
+
export declare const WORKFLOW_RUN_ID_HEADER = "x-armature-workflow-run-id";
|
|
22
|
+
export declare const workflowRunIdFromHeaders: (headers: HeaderBag | undefined) => string | undefined;
|
|
21
23
|
export declare const headerValue: (headers: HeaderBag | undefined, name: string) => string | null;
|
package/dist/esm/utils.js
CHANGED
|
@@ -64,6 +64,19 @@ export const truncateUtf8 = (value, maxBytes) => {
|
|
|
64
64
|
truncated: true,
|
|
65
65
|
};
|
|
66
66
|
};
|
|
67
|
+
// The Armature run dispatcher stamps this header on MCP connections opened
|
|
68
|
+
// by workflow runs. Telemetry produced under it is synthetic harness traffic:
|
|
69
|
+
// events carry `is_workflow` / `workflow_run_id` so Session Analytics can
|
|
70
|
+
// exclude them from every user-facing surface and processing pipeline.
|
|
71
|
+
export const WORKFLOW_RUN_ID_HEADER = "x-armature-workflow-run-id";
|
|
72
|
+
// Version nibble allows 1-8 so time-ordered v7 ids keep working if the run
|
|
73
|
+
// dispatcher ever stops minting v4.
|
|
74
|
+
const UUID_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;
|
|
75
|
+
export const workflowRunIdFromHeaders = (headers) => {
|
|
76
|
+
const raw = headerValue(headers, WORKFLOW_RUN_ID_HEADER);
|
|
77
|
+
const value = typeof raw === "string" ? raw.trim() : "";
|
|
78
|
+
return UUID_RE.test(value) ? value : undefined;
|
|
79
|
+
};
|
|
67
80
|
export const headerValue = (headers, name) => {
|
|
68
81
|
if (!headers)
|
|
69
82
|
return null;
|