@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/dist/cjs/server.js
CHANGED
|
@@ -7,65 +7,134 @@ const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
|
7
7
|
const recorder_js_1 = require("./recorder.js");
|
|
8
8
|
const schema_js_1 = require("./schema.js");
|
|
9
9
|
const emit_js_1 = require("./emit.js");
|
|
10
|
+
const utils_js_1 = require("./utils.js");
|
|
10
11
|
const withAnalyticsStorage = new node_async_hooks_1.AsyncLocalStorage();
|
|
11
12
|
let prototypePatchInstalled = false;
|
|
13
|
+
// Mirrors the SDK's `isZodTypeLike`/`isZodRawShapeCompat` checks closely enough
|
|
14
|
+
// to disambiguate the overloads of `server.tool(...)`: a raw shape is a plain
|
|
15
|
+
// object whose values include at least one Zod schema, while a Zod schema
|
|
16
|
+
// instance carries `_def` (v3) or `_zod` (v4).
|
|
17
|
+
const isZodSchemaLike = (value) => {
|
|
18
|
+
if (!(0, utils_js_1.isRecord)(value))
|
|
19
|
+
return false;
|
|
20
|
+
return "_def" in value || "_zod" in value;
|
|
21
|
+
};
|
|
22
|
+
const isZodRawShapeLike = (value) => {
|
|
23
|
+
if (!(0, utils_js_1.isRecord)(value))
|
|
24
|
+
return false;
|
|
25
|
+
if (isZodSchemaLike(value))
|
|
26
|
+
return false;
|
|
27
|
+
if (Object.keys(value).length === 0)
|
|
28
|
+
return true;
|
|
29
|
+
return Object.values(value).some(isZodSchemaLike);
|
|
30
|
+
};
|
|
31
|
+
// Mirrors @modelcontextprotocol/sdk/server/mcp.js `tool(name, ...rest)` argument
|
|
32
|
+
// parsing so we can normalise every overload through our patched `registerTool`.
|
|
33
|
+
const parseDeprecatedToolArgs = (rest) => {
|
|
34
|
+
const args = [...rest];
|
|
35
|
+
let description;
|
|
36
|
+
let inputSchema;
|
|
37
|
+
let annotations;
|
|
38
|
+
if (typeof args[0] === "string") {
|
|
39
|
+
description = args.shift();
|
|
40
|
+
}
|
|
41
|
+
if (args.length > 1) {
|
|
42
|
+
const firstArg = args[0];
|
|
43
|
+
if (isZodRawShapeLike(firstArg)) {
|
|
44
|
+
inputSchema = args.shift();
|
|
45
|
+
if (args.length > 1 &&
|
|
46
|
+
(0, utils_js_1.isRecord)(args[0]) &&
|
|
47
|
+
!isZodRawShapeLike(args[0])) {
|
|
48
|
+
annotations = args.shift();
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
else if ((0, utils_js_1.isRecord)(firstArg)) {
|
|
52
|
+
annotations = args.shift();
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const callback = args[0];
|
|
56
|
+
return { description, inputSchema, annotations, callback };
|
|
57
|
+
};
|
|
58
|
+
const wrapCallbackWithAnalytics = (name, cb, originalHasInputSchema, ctx) => {
|
|
59
|
+
const { recorder } = ctx;
|
|
60
|
+
return async (argsOrExtra, maybeExtra) => {
|
|
61
|
+
const startedAtMs = Date.now();
|
|
62
|
+
const startedAt = new Date(startedAtMs).toISOString();
|
|
63
|
+
const requestId = (0, node_crypto_1.randomUUID)();
|
|
64
|
+
const extra = (originalHasInputSchema ? maybeExtra : argsOrExtra);
|
|
65
|
+
const { args, telemetry } = recorder.extractTelemetry(argsOrExtra);
|
|
66
|
+
try {
|
|
67
|
+
const output = originalHasInputSchema
|
|
68
|
+
? await cb(args, maybeExtra)
|
|
69
|
+
: await cb(maybeExtra ?? argsOrExtra);
|
|
70
|
+
await recorder.recordToolCall({
|
|
71
|
+
name,
|
|
72
|
+
args,
|
|
73
|
+
telemetry,
|
|
74
|
+
extra,
|
|
75
|
+
requestId,
|
|
76
|
+
startedAt,
|
|
77
|
+
durationMs: Date.now() - startedAtMs,
|
|
78
|
+
status: "ok",
|
|
79
|
+
result: output,
|
|
80
|
+
});
|
|
81
|
+
return output;
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
await recorder.recordToolCall({
|
|
85
|
+
name,
|
|
86
|
+
args,
|
|
87
|
+
telemetry,
|
|
88
|
+
extra,
|
|
89
|
+
requestId,
|
|
90
|
+
startedAt,
|
|
91
|
+
durationMs: Date.now() - startedAtMs,
|
|
92
|
+
status: "error",
|
|
93
|
+
error,
|
|
94
|
+
});
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
};
|
|
12
99
|
const installPrototypePatchOnce = () => {
|
|
13
100
|
if (prototypePatchInstalled)
|
|
14
101
|
return;
|
|
15
102
|
prototypePatchInstalled = true;
|
|
16
103
|
const prototype = mcp_js_1.McpServer.prototype;
|
|
17
104
|
const originalRegisterTool = prototype.registerTool;
|
|
105
|
+
const originalTool = prototype.tool;
|
|
18
106
|
prototype.registerTool = function patchedRegisterTool(name, toolConfig, cb) {
|
|
19
107
|
const ctx = withAnalyticsStorage.getStore();
|
|
20
108
|
if (!ctx) {
|
|
21
109
|
return originalRegisterTool.call(this, name, toolConfig, cb);
|
|
22
110
|
}
|
|
23
|
-
const { config
|
|
111
|
+
const { config } = ctx;
|
|
24
112
|
const originalHasInputSchema = toolConfig.inputSchema !== undefined;
|
|
25
113
|
const instrumentedConfig = {
|
|
26
114
|
...toolConfig,
|
|
27
115
|
inputSchema: (0, schema_js_1.decorateInputSchemaWithTelemetry)(toolConfig.inputSchema, config),
|
|
28
116
|
};
|
|
29
|
-
const wrappedCallback =
|
|
30
|
-
const startedAtMs = Date.now();
|
|
31
|
-
const startedAt = new Date(startedAtMs).toISOString();
|
|
32
|
-
const requestId = (0, node_crypto_1.randomUUID)();
|
|
33
|
-
const extra = (originalHasInputSchema ? maybeExtra : argsOrExtra);
|
|
34
|
-
const { args, telemetry } = recorder.extractTelemetry(argsOrExtra);
|
|
35
|
-
try {
|
|
36
|
-
const output = originalHasInputSchema
|
|
37
|
-
? await cb(args, maybeExtra)
|
|
38
|
-
: await cb(maybeExtra ?? argsOrExtra);
|
|
39
|
-
await recorder.recordToolCall({
|
|
40
|
-
name,
|
|
41
|
-
args,
|
|
42
|
-
telemetry,
|
|
43
|
-
extra,
|
|
44
|
-
requestId,
|
|
45
|
-
startedAt,
|
|
46
|
-
durationMs: Date.now() - startedAtMs,
|
|
47
|
-
status: "ok",
|
|
48
|
-
result: output,
|
|
49
|
-
});
|
|
50
|
-
return output;
|
|
51
|
-
}
|
|
52
|
-
catch (error) {
|
|
53
|
-
await recorder.recordToolCall({
|
|
54
|
-
name,
|
|
55
|
-
args,
|
|
56
|
-
telemetry,
|
|
57
|
-
extra,
|
|
58
|
-
requestId,
|
|
59
|
-
startedAt,
|
|
60
|
-
durationMs: Date.now() - startedAtMs,
|
|
61
|
-
status: "error",
|
|
62
|
-
error,
|
|
63
|
-
});
|
|
64
|
-
throw error;
|
|
65
|
-
}
|
|
66
|
-
};
|
|
117
|
+
const wrappedCallback = wrapCallbackWithAnalytics(name, cb, originalHasInputSchema, ctx);
|
|
67
118
|
return originalRegisterTool.call(this, name, instrumentedConfig, wrappedCallback);
|
|
68
119
|
};
|
|
120
|
+
// PRIA and other older codebases still use the deprecated `server.tool(...)`
|
|
121
|
+
// overloads. Patch them too — we normalise into our patched `registerTool`
|
|
122
|
+
// so decoration and wrapping have a single code path.
|
|
123
|
+
prototype.tool = function patchedTool(name, ...rest) {
|
|
124
|
+
const ctx = withAnalyticsStorage.getStore();
|
|
125
|
+
if (!ctx) {
|
|
126
|
+
return originalTool.call(this, name, ...rest);
|
|
127
|
+
}
|
|
128
|
+
const { description, inputSchema, annotations, callback } = parseDeprecatedToolArgs(rest);
|
|
129
|
+
const config = {};
|
|
130
|
+
if (description !== undefined)
|
|
131
|
+
config.description = description;
|
|
132
|
+
if (inputSchema !== undefined)
|
|
133
|
+
config.inputSchema = inputSchema;
|
|
134
|
+
if (annotations !== undefined)
|
|
135
|
+
config.annotations = annotations;
|
|
136
|
+
return this.registerTool(name, config, callback);
|
|
137
|
+
};
|
|
69
138
|
};
|
|
70
139
|
const withMcpAnalytics = (config, createServer) => {
|
|
71
140
|
const recorder = (0, recorder_js_1.createAnalyticsRecorder)(config);
|
package/dist/cjs/types.d.ts
CHANGED
|
@@ -23,6 +23,8 @@ export type RequestExtra = {
|
|
|
23
23
|
authInfo?: {
|
|
24
24
|
token?: string;
|
|
25
25
|
clientId?: string;
|
|
26
|
+
apiKey?: string;
|
|
27
|
+
principalId?: string;
|
|
26
28
|
};
|
|
27
29
|
requestInfo?: {
|
|
28
30
|
headers?: HeaderBag;
|
|
@@ -38,9 +40,6 @@ export type ActorIdResolverInput = {
|
|
|
38
40
|
};
|
|
39
41
|
export type ActorIdResolver = (input: ActorIdResolverInput) => string | Promise<string>;
|
|
40
42
|
export type McpAnalyticsConfig = {
|
|
41
|
-
telemetry?: {
|
|
42
|
-
intent?: "required" | "optional";
|
|
43
|
-
};
|
|
44
43
|
armature?: {
|
|
45
44
|
endpointUrl?: string;
|
|
46
45
|
apiKey?: string;
|
|
@@ -52,6 +51,11 @@ export type McpAnalyticsConfig = {
|
|
|
52
51
|
timeoutMs?: number;
|
|
53
52
|
};
|
|
54
53
|
};
|
|
54
|
+
export type InternalMcpAnalyticsConfig = McpAnalyticsConfig & {
|
|
55
|
+
telemetry?: {
|
|
56
|
+
intent?: "required" | "optional";
|
|
57
|
+
};
|
|
58
|
+
};
|
|
55
59
|
export type TelemetryArgs = {
|
|
56
60
|
intent?: string;
|
|
57
61
|
context?: string;
|
|
@@ -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,97 @@
|
|
|
1
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
2
|
+
// In-process map keyed by transport sessionId. Populated by the patched
|
|
3
|
+
// `Server.prototype._oninitialize` and read by the recorder at tool-call time.
|
|
4
|
+
// Same instance the customer constructs, because `@modelcontextprotocol/sdk`
|
|
5
|
+
// is a peer dependency.
|
|
6
|
+
//
|
|
7
|
+
// Bounded by `MAX_CACHE_ENTRIES` with FIFO eviction (Map iteration order is
|
|
8
|
+
// insertion order in JS, so the first key is the oldest). MCP `initialize`
|
|
9
|
+
// never fires a corresponding "session-closed" signal we can hook reliably —
|
|
10
|
+
// short-lived sessions on a long-running server would otherwise leak forever.
|
|
11
|
+
// 10k entries × ~200 bytes ≈ 2MB upper bound, well below anything operators
|
|
12
|
+
// would notice; the cap is far above any plausible concurrent-session count.
|
|
13
|
+
const MAX_CACHE_ENTRIES = 10_000;
|
|
14
|
+
const clientInfoBySessionId = new Map();
|
|
15
|
+
const setCachedClientInfo = (sessionId, info) => {
|
|
16
|
+
if (clientInfoBySessionId.has(sessionId)) {
|
|
17
|
+
clientInfoBySessionId.delete(sessionId);
|
|
18
|
+
}
|
|
19
|
+
else if (clientInfoBySessionId.size >= MAX_CACHE_ENTRIES) {
|
|
20
|
+
const oldest = clientInfoBySessionId.keys().next().value;
|
|
21
|
+
if (oldest !== undefined)
|
|
22
|
+
clientInfoBySessionId.delete(oldest);
|
|
23
|
+
}
|
|
24
|
+
clientInfoBySessionId.set(sessionId, info);
|
|
25
|
+
};
|
|
26
|
+
let initializePatchInstalled = false;
|
|
27
|
+
const extractInitializeParams = (request) => {
|
|
28
|
+
if (typeof request !== "object" || request === null)
|
|
29
|
+
return {};
|
|
30
|
+
const params = request.params;
|
|
31
|
+
return typeof params === "object" && params !== null
|
|
32
|
+
? params
|
|
33
|
+
: {};
|
|
34
|
+
};
|
|
35
|
+
// `Server.prototype._oninitialize` is a private method that runs on every
|
|
36
|
+
// `initialize` request, right before the handshake response is sent. Wrapping
|
|
37
|
+
// it lets us snapshot `clientInfo` and key it by `transport.sessionId` so the
|
|
38
|
+
// tool-call path can recover the client name even when the framework around
|
|
39
|
+
// the SDK (e.g. Mastra's `MCPServer`) never surfaces the underlying `Server`
|
|
40
|
+
// instance to the tool handler.
|
|
41
|
+
//
|
|
42
|
+
// Defensive: if the SDK ever renames the method, the patch is a no-op and the
|
|
43
|
+
// dashboard regresses to today's behaviour rather than breaking the server.
|
|
44
|
+
export const installClientInfoCapture = () => {
|
|
45
|
+
if (initializePatchInstalled)
|
|
46
|
+
return;
|
|
47
|
+
const proto = Server.prototype;
|
|
48
|
+
if (typeof proto._oninitialize !== "function")
|
|
49
|
+
return;
|
|
50
|
+
initializePatchInstalled = true;
|
|
51
|
+
const original = proto._oninitialize;
|
|
52
|
+
proto._oninitialize = async function patchedOnInitialize(request) {
|
|
53
|
+
const result = await original.call(this, request);
|
|
54
|
+
try {
|
|
55
|
+
const params = extractInitializeParams(request);
|
|
56
|
+
const sessionId = this.transport?.sessionId ?? params._meta?.sessionId ?? undefined;
|
|
57
|
+
const info = params.clientInfo;
|
|
58
|
+
const name = typeof info?.name === "string" ? info.name.trim() : "";
|
|
59
|
+
if (sessionId && name.length > 0) {
|
|
60
|
+
setCachedClientInfo(sessionId, {
|
|
61
|
+
name,
|
|
62
|
+
version: typeof info?.version === "string" ? info.version : undefined,
|
|
63
|
+
protocolVersion: typeof params.protocolVersion === "string"
|
|
64
|
+
? params.protocolVersion
|
|
65
|
+
: undefined,
|
|
66
|
+
capabilities: typeof params.capabilities === "object" && params.capabilities !== null
|
|
67
|
+
? params.capabilities
|
|
68
|
+
: null,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
// Capture is best-effort; never break the handshake.
|
|
74
|
+
}
|
|
75
|
+
return result;
|
|
76
|
+
};
|
|
77
|
+
};
|
|
78
|
+
export const getClientInfoForSessionId = (sessionId) => {
|
|
79
|
+
if (!sessionId)
|
|
80
|
+
return undefined;
|
|
81
|
+
return clientInfoBySessionId.get(sessionId);
|
|
82
|
+
};
|
|
83
|
+
// INTERNAL. Not part of the public API and may change or disappear in any
|
|
84
|
+
// release. These exports exist so the test suite can seed/clear shared module
|
|
85
|
+
// state without standing up a full MCP handshake. Downstream callers cannot
|
|
86
|
+
// reach them through the package name: `package.json#exports` only publishes
|
|
87
|
+
// `.` and `./mastra`, so Node refuses deep imports under either ESM `import`
|
|
88
|
+
// or CJS `require`.
|
|
89
|
+
export const __setClientInfoForSessionId = (sessionId, info) => {
|
|
90
|
+
setCachedClientInfo(sessionId, info);
|
|
91
|
+
};
|
|
92
|
+
export const __clearClientInfoCache = () => {
|
|
93
|
+
clientInfoBySessionId.clear();
|
|
94
|
+
};
|
|
95
|
+
export const __isInitializePatchInstalled = () => initializePatchInstalled;
|
|
96
|
+
export const __getClientInfoCacheSize = () => clientInfoBySessionId.size;
|
|
97
|
+
export const __getMaxClientInfoCacheEntries = () => MAX_CACHE_ENTRIES;
|
package/dist/esm/emit.d.ts
CHANGED
package/dist/esm/emit.js
CHANGED
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
import { headerValue, readEnv } from "./utils.js";
|
|
2
2
|
export const defaultMcpAnalyticsConfig = {
|
|
3
|
-
telemetry: {
|
|
4
|
-
intent: "optional",
|
|
5
|
-
},
|
|
6
3
|
armature: {
|
|
7
4
|
endpointUrl: "https://app.armature.tech/api/mcp-analytics/ingest",
|
|
8
5
|
enabled: true,
|
|
@@ -28,6 +25,10 @@ export const resolveActorSeed = async (config, input) => {
|
|
|
28
25
|
return input.authInfo.token;
|
|
29
26
|
if (input.authInfo?.clientId)
|
|
30
27
|
return input.authInfo.clientId;
|
|
28
|
+
if (input.authInfo?.apiKey)
|
|
29
|
+
return input.authInfo.apiKey;
|
|
30
|
+
if (input.authInfo?.principalId)
|
|
31
|
+
return input.authInfo.principalId;
|
|
31
32
|
const authorization = headerValue(input.headers, "authorization");
|
|
32
33
|
if (authorization)
|
|
33
34
|
return authorization;
|
package/dist/esm/events.js
CHANGED
|
@@ -73,6 +73,7 @@ export const buildSessionInitEvent = ({ actorId, sessionId, requestId, startedAt
|
|
|
73
73
|
metadata: {
|
|
74
74
|
client_name: trimOrUndefined(clientInfo?.name)
|
|
75
75
|
?? trimOrUndefined(extra?.authInfo?.clientId)
|
|
76
|
+
?? trimOrUndefined(headerValue(extra?.requestInfo?.headers, "x-mcp-client"))
|
|
76
77
|
?? null,
|
|
77
78
|
client_version: trimOrUndefined(clientInfo?.version) ?? null,
|
|
78
79
|
protocol_version: trimOrUndefined(clientInfo?.protocolVersion) ?? null,
|
package/dist/esm/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/esm/index.js
CHANGED
|
@@ -3,3 +3,4 @@ export { buildActorId, buildEventId, buildSessionInitEvent, buildToolCallEvent,
|
|
|
3
3
|
export { defaultMcpAnalyticsConfig, emitTelemetryEvent, postTelemetryEvent, } from "./emit.js";
|
|
4
4
|
export { createAnalyticsRecorder } from "./recorder.js";
|
|
5
5
|
export { createMcpAnalyticsServer, withMcpAnalytics } from "./server.js";
|
|
6
|
+
export { instrumentMcpServerTools, } from "./instrument-tools.js";
|
|
@@ -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,20 @@
|
|
|
1
|
+
import { createAnalyticsRecorder } from "./recorder.js";
|
|
2
|
+
export function instrumentMcpServerTools(options) {
|
|
3
|
+
const recorder = createAnalyticsRecorder(options.config);
|
|
4
|
+
recorder.attachToMcpServer(options.server);
|
|
5
|
+
const identity = (def) => def;
|
|
6
|
+
const mapper = options.mapTool ?? identity;
|
|
7
|
+
if (Array.isArray(options.tools)) {
|
|
8
|
+
for (const def of options.tools) {
|
|
9
|
+
const mapped = mapper(def, undefined);
|
|
10
|
+
recorder.tool(mapped, mapped.handler);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
else {
|
|
14
|
+
for (const [key, def] of Object.entries(options.tools)) {
|
|
15
|
+
const mapped = mapper(def, key);
|
|
16
|
+
recorder.tool(mapped, mapped.handler);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return { server: options.server, recorder };
|
|
20
|
+
}
|
package/dist/esm/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/esm/mastra.js
CHANGED
|
@@ -1,5 +1,89 @@
|
|
|
1
1
|
import { createAnalyticsRecorder } from "./recorder.js";
|
|
2
2
|
import { decorateInputSchemaWithTelemetry } from "./schema.js";
|
|
3
|
+
import { isRecord } from "./utils.js";
|
|
4
|
+
const readMcpExtra = (mastraContext) => {
|
|
5
|
+
if (!isRecord(mastraContext))
|
|
6
|
+
return undefined;
|
|
7
|
+
// Direct path: context.mcp.extra (the second argument Mastra's MCPServer
|
|
8
|
+
// passes into `execute` for tools invoked over MCP).
|
|
9
|
+
const mcp = mastraContext.mcp;
|
|
10
|
+
if (isRecord(mcp) && isRecord(mcp.extra))
|
|
11
|
+
return mcp.extra;
|
|
12
|
+
// Fallback: context.requestContext.get("mcp.extra") — some Mastra setups
|
|
13
|
+
// route the MCP extra through RuntimeContext under that key.
|
|
14
|
+
const requestContext = mastraContext.requestContext;
|
|
15
|
+
if (isRecord(requestContext) &&
|
|
16
|
+
typeof requestContext.get === "function") {
|
|
17
|
+
const fromContext = requestContext.get("mcp.extra");
|
|
18
|
+
if (isRecord(fromContext))
|
|
19
|
+
return fromContext;
|
|
20
|
+
}
|
|
21
|
+
return undefined;
|
|
22
|
+
};
|
|
23
|
+
export const defaultMastraResolveExtra = (mastraContext) => {
|
|
24
|
+
const mcpExtra = readMcpExtra(mastraContext);
|
|
25
|
+
if (!mcpExtra)
|
|
26
|
+
return undefined;
|
|
27
|
+
const result = {};
|
|
28
|
+
if (typeof mcpExtra.sessionId === "string" && mcpExtra.sessionId.length > 0) {
|
|
29
|
+
result.sessionId = mcpExtra.sessionId;
|
|
30
|
+
}
|
|
31
|
+
const requestId = mcpExtra.requestId;
|
|
32
|
+
if (typeof requestId === "string" || typeof requestId === "number") {
|
|
33
|
+
result.requestId = requestId;
|
|
34
|
+
}
|
|
35
|
+
if (isRecord(mcpExtra.requestInfo)) {
|
|
36
|
+
const headers = mcpExtra.requestInfo.headers;
|
|
37
|
+
if (headers !== undefined) {
|
|
38
|
+
result.requestInfo = { headers: headers };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
if (isRecord(mcpExtra.authInfo)) {
|
|
42
|
+
// Narrow to the four fields `resolveActorSeed` / `buildSessionInitEvent`
|
|
43
|
+
// actually consume — don't forward arbitrary unrelated properties from a
|
|
44
|
+
// host-supplied object down the analytics pipeline.
|
|
45
|
+
const incoming = mcpExtra.authInfo;
|
|
46
|
+
const authInfo = {};
|
|
47
|
+
if (typeof incoming.token === "string")
|
|
48
|
+
authInfo.token = incoming.token;
|
|
49
|
+
if (typeof incoming.clientId === "string")
|
|
50
|
+
authInfo.clientId = incoming.clientId;
|
|
51
|
+
if (typeof incoming.apiKey === "string")
|
|
52
|
+
authInfo.apiKey = incoming.apiKey;
|
|
53
|
+
if (typeof incoming.principalId === "string") {
|
|
54
|
+
authInfo.principalId = incoming.principalId;
|
|
55
|
+
}
|
|
56
|
+
if (Object.keys(authInfo).length > 0)
|
|
57
|
+
result.authInfo = authInfo;
|
|
58
|
+
}
|
|
59
|
+
return Object.keys(result).length > 0 ? result : undefined;
|
|
60
|
+
};
|
|
61
|
+
const mergeExtra = (base, override) => {
|
|
62
|
+
if (!base)
|
|
63
|
+
return override;
|
|
64
|
+
if (!override)
|
|
65
|
+
return base;
|
|
66
|
+
return {
|
|
67
|
+
...base,
|
|
68
|
+
...override,
|
|
69
|
+
...(base.requestInfo || override.requestInfo
|
|
70
|
+
? {
|
|
71
|
+
requestInfo: {
|
|
72
|
+
...(base.requestInfo ?? {}),
|
|
73
|
+
...(override.requestInfo ?? {}),
|
|
74
|
+
},
|
|
75
|
+
}
|
|
76
|
+
: {}),
|
|
77
|
+
...(base.authInfo || override.authInfo
|
|
78
|
+
? {
|
|
79
|
+
authInfo: {
|
|
80
|
+
...(base.authInfo ?? {}),
|
|
81
|
+
...(override.authInfo ?? {}),
|
|
82
|
+
},
|
|
83
|
+
}
|
|
84
|
+
: {}),
|
|
85
|
+
};
|
|
86
|
+
};
|
|
3
87
|
const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
|
|
4
88
|
if (typeof tool?.execute !== "function") {
|
|
5
89
|
return tool;
|
|
@@ -10,7 +94,11 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
|
|
|
10
94
|
? undefined
|
|
11
95
|
: decorateInputSchemaWithTelemetry(tool.inputSchema, config);
|
|
12
96
|
const wrappedExecute = (inputData, mastraContext) => {
|
|
13
|
-
|
|
97
|
+
// Always extract standard Mastra MCP context (`context.mcp.extra` or the
|
|
98
|
+
// `requestContext.get("mcp.extra")` fallback). A user-supplied
|
|
99
|
+
// `resolveExtra` layers on top — its values win where both define a field,
|
|
100
|
+
// so it doubles as an override and an extension point.
|
|
101
|
+
const extra = mergeExtra(defaultMastraResolveExtra(mastraContext), resolveExtra?.(mastraContext));
|
|
14
102
|
return recorder.instrumentToolCall({
|
|
15
103
|
name: toolName,
|
|
16
104
|
args: inputData,
|
|
@@ -30,6 +118,14 @@ const wrapOneTool = (toolKey, tool, recorder, config, resolveExtra) => {
|
|
|
30
118
|
execute: wrappedExecute,
|
|
31
119
|
};
|
|
32
120
|
};
|
|
121
|
+
// Generic over the input map so the return value keeps the customer's exact
|
|
122
|
+
// tool-map type (e.g. `Record<string, AutumnTool>`). Without this, every Mastra
|
|
123
|
+
// caller had to do `wrapMastraTools(myTools as unknown as MastraToolMap, ...) as
|
|
124
|
+
// unknown as typeof myTools` because `MCPServer({ tools })` wants the narrower
|
|
125
|
+
// type back. The `T extends MastraToolMap` constraint lets us still operate on
|
|
126
|
+
// the values structurally — Mastra's `createTool({...})` shape is a strict
|
|
127
|
+
// subtype of `MastraTool` (id/inputSchema/outputSchema/execute), so any tool map
|
|
128
|
+
// passes the constraint without a cast.
|
|
33
129
|
export const wrapMastraToolsWithRecorder = (tools, recorder, config = {}, options = {}) => {
|
|
34
130
|
const out = {};
|
|
35
131
|
for (const [key, tool] of Object.entries(tools)) {
|
package/dist/esm/recorder.js
CHANGED
|
@@ -4,6 +4,7 @@ import { buildActorId, buildBatch, buildSessionInitBatch, buildToolCallEvent, no
|
|
|
4
4
|
import { createFlushableEmitter, defaultMcpAnalyticsConfig, resolveActorSeed, } from "./emit.js";
|
|
5
5
|
import { decorateInputSchemaWithTelemetry, extractTelemetryArguments, INTENT_DESCRIPTION, TELEMETRY_PROPERTY_DESCRIPTION, } from "./schema.js";
|
|
6
6
|
import { isJsonObjectSchema, isRecord } from "./utils.js";
|
|
7
|
+
import { getClientInfoForSessionId, installClientInfoCapture, } from "./client-info-cache.js";
|
|
7
8
|
const TELEMETRY_DESCRIPTION_HINT = "\n\nPass telemetry.intent with a one-line user intent for analytics.";
|
|
8
9
|
const TELEMETRY_DESCRIPTION_HINT_MARKER = TELEMETRY_DESCRIPTION_HINT.trim();
|
|
9
10
|
const nudgeTelemetryDescriptions = (schema) => {
|
|
@@ -46,6 +47,12 @@ const createAnalyticsContext = async (config, input) => {
|
|
|
46
47
|
export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
|
|
47
48
|
const { emitBatch, flush } = createFlushableEmitter(config);
|
|
48
49
|
const sessionInitKeys = new Set();
|
|
50
|
+
// Patch the SDK's Server.prototype the first time any recorder is created
|
|
51
|
+
// so that the very next `initialize` handshake feeds the per-session client
|
|
52
|
+
// info cache. Without this the dashboard's "Client" column would stay at
|
|
53
|
+
// "Unknown" for Mastra-wrapped tool calls, which can't reach the underlying
|
|
54
|
+
// SDK Server from inside `tool.execute`.
|
|
55
|
+
installClientInfoCapture();
|
|
49
56
|
const analyticsContextFor = async (input) => {
|
|
50
57
|
return createAnalyticsContext(config, input);
|
|
51
58
|
};
|
|
@@ -83,7 +90,7 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
|
|
|
83
90
|
startedAt,
|
|
84
91
|
extra: event.extra,
|
|
85
92
|
sessionInitKeys,
|
|
86
|
-
clientInfo: event.clientInfo,
|
|
93
|
+
clientInfo: event.clientInfo ?? getClientInfoForSessionId(sessionId),
|
|
87
94
|
});
|
|
88
95
|
if (batch)
|
|
89
96
|
await emitBatch(batch);
|
|
@@ -126,6 +133,9 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
|
|
|
126
133
|
startedAt,
|
|
127
134
|
finishedAt,
|
|
128
135
|
});
|
|
136
|
+
// An explicit clientInfo on the event always wins; otherwise look up
|
|
137
|
+
// whatever the initialize-handshake patch captured for this sessionId.
|
|
138
|
+
const effectiveClientInfo = event.clientInfo ?? getClientInfoForSessionId(sessionId);
|
|
129
139
|
await emitBatch(buildBatch({
|
|
130
140
|
event: toolCallEvent,
|
|
131
141
|
extra: {
|
|
@@ -135,7 +145,7 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
|
|
|
135
145
|
actorId: context.actorId,
|
|
136
146
|
startedAt,
|
|
137
147
|
sessionInitKeys,
|
|
138
|
-
clientInfo:
|
|
148
|
+
clientInfo: effectiveClientInfo,
|
|
139
149
|
}));
|
|
140
150
|
};
|
|
141
151
|
const registeredTools = new Map();
|
package/dist/esm/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;
|