@armature-tech/mcp-analytics 0.4.4 → 0.6.0
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 +5 -5
- package/SKILL.md +40 -4
- package/dist/cjs/client-info-cache.d.ts +8 -0
- package/dist/cjs/client-info-cache.js +107 -0
- package/dist/cjs/emit.d.ts +0 -3
- package/dist/cjs/emit.js +4 -3
- package/dist/cjs/events.js +1 -0
- package/dist/cjs/index.d.ts +1 -0
- package/dist/cjs/index.js +3 -1
- package/dist/cjs/instrument-tools.d.ts +26 -0
- package/dist/cjs/instrument-tools.js +23 -0
- package/dist/cjs/mastra.d.ts +6 -5
- package/dist/cjs/mastra.js +99 -2
- package/dist/cjs/recorder.js +12 -2
- package/dist/cjs/schema.d.ts +10 -10
- package/dist/cjs/schema.js +5 -2
- package/dist/cjs/server.js +108 -39
- package/dist/cjs/types.d.ts +7 -3
- package/dist/esm/client-info-cache.d.ts +8 -0
- package/dist/esm/client-info-cache.js +97 -0
- package/dist/esm/emit.d.ts +0 -3
- package/dist/esm/emit.js +4 -3
- package/dist/esm/events.js +1 -0
- package/dist/esm/index.d.ts +1 -0
- package/dist/esm/index.js +1 -0
- package/dist/esm/instrument-tools.d.ts +26 -0
- package/dist/esm/instrument-tools.js +20 -0
- package/dist/esm/mastra.d.ts +6 -5
- package/dist/esm/mastra.js +97 -1
- package/dist/esm/recorder.js +12 -2
- package/dist/esm/schema.d.ts +10 -10
- package/dist/esm/schema.js +5 -2
- package/dist/esm/server.js +108 -39
- package/dist/esm/types.d.ts +7 -3
- package/package.json +5 -2
package/README.md
CHANGED
|
@@ -49,13 +49,13 @@ Decorate input schemas, strip telemetry fields before the handler runs, time the
|
|
|
49
49
|
|
|
50
50
|
**3) The agent should be able to tell you what it's doing.**
|
|
51
51
|
|
|
52
|
-
We add a `telemetry` object to each tool's input schema with `intent`, `context`, and `frustration_level`. Agents fill it in, the SDK strips it before your handler sees args, and Armature shows you the *why* behind each call.
|
|
52
|
+
We add a `telemetry` object to each tool's input schema with `intent`, `context`, and `frustration_level`. Agents fill it in, the SDK strips it before your handler sees args, and Armature shows you the *why* behind each call. The block and its fields are optional — agents pass what they can, the SDK records what's there.
|
|
53
53
|
|
|
54
54
|
## How it works
|
|
55
55
|
|
|
56
56
|
Three things happen on every tool call:
|
|
57
57
|
|
|
58
|
-
1. **The agent sees a `telemetry` block** added to your tool's input schema — `intent`, `context`, `frustration_level`.
|
|
58
|
+
1. **The agent sees a `telemetry` block** added to your tool's input schema — `intent`, `context`, `frustration_level`. The block is optional; the SDK never rejects a call for omitting it.
|
|
59
59
|
2. **Your handler sees its original args.** The SDK strips `telemetry` before invoking it.
|
|
60
60
|
3. **An authenticated batch is POSTed to Armature** with timing, status, input/output previews, and whatever the agent put in `telemetry`. The first call on a new `sessionId` is preceded by a `session_init` event.
|
|
61
61
|
|
|
@@ -63,6 +63,7 @@ Three things happen on every tool call:
|
|
|
63
63
|
|
|
64
64
|
`createMcpAnalyticsServer` covers most repos. If yours doesn't fit, there are three other entry points — the [agent skill](SKILL.md) picks the right one automatically:
|
|
65
65
|
|
|
66
|
+
- **Concrete-server registry helper** — `instrumentMcpServerTools({ server, tools, config, mapTool })`. Use when you already own both the `McpServer` instance and your tool registry; the helper calls `server.registerTool(...)` directly (no prototype patching), so it survives pnpm virtual-peer layouts where `createMcpAnalyticsServer`'s patch can miss the customer's SDK module copy.
|
|
66
67
|
- **Registry-style** — `createAnalyticsRecorder()` + `analytics.tool(...)` + `analytics.createMcpServer(...)`. Use when you're building a server from scratch and want the recorder to own tool registration.
|
|
67
68
|
- **Dispatcher-style** — same recorder, but you call `analytics.toolDefinitions()` from your `tools/list` handler and `analytics.dispatch(name, args, ctx)` from `tools/call`. For servers that hand-roll the JSON-RPC layer.
|
|
68
69
|
- **Mastra** — `wrapMastraTools(tools, config)` from `@armature-tech/mcp-analytics/mastra`. Drop the wrapped map into `new MCPServer({ tools })`.
|
|
@@ -73,9 +74,6 @@ Code examples for all three live in [`SKILL.md`](SKILL.md).
|
|
|
73
74
|
|
|
74
75
|
```ts
|
|
75
76
|
type McpAnalyticsConfig = {
|
|
76
|
-
telemetry?: {
|
|
77
|
-
intent?: "required" | "optional"; // default "optional"
|
|
78
|
-
};
|
|
79
77
|
armature?: {
|
|
80
78
|
endpointUrl?: string; // default reads ANALYTICS_INGEST_URL
|
|
81
79
|
apiKey?: string; // default reads ANALYTICS_INGEST_API_KEY
|
|
@@ -89,6 +87,8 @@ type McpAnalyticsConfig = {
|
|
|
89
87
|
};
|
|
90
88
|
```
|
|
91
89
|
|
|
90
|
+
The shape of the `telemetry` block on each tool's input schema is Armature-owned and not customer-configurable. Customers only set operational config (delivery, actor id, transport).
|
|
91
|
+
|
|
92
92
|
**Delivery mode.** `"background"` (default, best for long-lived processes) returns the tool result immediately and posts the batch on `setImmediate` — call `await analytics.flush()` at shutdown. `"await"` (recommended for serverless) resolves only after the batch has been posted; no flush needed.
|
|
93
93
|
|
|
94
94
|
**Actor id.** A SHA-256 of an actor seed. By default the seed comes from the request's auth token / client id / authorization header. Pass a static `armature.actorId` seed for a stable source, or a function to derive the seed from `{ ctx, extra, headers, authInfo, toolName, telemetry }`. Armature scopes the actor id to your server via the API key, so the same seed under two different servers stays linked to the same person (cross-surface analytics).
|
package/SKILL.md
CHANGED
|
@@ -135,6 +135,36 @@ If you need `recorder.flush()` (serverless), use `withMcpAnalytics` instead and
|
|
|
135
135
|
`await recorder.flush()` at the end of the request handler. Don't sprinkle `flush()` calls
|
|
136
136
|
through tool handlers — once per request, at the end, is enough.
|
|
137
137
|
|
|
138
|
+
#### Shape A alternative — `instrumentMcpServerTools`
|
|
139
|
+
|
|
140
|
+
Use when the customer **already owns both the `McpServer` instance and a tool registry**
|
|
141
|
+
(array or map of definitions), and either: the project is pnpm with virtual peer
|
|
142
|
+
hoisting (where prototype patching can target the wrong `@modelcontextprotocol/sdk`
|
|
143
|
+
module copy), or refactoring the construction site into a factory function for
|
|
144
|
+
`createMcpAnalyticsServer` is awkward. No prototype patching — the helper calls
|
|
145
|
+
`server.registerTool(...)` directly on the instance the caller passed in.
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
import { instrumentMcpServerTools } from "@armature-tech/mcp-analytics";
|
|
149
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
150
|
+
|
|
151
|
+
const { server, recorder } = instrumentMcpServerTools({
|
|
152
|
+
server: new McpServer(serverInfo),
|
|
153
|
+
tools: myExistingRegistry,
|
|
154
|
+
config: { armature: { delivery: "await" } },
|
|
155
|
+
// Only needed if your registry shape differs from `InstrumentedTool` —
|
|
156
|
+
// i.e. the entries aren't already `{ name, description?, inputSchema?, handler }`.
|
|
157
|
+
mapTool: (def) => ({
|
|
158
|
+
name: def.name,
|
|
159
|
+
description: def.description,
|
|
160
|
+
inputSchema: def.inputSchema,
|
|
161
|
+
handler: (args, context) => def.handler(args, context.extra),
|
|
162
|
+
}),
|
|
163
|
+
});
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
`recorder` is returned for `await recorder.flush()` on serverless / shutdown.
|
|
167
|
+
|
|
138
168
|
### Shape B — Registry-style
|
|
139
169
|
|
|
140
170
|
The recorder owns the tool registry. Define tools on the recorder, then ask it to build
|
|
@@ -240,20 +270,26 @@ new MCPServer({ tools: analytics.wrapTools(createMyTools()), ... });
|
|
|
240
270
|
process.on("SIGTERM", () => analytics.flush());
|
|
241
271
|
```
|
|
242
272
|
|
|
243
|
-
|
|
244
|
-
`
|
|
245
|
-
|
|
273
|
+
By default the adapter pulls `sessionId`, `requestId`, `requestInfo.headers`, and
|
|
274
|
+
`authInfo` straight out of Mastra's standard MCP context — `context.mcp.extra` (with
|
|
275
|
+
`context.requestContext.get("mcp.extra")` as a fallback). No `resolveExtra` glue
|
|
276
|
+
required for tools invoked over MCP. Pass a `resolveExtra` only when you need to
|
|
277
|
+
override or add fields (e.g. servers that store auth elsewhere); the values you return
|
|
278
|
+
are merged on top of the default extraction:
|
|
246
279
|
|
|
247
280
|
```ts
|
|
248
281
|
wrapMastraTools(tools, {
|
|
249
282
|
armature: { delivery: "await" },
|
|
250
283
|
resolveExtra: (mastraContext) => ({
|
|
251
284
|
sessionId: (mastraContext as any)?.runtimeContext?.get?.("sessionId"),
|
|
252
|
-
authInfo: (mastraContext as any)?.requestContext?.authInfo,
|
|
253
285
|
}),
|
|
254
286
|
});
|
|
255
287
|
```
|
|
256
288
|
|
|
289
|
+
The SDK also recognises `authInfo.apiKey` and `authInfo.principalId` as actor-seed
|
|
290
|
+
aliases (alongside `authInfo.token` and `authInfo.clientId`), so Mastra setups that
|
|
291
|
+
expose auth under those names don't need a custom `actorId` resolver.
|
|
292
|
+
|
|
257
293
|
`actorId` is configured the normal way on `config.armature.actorId` — the resolver
|
|
258
294
|
receives `ctx` set to Mastra's second-arg context.
|
|
259
295
|
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { McpClientInfo } from "./types.js";
|
|
2
|
+
export declare const installClientInfoCapture: () => void;
|
|
3
|
+
export declare const getClientInfoForSessionId: (sessionId: string | undefined) => McpClientInfo | undefined;
|
|
4
|
+
export declare const __setClientInfoForSessionId: (sessionId: string, info: McpClientInfo) => void;
|
|
5
|
+
export declare const __clearClientInfoCache: () => void;
|
|
6
|
+
export declare const __isInitializePatchInstalled: () => boolean;
|
|
7
|
+
export declare const __getClientInfoCacheSize: () => number;
|
|
8
|
+
export declare const __getMaxClientInfoCacheEntries: () => number;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.__getMaxClientInfoCacheEntries = exports.__getClientInfoCacheSize = exports.__isInitializePatchInstalled = exports.__clearClientInfoCache = exports.__setClientInfoForSessionId = exports.getClientInfoForSessionId = exports.installClientInfoCapture = void 0;
|
|
4
|
+
const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
|
|
5
|
+
// In-process map keyed by transport sessionId. Populated by the patched
|
|
6
|
+
// `Server.prototype._oninitialize` and read by the recorder at tool-call time.
|
|
7
|
+
// Same instance the customer constructs, because `@modelcontextprotocol/sdk`
|
|
8
|
+
// is a peer dependency.
|
|
9
|
+
//
|
|
10
|
+
// Bounded by `MAX_CACHE_ENTRIES` with FIFO eviction (Map iteration order is
|
|
11
|
+
// insertion order in JS, so the first key is the oldest). MCP `initialize`
|
|
12
|
+
// never fires a corresponding "session-closed" signal we can hook reliably —
|
|
13
|
+
// short-lived sessions on a long-running server would otherwise leak forever.
|
|
14
|
+
// 10k entries × ~200 bytes ≈ 2MB upper bound, well below anything operators
|
|
15
|
+
// would notice; the cap is far above any plausible concurrent-session count.
|
|
16
|
+
const MAX_CACHE_ENTRIES = 10_000;
|
|
17
|
+
const clientInfoBySessionId = new Map();
|
|
18
|
+
const setCachedClientInfo = (sessionId, info) => {
|
|
19
|
+
if (clientInfoBySessionId.has(sessionId)) {
|
|
20
|
+
clientInfoBySessionId.delete(sessionId);
|
|
21
|
+
}
|
|
22
|
+
else if (clientInfoBySessionId.size >= MAX_CACHE_ENTRIES) {
|
|
23
|
+
const oldest = clientInfoBySessionId.keys().next().value;
|
|
24
|
+
if (oldest !== undefined)
|
|
25
|
+
clientInfoBySessionId.delete(oldest);
|
|
26
|
+
}
|
|
27
|
+
clientInfoBySessionId.set(sessionId, info);
|
|
28
|
+
};
|
|
29
|
+
let initializePatchInstalled = false;
|
|
30
|
+
const extractInitializeParams = (request) => {
|
|
31
|
+
if (typeof request !== "object" || request === null)
|
|
32
|
+
return {};
|
|
33
|
+
const params = request.params;
|
|
34
|
+
return typeof params === "object" && params !== null
|
|
35
|
+
? params
|
|
36
|
+
: {};
|
|
37
|
+
};
|
|
38
|
+
// `Server.prototype._oninitialize` is a private method that runs on every
|
|
39
|
+
// `initialize` request, right before the handshake response is sent. Wrapping
|
|
40
|
+
// it lets us snapshot `clientInfo` and key it by `transport.sessionId` so the
|
|
41
|
+
// tool-call path can recover the client name even when the framework around
|
|
42
|
+
// the SDK (e.g. Mastra's `MCPServer`) never surfaces the underlying `Server`
|
|
43
|
+
// instance to the tool handler.
|
|
44
|
+
//
|
|
45
|
+
// Defensive: if the SDK ever renames the method, the patch is a no-op and the
|
|
46
|
+
// dashboard regresses to today's behaviour rather than breaking the server.
|
|
47
|
+
const installClientInfoCapture = () => {
|
|
48
|
+
if (initializePatchInstalled)
|
|
49
|
+
return;
|
|
50
|
+
const proto = index_js_1.Server.prototype;
|
|
51
|
+
if (typeof proto._oninitialize !== "function")
|
|
52
|
+
return;
|
|
53
|
+
initializePatchInstalled = true;
|
|
54
|
+
const original = proto._oninitialize;
|
|
55
|
+
proto._oninitialize = async function patchedOnInitialize(request) {
|
|
56
|
+
const result = await original.call(this, request);
|
|
57
|
+
try {
|
|
58
|
+
const params = extractInitializeParams(request);
|
|
59
|
+
const sessionId = this.transport?.sessionId ?? params._meta?.sessionId ?? undefined;
|
|
60
|
+
const info = params.clientInfo;
|
|
61
|
+
const name = typeof info?.name === "string" ? info.name.trim() : "";
|
|
62
|
+
if (sessionId && name.length > 0) {
|
|
63
|
+
setCachedClientInfo(sessionId, {
|
|
64
|
+
name,
|
|
65
|
+
version: typeof info?.version === "string" ? info.version : undefined,
|
|
66
|
+
protocolVersion: typeof params.protocolVersion === "string"
|
|
67
|
+
? params.protocolVersion
|
|
68
|
+
: undefined,
|
|
69
|
+
capabilities: typeof params.capabilities === "object" && params.capabilities !== null
|
|
70
|
+
? params.capabilities
|
|
71
|
+
: null,
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
// Capture is best-effort; never break the handshake.
|
|
77
|
+
}
|
|
78
|
+
return result;
|
|
79
|
+
};
|
|
80
|
+
};
|
|
81
|
+
exports.installClientInfoCapture = installClientInfoCapture;
|
|
82
|
+
const getClientInfoForSessionId = (sessionId) => {
|
|
83
|
+
if (!sessionId)
|
|
84
|
+
return undefined;
|
|
85
|
+
return clientInfoBySessionId.get(sessionId);
|
|
86
|
+
};
|
|
87
|
+
exports.getClientInfoForSessionId = getClientInfoForSessionId;
|
|
88
|
+
// INTERNAL. Not part of the public API and may change or disappear in any
|
|
89
|
+
// release. These exports exist so the test suite can seed/clear shared module
|
|
90
|
+
// state without standing up a full MCP handshake. Downstream callers cannot
|
|
91
|
+
// reach them through the package name: `package.json#exports` only publishes
|
|
92
|
+
// `.` and `./mastra`, so Node refuses deep imports under either ESM `import`
|
|
93
|
+
// or CJS `require`.
|
|
94
|
+
const __setClientInfoForSessionId = (sessionId, info) => {
|
|
95
|
+
setCachedClientInfo(sessionId, info);
|
|
96
|
+
};
|
|
97
|
+
exports.__setClientInfoForSessionId = __setClientInfoForSessionId;
|
|
98
|
+
const __clearClientInfoCache = () => {
|
|
99
|
+
clientInfoBySessionId.clear();
|
|
100
|
+
};
|
|
101
|
+
exports.__clearClientInfoCache = __clearClientInfoCache;
|
|
102
|
+
const __isInitializePatchInstalled = () => initializePatchInstalled;
|
|
103
|
+
exports.__isInitializePatchInstalled = __isInitializePatchInstalled;
|
|
104
|
+
const __getClientInfoCacheSize = () => clientInfoBySessionId.size;
|
|
105
|
+
exports.__getClientInfoCacheSize = __getClientInfoCacheSize;
|
|
106
|
+
const __getMaxClientInfoCacheEntries = () => MAX_CACHE_ENTRIES;
|
|
107
|
+
exports.__getMaxClientInfoCacheEntries = __getMaxClientInfoCacheEntries;
|
package/dist/cjs/emit.d.ts
CHANGED
package/dist/cjs/emit.js
CHANGED
|
@@ -3,9 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.createFlushableEmitter = exports.emitTelemetryEvent = exports.postTelemetryEvent = exports.resolveActorSeed = exports.resolveApiKey = exports.resolveEndpointUrl = exports.defaultMcpAnalyticsConfig = void 0;
|
|
4
4
|
const utils_js_1 = require("./utils.js");
|
|
5
5
|
exports.defaultMcpAnalyticsConfig = {
|
|
6
|
-
telemetry: {
|
|
7
|
-
intent: "optional",
|
|
8
|
-
},
|
|
9
6
|
armature: {
|
|
10
7
|
endpointUrl: "https://app.armature.tech/api/mcp-analytics/ingest",
|
|
11
8
|
enabled: true,
|
|
@@ -33,6 +30,10 @@ const resolveActorSeed = async (config, input) => {
|
|
|
33
30
|
return input.authInfo.token;
|
|
34
31
|
if (input.authInfo?.clientId)
|
|
35
32
|
return input.authInfo.clientId;
|
|
33
|
+
if (input.authInfo?.apiKey)
|
|
34
|
+
return input.authInfo.apiKey;
|
|
35
|
+
if (input.authInfo?.principalId)
|
|
36
|
+
return input.authInfo.principalId;
|
|
36
37
|
const authorization = (0, utils_js_1.headerValue)(input.headers, "authorization");
|
|
37
38
|
if (authorization)
|
|
38
39
|
return authorization;
|
package/dist/cjs/events.js
CHANGED
|
@@ -79,6 +79,7 @@ const buildSessionInitEvent = ({ actorId, sessionId, requestId, startedAt, extra
|
|
|
79
79
|
metadata: {
|
|
80
80
|
client_name: trimOrUndefined(clientInfo?.name)
|
|
81
81
|
?? trimOrUndefined(extra?.authInfo?.clientId)
|
|
82
|
+
?? trimOrUndefined((0, utils_js_1.headerValue)(extra?.requestInfo?.headers, "x-mcp-client"))
|
|
82
83
|
?? null,
|
|
83
84
|
client_version: trimOrUndefined(clientInfo?.version) ?? null,
|
|
84
85
|
protocol_version: trimOrUndefined(clientInfo?.protocolVersion) ?? null,
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -4,3 +4,4 @@ export { buildActorId, buildEventId, buildSessionInitEvent, buildToolCallEvent,
|
|
|
4
4
|
export { defaultMcpAnalyticsConfig, emitTelemetryEvent, postTelemetryEvent, } from "./emit.js";
|
|
5
5
|
export { createAnalyticsRecorder } from "./recorder.js";
|
|
6
6
|
export { createMcpAnalyticsServer, withMcpAnalytics } from "./server.js";
|
|
7
|
+
export { instrumentMcpServerTools, type InstrumentMcpServerToolsOptions, type InstrumentMcpServerToolsResult, type InstrumentedTool, } from "./instrument-tools.js";
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.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.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;
|
|
4
4
|
var schema_js_1 = require("./schema.js");
|
|
5
5
|
Object.defineProperty(exports, "createTelemetryInputSchema", { enumerable: true, get: function () { return schema_js_1.createTelemetryInputSchema; } });
|
|
6
6
|
Object.defineProperty(exports, "createTelemetryJsonSchema", { enumerable: true, get: function () { return schema_js_1.createTelemetryJsonSchema; } });
|
|
@@ -21,3 +21,5 @@ Object.defineProperty(exports, "createAnalyticsRecorder", { enumerable: true, ge
|
|
|
21
21
|
var server_js_1 = require("./server.js");
|
|
22
22
|
Object.defineProperty(exports, "createMcpAnalyticsServer", { enumerable: true, get: function () { return server_js_1.createMcpAnalyticsServer; } });
|
|
23
23
|
Object.defineProperty(exports, "withMcpAnalytics", { enumerable: true, get: function () { return server_js_1.withMcpAnalytics; } });
|
|
24
|
+
var instrument_tools_js_1 = require("./instrument-tools.js");
|
|
25
|
+
Object.defineProperty(exports, "instrumentMcpServerTools", { enumerable: true, get: function () { return instrument_tools_js_1.instrumentMcpServerTools; } });
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import type { AnalyticsRecorder, McpAnalyticsConfig, RegisteredToolHandler, ToolRegistration } from "./types.js";
|
|
3
|
+
export type InstrumentedTool = ToolRegistration & {
|
|
4
|
+
handler: RegisteredToolHandler<unknown, unknown>;
|
|
5
|
+
};
|
|
6
|
+
type BaseInstrumentOptions = {
|
|
7
|
+
server: McpServer;
|
|
8
|
+
config?: McpAnalyticsConfig;
|
|
9
|
+
};
|
|
10
|
+
export type InstrumentMcpServerToolsOptions<TDef> = BaseInstrumentOptions & {
|
|
11
|
+
tools: TDef[] | Record<string, TDef>;
|
|
12
|
+
mapTool?: (def: TDef, key?: string) => InstrumentedTool;
|
|
13
|
+
};
|
|
14
|
+
export type InstrumentMcpServerToolsResult = {
|
|
15
|
+
server: McpServer;
|
|
16
|
+
recorder: AnalyticsRecorder;
|
|
17
|
+
};
|
|
18
|
+
export declare function instrumentMcpServerTools(options: BaseInstrumentOptions & {
|
|
19
|
+
tools: InstrumentedTool[] | Record<string, InstrumentedTool>;
|
|
20
|
+
mapTool?: (def: InstrumentedTool, key?: string) => InstrumentedTool;
|
|
21
|
+
}): InstrumentMcpServerToolsResult;
|
|
22
|
+
export declare function instrumentMcpServerTools<TDef>(options: BaseInstrumentOptions & {
|
|
23
|
+
tools: TDef[] | Record<string, TDef>;
|
|
24
|
+
mapTool: (def: TDef, key?: string) => InstrumentedTool;
|
|
25
|
+
}): InstrumentMcpServerToolsResult;
|
|
26
|
+
export {};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.instrumentMcpServerTools = instrumentMcpServerTools;
|
|
4
|
+
const recorder_js_1 = require("./recorder.js");
|
|
5
|
+
function instrumentMcpServerTools(options) {
|
|
6
|
+
const recorder = (0, recorder_js_1.createAnalyticsRecorder)(options.config);
|
|
7
|
+
recorder.attachToMcpServer(options.server);
|
|
8
|
+
const identity = (def) => def;
|
|
9
|
+
const mapper = options.mapTool ?? identity;
|
|
10
|
+
if (Array.isArray(options.tools)) {
|
|
11
|
+
for (const def of options.tools) {
|
|
12
|
+
const mapped = mapper(def, undefined);
|
|
13
|
+
recorder.tool(mapped, mapped.handler);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
else {
|
|
17
|
+
for (const [key, def] of Object.entries(options.tools)) {
|
|
18
|
+
const mapped = mapper(def, key);
|
|
19
|
+
recorder.tool(mapped, mapped.handler);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return { server: options.server, recorder };
|
|
23
|
+
}
|
package/dist/cjs/mastra.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AnalyticsRecorder, McpAnalyticsConfig, RequestExtra } from "./types.js";
|
|
1
|
+
import type { AnalyticsRecorder, InternalMcpAnalyticsConfig, McpAnalyticsConfig, RequestExtra } from "./types.js";
|
|
2
2
|
export type MastraToolExecute = (inputData: any, context?: any) => unknown | Promise<unknown>;
|
|
3
3
|
export type MastraTool = {
|
|
4
4
|
id?: string;
|
|
@@ -12,13 +12,14 @@ export type MastraToolMap = Record<string, MastraTool>;
|
|
|
12
12
|
export type MastraAdapterOptions = McpAnalyticsConfig & {
|
|
13
13
|
resolveExtra?: (mastraContext: unknown) => RequestExtra | undefined;
|
|
14
14
|
};
|
|
15
|
-
export declare const
|
|
15
|
+
export declare const defaultMastraResolveExtra: (mastraContext: unknown) => RequestExtra | undefined;
|
|
16
|
+
export declare const wrapMastraToolsWithRecorder: <T extends MastraToolMap>(tools: T, recorder: AnalyticsRecorder, config?: InternalMcpAnalyticsConfig, options?: {
|
|
16
17
|
resolveExtra?: MastraAdapterOptions["resolveExtra"];
|
|
17
|
-
}) =>
|
|
18
|
-
export declare const wrapMastraTools: (tools:
|
|
18
|
+
}) => T;
|
|
19
|
+
export declare const wrapMastraTools: <T extends MastraToolMap>(tools: T, options?: MastraAdapterOptions) => T;
|
|
19
20
|
export type MastraAnalytics = {
|
|
20
21
|
recorder: AnalyticsRecorder;
|
|
21
|
-
wrapTools: (tools:
|
|
22
|
+
wrapTools: <T extends MastraToolMap>(tools: T) => T;
|
|
22
23
|
flush: () => Promise<void>;
|
|
23
24
|
};
|
|
24
25
|
export declare const createMastraAnalytics: (options?: MastraAdapterOptions) => MastraAnalytics;
|
package/dist/cjs/mastra.js
CHANGED
|
@@ -1,8 +1,93 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.createMastraAnalytics = exports.wrapMastraTools = exports.wrapMastraToolsWithRecorder = void 0;
|
|
3
|
+
exports.createMastraAnalytics = exports.wrapMastraTools = exports.wrapMastraToolsWithRecorder = exports.defaultMastraResolveExtra = void 0;
|
|
4
4
|
const recorder_js_1 = require("./recorder.js");
|
|
5
5
|
const schema_js_1 = require("./schema.js");
|
|
6
|
+
const utils_js_1 = require("./utils.js");
|
|
7
|
+
const readMcpExtra = (mastraContext) => {
|
|
8
|
+
if (!(0, utils_js_1.isRecord)(mastraContext))
|
|
9
|
+
return undefined;
|
|
10
|
+
// Direct path: context.mcp.extra (the second argument Mastra's MCPServer
|
|
11
|
+
// passes into `execute` for tools invoked over MCP).
|
|
12
|
+
const mcp = mastraContext.mcp;
|
|
13
|
+
if ((0, utils_js_1.isRecord)(mcp) && (0, utils_js_1.isRecord)(mcp.extra))
|
|
14
|
+
return mcp.extra;
|
|
15
|
+
// Fallback: context.requestContext.get("mcp.extra") — some Mastra setups
|
|
16
|
+
// route the MCP extra through RuntimeContext under that key.
|
|
17
|
+
const requestContext = mastraContext.requestContext;
|
|
18
|
+
if ((0, utils_js_1.isRecord)(requestContext) &&
|
|
19
|
+
typeof requestContext.get === "function") {
|
|
20
|
+
const fromContext = requestContext.get("mcp.extra");
|
|
21
|
+
if ((0, utils_js_1.isRecord)(fromContext))
|
|
22
|
+
return fromContext;
|
|
23
|
+
}
|
|
24
|
+
return undefined;
|
|
25
|
+
};
|
|
26
|
+
const defaultMastraResolveExtra = (mastraContext) => {
|
|
27
|
+
const mcpExtra = readMcpExtra(mastraContext);
|
|
28
|
+
if (!mcpExtra)
|
|
29
|
+
return undefined;
|
|
30
|
+
const result = {};
|
|
31
|
+
if (typeof mcpExtra.sessionId === "string" && mcpExtra.sessionId.length > 0) {
|
|
32
|
+
result.sessionId = mcpExtra.sessionId;
|
|
33
|
+
}
|
|
34
|
+
const requestId = mcpExtra.requestId;
|
|
35
|
+
if (typeof requestId === "string" || typeof requestId === "number") {
|
|
36
|
+
result.requestId = requestId;
|
|
37
|
+
}
|
|
38
|
+
if ((0, utils_js_1.isRecord)(mcpExtra.requestInfo)) {
|
|
39
|
+
const headers = mcpExtra.requestInfo.headers;
|
|
40
|
+
if (headers !== undefined) {
|
|
41
|
+
result.requestInfo = { headers: headers };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if ((0, utils_js_1.isRecord)(mcpExtra.authInfo)) {
|
|
45
|
+
// Narrow to the four fields `resolveActorSeed` / `buildSessionInitEvent`
|
|
46
|
+
// actually consume — don't forward arbitrary unrelated properties from a
|
|
47
|
+
// host-supplied object down the analytics pipeline.
|
|
48
|
+
const incoming = mcpExtra.authInfo;
|
|
49
|
+
const authInfo = {};
|
|
50
|
+
if (typeof incoming.token === "string")
|
|
51
|
+
authInfo.token = incoming.token;
|
|
52
|
+
if (typeof incoming.clientId === "string")
|
|
53
|
+
authInfo.clientId = incoming.clientId;
|
|
54
|
+
if (typeof incoming.apiKey === "string")
|
|
55
|
+
authInfo.apiKey = incoming.apiKey;
|
|
56
|
+
if (typeof incoming.principalId === "string") {
|
|
57
|
+
authInfo.principalId = incoming.principalId;
|
|
58
|
+
}
|
|
59
|
+
if (Object.keys(authInfo).length > 0)
|
|
60
|
+
result.authInfo = authInfo;
|
|
61
|
+
}
|
|
62
|
+
return Object.keys(result).length > 0 ? result : undefined;
|
|
63
|
+
};
|
|
64
|
+
exports.defaultMastraResolveExtra = defaultMastraResolveExtra;
|
|
65
|
+
const mergeExtra = (base, override) => {
|
|
66
|
+
if (!base)
|
|
67
|
+
return override;
|
|
68
|
+
if (!override)
|
|
69
|
+
return base;
|
|
70
|
+
return {
|
|
71
|
+
...base,
|
|
72
|
+
...override,
|
|
73
|
+
...(base.requestInfo || override.requestInfo
|
|
74
|
+
? {
|
|
75
|
+
requestInfo: {
|
|
76
|
+
...(base.requestInfo ?? {}),
|
|
77
|
+
...(override.requestInfo ?? {}),
|
|
78
|
+
},
|
|
79
|
+
}
|
|
80
|
+
: {}),
|
|
81
|
+
...(base.authInfo || override.authInfo
|
|
82
|
+
? {
|
|
83
|
+
authInfo: {
|
|
84
|
+
...(base.authInfo ?? {}),
|
|
85
|
+
...(override.authInfo ?? {}),
|
|
86
|
+
},
|
|
87
|
+
}
|
|
88
|
+
: {}),
|
|
89
|
+
};
|
|
90
|
+
};
|
|
6
91
|
const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
|
|
7
92
|
if (typeof tool?.execute !== "function") {
|
|
8
93
|
return tool;
|
|
@@ -13,7 +98,11 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
|
|
|
13
98
|
? undefined
|
|
14
99
|
: (0, schema_js_1.decorateInputSchemaWithTelemetry)(tool.inputSchema, config);
|
|
15
100
|
const wrappedExecute = (inputData, mastraContext) => {
|
|
16
|
-
|
|
101
|
+
// Always extract standard Mastra MCP context (`context.mcp.extra` or the
|
|
102
|
+
// `requestContext.get("mcp.extra")` fallback). A user-supplied
|
|
103
|
+
// `resolveExtra` layers on top — its values win where both define a field,
|
|
104
|
+
// so it doubles as an override and an extension point.
|
|
105
|
+
const extra = mergeExtra((0, exports.defaultMastraResolveExtra)(mastraContext), resolveExtra?.(mastraContext));
|
|
17
106
|
return recorder.instrumentToolCall({
|
|
18
107
|
name: toolName,
|
|
19
108
|
args: inputData,
|
|
@@ -33,6 +122,14 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
|
|
|
33
122
|
execute: wrappedExecute,
|
|
34
123
|
};
|
|
35
124
|
};
|
|
125
|
+
// Generic over the input map so the return value keeps the customer's exact
|
|
126
|
+
// tool-map type (e.g. `Record<string, AutumnTool>`). Without this, every Mastra
|
|
127
|
+
// caller had to do `wrapMastraTools(myTools as unknown as MastraToolMap, ...) as
|
|
128
|
+
// unknown as typeof myTools` because `MCPServer({ tools })` wants the narrower
|
|
129
|
+
// type back. The `T extends MastraToolMap` constraint lets us still operate on
|
|
130
|
+
// the values structurally — Mastra's `createTool({...})` shape is a strict
|
|
131
|
+
// subtype of `MastraTool` (id/inputSchema/outputSchema/execute), so any tool map
|
|
132
|
+
// passes the constraint without a cast.
|
|
36
133
|
const wrapMastraToolsWithRecorder = (tools, recorder, config = {}, options = {}) => {
|
|
37
134
|
const out = {};
|
|
38
135
|
for (const [key, tool] of Object.entries(tools)) {
|
package/dist/cjs/recorder.js
CHANGED
|
@@ -7,6 +7,7 @@ const events_js_1 = require("./events.js");
|
|
|
7
7
|
const emit_js_1 = require("./emit.js");
|
|
8
8
|
const schema_js_1 = require("./schema.js");
|
|
9
9
|
const utils_js_1 = require("./utils.js");
|
|
10
|
+
const client_info_cache_js_1 = require("./client-info-cache.js");
|
|
10
11
|
const TELEMETRY_DESCRIPTION_HINT = "\n\nPass telemetry.intent with a one-line user intent for analytics.";
|
|
11
12
|
const TELEMETRY_DESCRIPTION_HINT_MARKER = TELEMETRY_DESCRIPTION_HINT.trim();
|
|
12
13
|
const nudgeTelemetryDescriptions = (schema) => {
|
|
@@ -49,6 +50,12 @@ const createAnalyticsContext = async (config, input) => {
|
|
|
49
50
|
const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) => {
|
|
50
51
|
const { emitBatch, flush } = (0, emit_js_1.createFlushableEmitter)(config);
|
|
51
52
|
const sessionInitKeys = new Set();
|
|
53
|
+
// Patch the SDK's Server.prototype the first time any recorder is created
|
|
54
|
+
// so that the very next `initialize` handshake feeds the per-session client
|
|
55
|
+
// info cache. Without this the dashboard's "Client" column would stay at
|
|
56
|
+
// "Unknown" for Mastra-wrapped tool calls, which can't reach the underlying
|
|
57
|
+
// SDK Server from inside `tool.execute`.
|
|
58
|
+
(0, client_info_cache_js_1.installClientInfoCapture)();
|
|
52
59
|
const analyticsContextFor = async (input) => {
|
|
53
60
|
return createAnalyticsContext(config, input);
|
|
54
61
|
};
|
|
@@ -86,7 +93,7 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
|
|
|
86
93
|
startedAt,
|
|
87
94
|
extra: event.extra,
|
|
88
95
|
sessionInitKeys,
|
|
89
|
-
clientInfo: event.clientInfo,
|
|
96
|
+
clientInfo: event.clientInfo ?? (0, client_info_cache_js_1.getClientInfoForSessionId)(sessionId),
|
|
90
97
|
});
|
|
91
98
|
if (batch)
|
|
92
99
|
await emitBatch(batch);
|
|
@@ -129,6 +136,9 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
|
|
|
129
136
|
startedAt,
|
|
130
137
|
finishedAt,
|
|
131
138
|
});
|
|
139
|
+
// An explicit clientInfo on the event always wins; otherwise look up
|
|
140
|
+
// whatever the initialize-handshake patch captured for this sessionId.
|
|
141
|
+
const effectiveClientInfo = event.clientInfo ?? (0, client_info_cache_js_1.getClientInfoForSessionId)(sessionId);
|
|
132
142
|
await emitBatch((0, events_js_1.buildBatch)({
|
|
133
143
|
event: toolCallEvent,
|
|
134
144
|
extra: {
|
|
@@ -138,7 +148,7 @@ const createAnalyticsRecorder = (config = emit_js_1.defaultMcpAnalyticsConfig) =
|
|
|
138
148
|
actorId: context.actorId,
|
|
139
149
|
startedAt,
|
|
140
150
|
sessionInitKeys,
|
|
141
|
-
clientInfo:
|
|
151
|
+
clientInfo: effectiveClientInfo,
|
|
142
152
|
}));
|
|
143
153
|
};
|
|
144
154
|
const registeredTools = new Map();
|
package/dist/cjs/schema.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import * as zv4 from "zod/v4";
|
|
3
|
-
import type { ExtractedToolArguments,
|
|
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
5
|
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
|
-
export declare const createTelemetryInputSchema: (config?:
|
|
6
|
+
export declare const createTelemetryInputSchema: (config?: InternalMcpAnalyticsConfig) => z.ZodObject<{
|
|
7
7
|
intent: z.ZodString;
|
|
8
8
|
context: z.ZodOptional<z.ZodString>;
|
|
9
9
|
frustration_level: z.ZodOptional<z.ZodEnum<["low", "medium", "high"]>>;
|
|
@@ -15,7 +15,7 @@ export declare const createTelemetryInputSchema: (config?: McpAnalyticsConfig) =
|
|
|
15
15
|
intent: string;
|
|
16
16
|
context?: string | undefined;
|
|
17
17
|
frustration_level?: "low" | "medium" | "high" | undefined;
|
|
18
|
-
}> | z.ZodObject<{
|
|
18
|
+
}> | z.ZodOptional<z.ZodObject<{
|
|
19
19
|
intent: z.ZodOptional<z.ZodString>;
|
|
20
20
|
context: z.ZodOptional<z.ZodString>;
|
|
21
21
|
frustration_level: z.ZodOptional<z.ZodString>;
|
|
@@ -27,9 +27,9 @@ export declare const createTelemetryInputSchema: (config?: McpAnalyticsConfig) =
|
|
|
27
27
|
intent?: string | undefined;
|
|
28
28
|
context?: string | undefined;
|
|
29
29
|
frustration_level?: string | undefined;
|
|
30
|
-
}
|
|
31
|
-
export declare const createTelemetryJsonSchema: (config?:
|
|
32
|
-
export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, config?:
|
|
30
|
+
}>>;
|
|
31
|
+
export declare const createTelemetryJsonSchema: (config?: InternalMcpAnalyticsConfig) => JsonObjectSchema;
|
|
32
|
+
export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, config?: InternalMcpAnalyticsConfig) => JsonObjectSchema | zv4.ZodObject<{
|
|
33
33
|
readonly [x: string]: zv4.core.$ZodType<unknown, unknown, zv4.core.$ZodTypeInternals<unknown, unknown>>;
|
|
34
34
|
telemetry: zv4.ZodObject<{
|
|
35
35
|
intent: zv4.ZodString;
|
|
@@ -39,11 +39,11 @@ export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, co
|
|
|
39
39
|
medium: "medium";
|
|
40
40
|
high: "high";
|
|
41
41
|
}>>;
|
|
42
|
-
}, zv4.core.$strip> | zv4.ZodObject<{
|
|
42
|
+
}, zv4.core.$strip> | zv4.ZodOptional<zv4.ZodObject<{
|
|
43
43
|
intent: zv4.ZodOptional<zv4.ZodString>;
|
|
44
44
|
context: zv4.ZodOptional<zv4.ZodString>;
|
|
45
45
|
frustration_level: zv4.ZodOptional<zv4.ZodString>;
|
|
46
|
-
}, zv4.core.$strip
|
|
46
|
+
}, zv4.core.$strip>>;
|
|
47
47
|
}, zv4.core.$strip> | z.ZodObject<{
|
|
48
48
|
[x: string]: any;
|
|
49
49
|
} & {
|
|
@@ -59,7 +59,7 @@ export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, co
|
|
|
59
59
|
intent: string;
|
|
60
60
|
context?: string | undefined;
|
|
61
61
|
frustration_level?: "low" | "medium" | "high" | undefined;
|
|
62
|
-
}> | z.ZodObject<{
|
|
62
|
+
}> | z.ZodOptional<z.ZodObject<{
|
|
63
63
|
intent: z.ZodOptional<z.ZodString>;
|
|
64
64
|
context: z.ZodOptional<z.ZodString>;
|
|
65
65
|
frustration_level: z.ZodOptional<z.ZodString>;
|
|
@@ -71,7 +71,7 @@ export declare const decorateInputSchemaWithTelemetry: (inputSchema: unknown, co
|
|
|
71
71
|
intent?: string | undefined;
|
|
72
72
|
context?: string | undefined;
|
|
73
73
|
frustration_level?: string | undefined;
|
|
74
|
-
}
|
|
74
|
+
}>>;
|
|
75
75
|
}, any, any, {
|
|
76
76
|
[x: string]: any;
|
|
77
77
|
telemetry?: unknown;
|
package/dist/cjs/schema.js
CHANGED
|
@@ -86,16 +86,19 @@ const isZodV3ObjectSchema = (value) => {
|
|
|
86
86
|
"shape" in value &&
|
|
87
87
|
typeof value.extend === "function");
|
|
88
88
|
};
|
|
89
|
+
// Loose mode wraps the telemetry object with `.optional()` so callers that omit
|
|
90
|
+
// the `telemetry` key entirely still parse. Strict mode keeps the object itself
|
|
91
|
+
// required (and `intent` required inside).
|
|
89
92
|
const createTelemetryInputSchema = (config = {}) => {
|
|
90
93
|
return config.telemetry?.intent === "required"
|
|
91
94
|
? strictTelemetryInputSchema
|
|
92
|
-
: looseTelemetryInputSchema;
|
|
95
|
+
: looseTelemetryInputSchema.optional();
|
|
93
96
|
};
|
|
94
97
|
exports.createTelemetryInputSchema = createTelemetryInputSchema;
|
|
95
98
|
const createTelemetryInputSchemaV4 = (config) => {
|
|
96
99
|
return config.telemetry?.intent === "required"
|
|
97
100
|
? strictTelemetryInputSchemaV4
|
|
98
|
-
: looseTelemetryInputSchemaV4;
|
|
101
|
+
: looseTelemetryInputSchemaV4.optional();
|
|
99
102
|
};
|
|
100
103
|
const createTelemetryJsonSchema = (config = {}) => {
|
|
101
104
|
const strict = config.telemetry?.intent === "required";
|