@armature-tech/mcp-analytics 0.6.5 → 0.6.7
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/index.d.ts +2 -1
- package/dist/cjs/index.js +6 -1
- package/dist/cjs/mastra.js +2 -1
- package/dist/cjs/recorder.js +21 -20
- package/dist/cjs/schema.d.ts +1 -0
- package/dist/cjs/schema.js +38 -9
- package/dist/cjs/server.js +8 -2
- package/dist/cjs/stateless-http.d.ts +30 -0
- package/dist/cjs/stateless-http.js +90 -0
- package/dist/cjs/utils.d.ts +1 -0
- package/dist/cjs/utils.js +26 -1
- package/dist/esm/index.d.ts +2 -1
- package/dist/esm/index.js +2 -1
- package/dist/esm/mastra.js +3 -2
- package/dist/esm/recorder.js +22 -21
- package/dist/esm/schema.d.ts +1 -0
- package/dist/esm/schema.js +36 -8
- package/dist/esm/server.js +10 -4
- package/dist/esm/stateless-http.d.ts +30 -0
- package/dist/esm/stateless-http.js +84 -0
- package/dist/esm/utils.d.ts +1 -0
- package/dist/esm/utils.js +24 -0
- package/package.json +4 -4
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/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
|
: {}),
|
|
@@ -127,7 +128,7 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
|
|
|
127
128
|
};
|
|
128
129
|
};
|
|
129
130
|
// Generic over the input map so the return value keeps the customer's exact
|
|
130
|
-
// tool-map type (e.g. `Record<string,
|
|
131
|
+
// tool-map type (e.g. `Record<string, HostTool>`). Without this, every Mastra
|
|
131
132
|
// caller had to do `wrapMastraTools(myTools as unknown as MastraToolMap, ...) as
|
|
132
133
|
// unknown as typeof myTools` because `MCPServer({ tools })` wants the narrower
|
|
133
134
|
// type back. The `T extends MastraToolMap` constraint lets us still operate on
|
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,7 +59,7 @@ 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,
|
|
@@ -105,7 +95,9 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
|
|
|
105
95
|
startedAt,
|
|
106
96
|
extra: event.extra,
|
|
107
97
|
sessionInitKeys,
|
|
108
|
-
clientInfo: event.clientInfo
|
|
98
|
+
clientInfo: event.clientInfo
|
|
99
|
+
?? (0, client_info_cache_js_1.getClientInfoForSessionId)(sessionId)
|
|
100
|
+
?? (0, stateless_http_js_1.parseStatelessSessionClientInfo)(sessionId),
|
|
109
101
|
workflowRunId: resolveWorkflowRunId(event),
|
|
110
102
|
});
|
|
111
103
|
if (batch)
|
|
@@ -152,8 +144,11 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
|
|
|
152
144
|
workflowRunId,
|
|
153
145
|
});
|
|
154
146
|
// An explicit clientInfo on the event always wins; otherwise look up
|
|
155
|
-
// whatever the initialize-handshake patch captured for this sessionId
|
|
156
|
-
|
|
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);
|
|
157
152
|
await emitBatch((0, events_js_1.buildBatch)({
|
|
158
153
|
event: toolCallEvent,
|
|
159
154
|
extra: {
|
|
@@ -174,14 +169,19 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
|
|
|
174
169
|
const startedAt = new Date(startedAtMs).toISOString();
|
|
175
170
|
try {
|
|
176
171
|
const result = await handler(args);
|
|
172
|
+
// A handler that returns an MCP error result (`isError: true`) instead of
|
|
173
|
+
// throwing is still a failed call; record it as such while returning the
|
|
174
|
+
// original result to the caller untouched.
|
|
175
|
+
const resultError = (0, utils_js_1.deriveToolResultError)(result);
|
|
177
176
|
await recordToolCall({
|
|
178
177
|
...event,
|
|
179
178
|
args,
|
|
180
179
|
telemetry,
|
|
181
180
|
startedAt,
|
|
182
181
|
durationMs: Date.now() - startedAtMs,
|
|
183
|
-
|
|
184
|
-
|
|
182
|
+
...(resultError === undefined
|
|
183
|
+
? { status: "ok", result }
|
|
184
|
+
: { status: "error", result, error: resultError }),
|
|
185
185
|
});
|
|
186
186
|
return result;
|
|
187
187
|
}
|
|
@@ -224,9 +224,10 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
|
|
|
224
224
|
const decoratedSchema = (0, schema_js_1.decorateInputSchemaWithTelemetry)(registration.inputSchema, config);
|
|
225
225
|
server.registerTool(registration.name, {
|
|
226
226
|
...(registration.title !== undefined ? { title: registration.title } : {}),
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
227
|
+
// Same nudge `decorateDefinitions` applies in the registry path — the
|
|
228
|
+
// caller-owned McpServer path must also tell agents to pass
|
|
229
|
+
// telemetry.intent, or sessions arrive with no intent (ARM-24).
|
|
230
|
+
description: (0, schema_js_1.appendTelemetryHint)(registration.description),
|
|
230
231
|
inputSchema: decoratedSchema,
|
|
231
232
|
}, (async (...callbackArgs) => {
|
|
232
233
|
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
|
@@ -67,6 +67,10 @@ const wrapCallbackWithAnalytics = (name, cb, originalHasInputSchema, ctx) => {
|
|
|
67
67
|
const output = originalHasInputSchema
|
|
68
68
|
? await cb(args, maybeExtra)
|
|
69
69
|
: await cb(maybeExtra ?? argsOrExtra);
|
|
70
|
+
// A returned MCP error result (`isError: true`) is a failed call even
|
|
71
|
+
// though the callback resolved; record it as an error while returning the
|
|
72
|
+
// original output to the caller untouched.
|
|
73
|
+
const resultError = (0, utils_js_1.deriveToolResultError)(output);
|
|
70
74
|
await recorder.recordToolCall({
|
|
71
75
|
name,
|
|
72
76
|
args,
|
|
@@ -75,8 +79,9 @@ const wrapCallbackWithAnalytics = (name, cb, originalHasInputSchema, ctx) => {
|
|
|
75
79
|
requestId,
|
|
76
80
|
startedAt,
|
|
77
81
|
durationMs: Date.now() - startedAtMs,
|
|
78
|
-
|
|
79
|
-
|
|
82
|
+
...(resultError === undefined
|
|
83
|
+
? { status: "ok", result: output }
|
|
84
|
+
: { status: "error", result: output, error: resultError }),
|
|
80
85
|
});
|
|
81
86
|
return output;
|
|
82
87
|
}
|
|
@@ -112,6 +117,7 @@ const installPrototypePatchOnce = () => {
|
|
|
112
117
|
const originalHasInputSchema = toolConfig.inputSchema !== undefined;
|
|
113
118
|
const instrumentedConfig = {
|
|
114
119
|
...toolConfig,
|
|
120
|
+
description: (0, schema_js_1.appendTelemetryHint)(toolConfig.description),
|
|
115
121
|
inputSchema: (0, schema_js_1.decorateInputSchemaWithTelemetry)(toolConfig.inputSchema, config),
|
|
116
122
|
};
|
|
117
123
|
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/utils.d.ts
CHANGED
|
@@ -13,6 +13,7 @@ export type BoundedKeySet = {
|
|
|
13
13
|
add: (key: string) => void;
|
|
14
14
|
};
|
|
15
15
|
export declare const createBoundedKeySet: (maxEntries: number) => BoundedKeySet;
|
|
16
|
+
export declare const deriveToolResultError: (result: unknown) => string | undefined;
|
|
16
17
|
export declare const stringifyPreview: (value: unknown) => string;
|
|
17
18
|
export declare const truncateUtf8: (value: string, maxBytes: number) => {
|
|
18
19
|
value: string;
|
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.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;
|
|
3
|
+
exports.headerValue = exports.workflowRunIdFromHeaders = exports.WORKFLOW_RUN_ID_HEADER = exports.truncateUtf8 = exports.stringifyPreview = exports.deriveToolResultError = 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;
|
|
@@ -54,6 +54,31 @@ const createBoundedKeySet = (maxEntries) => {
|
|
|
54
54
|
};
|
|
55
55
|
};
|
|
56
56
|
exports.createBoundedKeySet = createBoundedKeySet;
|
|
57
|
+
// Per MCP convention, a server signals a recoverable/upstream failure by
|
|
58
|
+
// returning a normal CallToolResult with `isError: true` (so the agent can see
|
|
59
|
+
// and retry it) rather than throwing. The handler therefore resolves rather
|
|
60
|
+
// than rejects, so without this check those failures would be recorded as
|
|
61
|
+
// successes. Returns a human-readable error message when `result` is such an
|
|
62
|
+
// error result, or undefined for a successful (or non-result-shaped) value.
|
|
63
|
+
// Defensive about shape: a non-object, missing `content`, or absent text all
|
|
64
|
+
// fall back gracefully and never throw.
|
|
65
|
+
const deriveToolResultError = (result) => {
|
|
66
|
+
if (!(0, exports.isRecord)(result) || result.isError !== true)
|
|
67
|
+
return undefined;
|
|
68
|
+
const content = result.content;
|
|
69
|
+
if (Array.isArray(content)) {
|
|
70
|
+
for (const item of content) {
|
|
71
|
+
if ((0, exports.isRecord)(item) &&
|
|
72
|
+
item.type === "text" &&
|
|
73
|
+
typeof item.text === "string" &&
|
|
74
|
+
item.text.trim().length > 0) {
|
|
75
|
+
return item.text;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return "tool returned isError";
|
|
80
|
+
};
|
|
81
|
+
exports.deriveToolResultError = deriveToolResultError;
|
|
57
82
|
const stringifyPreview = (value) => {
|
|
58
83
|
if (value === undefined)
|
|
59
84
|
return "undefined";
|
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
|
: {}),
|
|
@@ -123,7 +124,7 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
|
|
|
123
124
|
};
|
|
124
125
|
};
|
|
125
126
|
// Generic over the input map so the return value keeps the customer's exact
|
|
126
|
-
// tool-map type (e.g. `Record<string,
|
|
127
|
+
// tool-map type (e.g. `Record<string, HostTool>`). Without this, every Mastra
|
|
127
128
|
// caller had to do `wrapMastraTools(myTools as unknown as MastraToolMap, ...) as
|
|
128
129
|
// unknown as typeof myTools` because `MCPServer({ tools })` wants the narrower
|
|
129
130
|
// type back. The `T extends MastraToolMap` constraint lets us still operate on
|
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, workflowRunIdFromHeaders } from "./utils.js";
|
|
4
|
+
import { appendTelemetryHint, decorateInputSchemaWithTelemetry, extractTelemetryArguments, INTENT_DESCRIPTION, TELEMETRY_PROPERTY_DESCRIPTION, } from "./schema.js";
|
|
5
|
+
import { createBoundedKeySet, deriveToolResultError, 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 }) };
|
|
@@ -102,7 +92,9 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
|
|
|
102
92
|
startedAt,
|
|
103
93
|
extra: event.extra,
|
|
104
94
|
sessionInitKeys,
|
|
105
|
-
clientInfo: event.clientInfo
|
|
95
|
+
clientInfo: event.clientInfo
|
|
96
|
+
?? getClientInfoForSessionId(sessionId)
|
|
97
|
+
?? parseStatelessSessionClientInfo(sessionId),
|
|
106
98
|
workflowRunId: resolveWorkflowRunId(event),
|
|
107
99
|
});
|
|
108
100
|
if (batch)
|
|
@@ -149,8 +141,11 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
|
|
|
149
141
|
workflowRunId,
|
|
150
142
|
});
|
|
151
143
|
// An explicit clientInfo on the event always wins; otherwise look up
|
|
152
|
-
// whatever the initialize-handshake patch captured for this sessionId
|
|
153
|
-
|
|
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);
|
|
154
149
|
await emitBatch(buildBatch({
|
|
155
150
|
event: toolCallEvent,
|
|
156
151
|
extra: {
|
|
@@ -171,14 +166,19 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
|
|
|
171
166
|
const startedAt = new Date(startedAtMs).toISOString();
|
|
172
167
|
try {
|
|
173
168
|
const result = await handler(args);
|
|
169
|
+
// A handler that returns an MCP error result (`isError: true`) instead of
|
|
170
|
+
// throwing is still a failed call; record it as such while returning the
|
|
171
|
+
// original result to the caller untouched.
|
|
172
|
+
const resultError = deriveToolResultError(result);
|
|
174
173
|
await recordToolCall({
|
|
175
174
|
...event,
|
|
176
175
|
args,
|
|
177
176
|
telemetry,
|
|
178
177
|
startedAt,
|
|
179
178
|
durationMs: Date.now() - startedAtMs,
|
|
180
|
-
|
|
181
|
-
|
|
179
|
+
...(resultError === undefined
|
|
180
|
+
? { status: "ok", result }
|
|
181
|
+
: { status: "error", result, error: resultError }),
|
|
182
182
|
});
|
|
183
183
|
return result;
|
|
184
184
|
}
|
|
@@ -221,9 +221,10 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
|
|
|
221
221
|
const decoratedSchema = decorateInputSchemaWithTelemetry(registration.inputSchema, config);
|
|
222
222
|
server.registerTool(registration.name, {
|
|
223
223
|
...(registration.title !== undefined ? { title: registration.title } : {}),
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
224
|
+
// Same nudge `decorateDefinitions` applies in the registry path — the
|
|
225
|
+
// caller-owned McpServer path must also tell agents to pass
|
|
226
|
+
// telemetry.intent, or sessions arrive with no intent (ARM-24).
|
|
227
|
+
description: appendTelemetryHint(registration.description),
|
|
227
228
|
inputSchema: decoratedSchema,
|
|
228
229
|
}, (async (...callbackArgs) => {
|
|
229
230
|
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,9 +2,9 @@ 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
|
-
import { isRecord } from "./utils.js";
|
|
7
|
+
import { deriveToolResultError, isRecord } from "./utils.js";
|
|
8
8
|
const withAnalyticsStorage = new AsyncLocalStorage();
|
|
9
9
|
let prototypePatchInstalled = false;
|
|
10
10
|
// Mirrors the SDK's `isZodTypeLike`/`isZodRawShapeCompat` checks closely enough
|
|
@@ -64,6 +64,10 @@ const wrapCallbackWithAnalytics = (name, cb, originalHasInputSchema, ctx) => {
|
|
|
64
64
|
const output = originalHasInputSchema
|
|
65
65
|
? await cb(args, maybeExtra)
|
|
66
66
|
: await cb(maybeExtra ?? argsOrExtra);
|
|
67
|
+
// A returned MCP error result (`isError: true`) is a failed call even
|
|
68
|
+
// though the callback resolved; record it as an error while returning the
|
|
69
|
+
// original output to the caller untouched.
|
|
70
|
+
const resultError = deriveToolResultError(output);
|
|
67
71
|
await recorder.recordToolCall({
|
|
68
72
|
name,
|
|
69
73
|
args,
|
|
@@ -72,8 +76,9 @@ const wrapCallbackWithAnalytics = (name, cb, originalHasInputSchema, ctx) => {
|
|
|
72
76
|
requestId,
|
|
73
77
|
startedAt,
|
|
74
78
|
durationMs: Date.now() - startedAtMs,
|
|
75
|
-
|
|
76
|
-
|
|
79
|
+
...(resultError === undefined
|
|
80
|
+
? { status: "ok", result: output }
|
|
81
|
+
: { status: "error", result: output, error: resultError }),
|
|
77
82
|
});
|
|
78
83
|
return output;
|
|
79
84
|
}
|
|
@@ -109,6 +114,7 @@ const installPrototypePatchOnce = () => {
|
|
|
109
114
|
const originalHasInputSchema = toolConfig.inputSchema !== undefined;
|
|
110
115
|
const instrumentedConfig = {
|
|
111
116
|
...toolConfig,
|
|
117
|
+
description: appendTelemetryHint(toolConfig.description),
|
|
112
118
|
inputSchema: decorateInputSchemaWithTelemetry(toolConfig.inputSchema, config),
|
|
113
119
|
};
|
|
114
120
|
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/utils.d.ts
CHANGED
|
@@ -13,6 +13,7 @@ export type BoundedKeySet = {
|
|
|
13
13
|
add: (key: string) => void;
|
|
14
14
|
};
|
|
15
15
|
export declare const createBoundedKeySet: (maxEntries: number) => BoundedKeySet;
|
|
16
|
+
export declare const deriveToolResultError: (result: unknown) => string | undefined;
|
|
16
17
|
export declare const stringifyPreview: (value: unknown) => string;
|
|
17
18
|
export declare const truncateUtf8: (value: string, maxBytes: number) => {
|
|
18
19
|
value: string;
|
package/dist/esm/utils.js
CHANGED
|
@@ -45,6 +45,30 @@ export const createBoundedKeySet = (maxEntries) => {
|
|
|
45
45
|
},
|
|
46
46
|
};
|
|
47
47
|
};
|
|
48
|
+
// Per MCP convention, a server signals a recoverable/upstream failure by
|
|
49
|
+
// returning a normal CallToolResult with `isError: true` (so the agent can see
|
|
50
|
+
// and retry it) rather than throwing. The handler therefore resolves rather
|
|
51
|
+
// than rejects, so without this check those failures would be recorded as
|
|
52
|
+
// successes. Returns a human-readable error message when `result` is such an
|
|
53
|
+
// error result, or undefined for a successful (or non-result-shaped) value.
|
|
54
|
+
// Defensive about shape: a non-object, missing `content`, or absent text all
|
|
55
|
+
// fall back gracefully and never throw.
|
|
56
|
+
export const deriveToolResultError = (result) => {
|
|
57
|
+
if (!isRecord(result) || result.isError !== true)
|
|
58
|
+
return undefined;
|
|
59
|
+
const content = result.content;
|
|
60
|
+
if (Array.isArray(content)) {
|
|
61
|
+
for (const item of content) {
|
|
62
|
+
if (isRecord(item) &&
|
|
63
|
+
item.type === "text" &&
|
|
64
|
+
typeof item.text === "string" &&
|
|
65
|
+
item.text.trim().length > 0) {
|
|
66
|
+
return item.text;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return "tool returned isError";
|
|
71
|
+
};
|
|
48
72
|
export const stringifyPreview = (value) => {
|
|
49
73
|
if (value === undefined)
|
|
50
74
|
return "undefined";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@armature-tech/mcp-analytics",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.7",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "MCP analytics wrapper SDK that instruments MCP tool declarations with telemetry.",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -56,8 +56,8 @@
|
|
|
56
56
|
],
|
|
57
57
|
"scripts": {
|
|
58
58
|
"dev:armature": "tsx experimental/mock-env/mock-armature-server.ts",
|
|
59
|
-
"dev:instrumented-server": "tsx experimental/mock-env/instrumented-mock-
|
|
60
|
-
"dev:server": "tsx experimental/mock-env/mock-
|
|
59
|
+
"dev:instrumented-server": "tsx experimental/mock-env/instrumented-mock-example-mcp-server.ts",
|
|
60
|
+
"dev:server": "tsx experimental/mock-env/mock-example-mcp-server.ts",
|
|
61
61
|
"demo": "tsx experimental/mock-env/demo-client.ts",
|
|
62
62
|
"demo:instrumented": "tsx experimental/mock-env/instrumented-demo-client.ts",
|
|
63
63
|
"test": "tsx --test tests/*.test.ts",
|
|
@@ -82,7 +82,7 @@
|
|
|
82
82
|
"@modelcontextprotocol/sdk": "^1.20.0"
|
|
83
83
|
},
|
|
84
84
|
"devDependencies": {
|
|
85
|
-
"@modelcontextprotocol/sdk": "
|
|
85
|
+
"@modelcontextprotocol/sdk": "1.20.0",
|
|
86
86
|
"@types/node": "^22.10.2",
|
|
87
87
|
"tsx": "^4.19.2",
|
|
88
88
|
"typescript": "^5.7.2"
|