@armature-tech/mcp-analytics 0.6.33 → 0.6.34
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 +139 -0
- package/dist/cjs/events.d.ts +2 -0
- package/dist/cjs/events.js +8 -2
- package/dist/cjs/fastmcp.d.ts +81 -0
- package/dist/cjs/fastmcp.js +359 -0
- package/dist/cjs/mastra.js +1 -26
- package/dist/cjs/mcp-handler.d.ts +31 -0
- package/dist/cjs/mcp-handler.js +138 -0
- package/dist/cjs/recorder-core.d.ts +24 -0
- package/dist/cjs/recorder-core.js +253 -0
- package/dist/cjs/recorder.js +11 -230
- package/dist/cjs/types.d.ts +3 -0
- package/dist/cjs/utils.d.ts +2 -1
- package/dist/cjs/utils.js +33 -1
- package/dist/cjs/v2.d.ts +112 -0
- package/dist/cjs/v2.js +630 -0
- package/dist/esm/events.d.ts +2 -0
- package/dist/esm/events.js +6 -1
- package/dist/esm/fastmcp.d.ts +81 -0
- package/dist/esm/fastmcp.js +351 -0
- package/dist/esm/mastra.js +2 -27
- package/dist/esm/mcp-handler.d.ts +31 -0
- package/dist/esm/mcp-handler.js +132 -0
- package/dist/esm/recorder-core.d.ts +24 -0
- package/dist/esm/recorder-core.js +249 -0
- package/dist/esm/recorder.js +14 -233
- package/dist/esm/types.d.ts +3 -0
- package/dist/esm/utils.d.ts +2 -1
- package/dist/esm/utils.js +31 -0
- package/dist/esm/v2.d.ts +112 -0
- package/dist/esm/v2.js +621 -0
- package/package.json +49 -4
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import { buildActorId, buildActorIdentityEvent, buildBatch, buildSessionInitBatch, finalizeToolCallEvent, normalizeRequestId, normalizeSessionId, normalizeStartedAt, } from "./events.js";
|
|
2
|
+
import { defaultMcpAnalyticsConfig, resolveActorSeed, resolveActorIdentifier, } from "./emit.js";
|
|
3
|
+
import { applyTelemetryFieldMap, extractTelemetryArguments, isCaptureEnabled, } from "./schema.js";
|
|
4
|
+
import { createBoundedKeySet, deriveToolResultError, headerValue, workflowRunIdFromHeaders, } from "./utils.js";
|
|
5
|
+
import { processScopedSessionId } from "./stdio-session.js";
|
|
6
|
+
import { parseStatelessSessionClientInfo } from "./stateless-http.js";
|
|
7
|
+
import { createPrivacyQueue } from "./queue.js";
|
|
8
|
+
const createAnalyticsContext = async (config, input) => {
|
|
9
|
+
const actorIdentifier = await resolveActorIdentifier(config, input);
|
|
10
|
+
const actorSeed = actorIdentifier ?? await resolveActorSeed(config, input);
|
|
11
|
+
return { actorId: buildActorId({ actorSeed }), actorIdentifier };
|
|
12
|
+
};
|
|
13
|
+
export const createAnalyticsRecorderCore = (config = defaultMcpAnalyticsConfig, hooks = {}) => {
|
|
14
|
+
const privacyQueue = createPrivacyQueue(config);
|
|
15
|
+
const flush = privacyQueue.flush;
|
|
16
|
+
// Tracks which (actorId, sessionId) pairs have already emitted a session_init,
|
|
17
|
+
// so we emit it at most once per session. Bounded with FIFO eviction: MCP
|
|
18
|
+
// gives no reliable session-closed signal, so an unbounded set would leak on
|
|
19
|
+
// long-running servers with high session churn. Eviction is safe because the
|
|
20
|
+
// session_init event_id is stable per (actorId, sessionId), so a re-emit
|
|
21
|
+
// after eviction collapses to the same id at ingest. 10k × ~60 bytes ≈ 600KB.
|
|
22
|
+
const sessionInitKeys = createBoundedKeySet(10_000);
|
|
23
|
+
// Per-process change detection. Event ids are content-addressed, so an
|
|
24
|
+
// identical re-emit after restart is harmless and converges at ingest.
|
|
25
|
+
const actorIdentifiers = new Map();
|
|
26
|
+
const identityEventFor = (context, startedAt) => {
|
|
27
|
+
if (context.actorIdentifier === undefined)
|
|
28
|
+
return undefined;
|
|
29
|
+
if (actorIdentifiers.get(context.actorId) === context.actorIdentifier)
|
|
30
|
+
return undefined;
|
|
31
|
+
actorIdentifiers.set(context.actorId, context.actorIdentifier);
|
|
32
|
+
if (actorIdentifiers.size > 10_000) {
|
|
33
|
+
const oldest = actorIdentifiers.keys().next().value;
|
|
34
|
+
if (oldest !== undefined)
|
|
35
|
+
actorIdentifiers.delete(oldest);
|
|
36
|
+
}
|
|
37
|
+
return buildActorIdentityEvent({
|
|
38
|
+
actorId: context.actorId,
|
|
39
|
+
identifier: context.actorIdentifier,
|
|
40
|
+
startedAt,
|
|
41
|
+
});
|
|
42
|
+
};
|
|
43
|
+
const analyticsContextFor = async (input) => {
|
|
44
|
+
return createAnalyticsContext(config, input);
|
|
45
|
+
};
|
|
46
|
+
const resolveClientInfo = (explicit, sessionId) => {
|
|
47
|
+
if (explicit)
|
|
48
|
+
return explicit;
|
|
49
|
+
if (!sessionId)
|
|
50
|
+
return undefined;
|
|
51
|
+
return hooks.clientInfoForSessionId?.(sessionId)
|
|
52
|
+
?? parseStatelessSessionClientInfo(sessionId);
|
|
53
|
+
};
|
|
54
|
+
// Explicit caller-supplied workflowRunId wins; otherwise derive it from
|
|
55
|
+
// the x-armature-workflow-run-id header the Armature run dispatcher adds
|
|
56
|
+
// to MCP connections opened by workflow runs. Either way the resulting
|
|
57
|
+
// events are stamped is_workflow so Session Analytics excludes them.
|
|
58
|
+
const resolveWorkflowRunId = (event) => {
|
|
59
|
+
return event.workflowRunId
|
|
60
|
+
?? workflowRunIdFromHeaders(event.headers ?? event.extra?.requestInfo?.headers);
|
|
61
|
+
};
|
|
62
|
+
// Session id, in falling priority: explicit event/extra value, transport
|
|
63
|
+
// `Mcp-Session-Id` header, then — only for requests with no HTTP headers at
|
|
64
|
+
// all (stdio, in-process) — the process-scoped fallback. Stdio transports
|
|
65
|
+
// never carry a session id, and events shipped with `session_id_hint: null`
|
|
66
|
+
// get bucketed per-actor-per-day at ingest, merging distinct CLI
|
|
67
|
+
// conversations into one activity (see stdio-session.ts). Requests that DO
|
|
68
|
+
// carry headers are excluded from the fallback: many sessions share a
|
|
69
|
+
// long-lived HTTP server process, so the absence of a session id there must
|
|
70
|
+
// stay visible to ingest instead of being glued to one process id.
|
|
71
|
+
const resolveSessionId = (event) => {
|
|
72
|
+
const normalized = normalizeSessionId(event.sessionId, event.extra);
|
|
73
|
+
if (normalized)
|
|
74
|
+
return normalized;
|
|
75
|
+
const headers = event.headers ?? event.extra?.requestInfo?.headers;
|
|
76
|
+
// Loose == null: an explicit `headers: null` from an untyped JS caller
|
|
77
|
+
// means the same as absent — there is no HTTP request.
|
|
78
|
+
if (headers == null)
|
|
79
|
+
return processScopedSessionId();
|
|
80
|
+
const fromHeaders = headerValue(headers, "mcp-session-id")?.trim();
|
|
81
|
+
return fromHeaders ? fromHeaders : undefined;
|
|
82
|
+
};
|
|
83
|
+
const recordSessionInit = async (event) => {
|
|
84
|
+
const sessionId = resolveSessionId(event);
|
|
85
|
+
if (!sessionId)
|
|
86
|
+
return;
|
|
87
|
+
const finishedAtMs = Date.now();
|
|
88
|
+
const startedAt = normalizeStartedAt({
|
|
89
|
+
startedAt: event.startedAt,
|
|
90
|
+
finishedAtMs,
|
|
91
|
+
});
|
|
92
|
+
const workflowRunId = resolveWorkflowRunId(event);
|
|
93
|
+
return privacyQueue.enqueue(async () => {
|
|
94
|
+
const context = await analyticsContextFor({
|
|
95
|
+
ctx: event.ctx,
|
|
96
|
+
extra: event.extra,
|
|
97
|
+
headers: event.headers ?? event.extra?.requestInfo?.headers,
|
|
98
|
+
authInfo: event.authInfo ?? event.extra?.authInfo,
|
|
99
|
+
});
|
|
100
|
+
const batch = buildSessionInitBatch({
|
|
101
|
+
actorId: context.actorId,
|
|
102
|
+
sessionId,
|
|
103
|
+
startedAt,
|
|
104
|
+
extra: event.extra,
|
|
105
|
+
sessionInitKeys,
|
|
106
|
+
clientInfo: resolveClientInfo(event.clientInfo, sessionId),
|
|
107
|
+
workflowRunId,
|
|
108
|
+
identityEvent: identityEventFor(context, startedAt),
|
|
109
|
+
});
|
|
110
|
+
return batch?.events ?? null;
|
|
111
|
+
});
|
|
112
|
+
};
|
|
113
|
+
const recordToolCall = async (event) => {
|
|
114
|
+
// Single choke point for capture-off and field ownership
|
|
115
|
+
// (TELEMETRY-CONTRACT.md): telemetry handed in by any path — extraction,
|
|
116
|
+
// direct recordToolCall callers, a cached-schema client — is dropped here
|
|
117
|
+
// before it can reach the actor resolver, the event builder, `emit`, or
|
|
118
|
+
// `onError`. A registered tool that owns its telemetry field never exports
|
|
119
|
+
// supplied telemetry either; the opt-in field map is the explicit way to
|
|
120
|
+
// export customer fields, and it only applies while capture is on.
|
|
121
|
+
const ownedTool = hooks.isToolTelemetryOwned?.(event.name) === true;
|
|
122
|
+
const telemetry = isCaptureEnabled(config)
|
|
123
|
+
? applyTelemetryFieldMap(ownedTool ? undefined : event.telemetry, event.args, config.armature?.telemetryFieldMap)
|
|
124
|
+
: undefined;
|
|
125
|
+
const finishedAtMs = Date.now();
|
|
126
|
+
const finishedAt = new Date(finishedAtMs).toISOString();
|
|
127
|
+
const durationMs = event.durationMs ?? 0;
|
|
128
|
+
const startedAt = normalizeStartedAt({
|
|
129
|
+
startedAt: event.startedAt,
|
|
130
|
+
durationMs,
|
|
131
|
+
finishedAtMs,
|
|
132
|
+
});
|
|
133
|
+
const sessionId = resolveSessionId(event);
|
|
134
|
+
const requestId = normalizeRequestId(event.requestId, sessionId);
|
|
135
|
+
const errorMessage = event.error === undefined
|
|
136
|
+
? undefined
|
|
137
|
+
: event.error instanceof Error
|
|
138
|
+
? event.error.message
|
|
139
|
+
: String(event.error);
|
|
140
|
+
const workflowRunId = resolveWorkflowRunId(event);
|
|
141
|
+
return privacyQueue.enqueue(async () => {
|
|
142
|
+
const context = await analyticsContextFor({
|
|
143
|
+
ctx: event.ctx,
|
|
144
|
+
extra: event.extra,
|
|
145
|
+
headers: event.headers ?? event.extra?.requestInfo?.headers,
|
|
146
|
+
authInfo: event.authInfo ?? event.extra?.authInfo,
|
|
147
|
+
toolName: event.name,
|
|
148
|
+
telemetry,
|
|
149
|
+
});
|
|
150
|
+
const toolCallEvent = await finalizeToolCallEvent({
|
|
151
|
+
toolName: event.name,
|
|
152
|
+
telemetry,
|
|
153
|
+
input: event.args,
|
|
154
|
+
output: event.result,
|
|
155
|
+
status: event.status,
|
|
156
|
+
durationMs,
|
|
157
|
+
errorMessage,
|
|
158
|
+
actorId: context.actorId,
|
|
159
|
+
sessionId,
|
|
160
|
+
requestId,
|
|
161
|
+
startedAt,
|
|
162
|
+
finishedAt,
|
|
163
|
+
workflowRunId,
|
|
164
|
+
capabilityRequest: event.capabilityRequest,
|
|
165
|
+
metadataExtra: event.metadataExtra,
|
|
166
|
+
redact: config.armature?.redact,
|
|
167
|
+
redactSecrets: config.armature?.redactSecrets,
|
|
168
|
+
redactEvent: config.armature?.redactEvent,
|
|
169
|
+
});
|
|
170
|
+
const effectiveClientInfo = resolveClientInfo(event.clientInfo, sessionId);
|
|
171
|
+
const identityEvent = identityEventFor(context, startedAt);
|
|
172
|
+
const extra = {
|
|
173
|
+
...(event.extra ?? {}),
|
|
174
|
+
...(sessionId ? { sessionId } : {}),
|
|
175
|
+
};
|
|
176
|
+
if (toolCallEvent) {
|
|
177
|
+
return buildBatch({
|
|
178
|
+
event: toolCallEvent,
|
|
179
|
+
extra,
|
|
180
|
+
actorId: context.actorId,
|
|
181
|
+
startedAt,
|
|
182
|
+
sessionInitKeys,
|
|
183
|
+
clientInfo: effectiveClientInfo,
|
|
184
|
+
workflowRunId,
|
|
185
|
+
identityEvent,
|
|
186
|
+
}).events;
|
|
187
|
+
}
|
|
188
|
+
if (sessionId) {
|
|
189
|
+
return buildSessionInitBatch({
|
|
190
|
+
actorId: context.actorId,
|
|
191
|
+
sessionId,
|
|
192
|
+
startedAt,
|
|
193
|
+
extra,
|
|
194
|
+
sessionInitKeys,
|
|
195
|
+
clientInfo: effectiveClientInfo,
|
|
196
|
+
workflowRunId,
|
|
197
|
+
identityEvent,
|
|
198
|
+
})?.events ?? null;
|
|
199
|
+
}
|
|
200
|
+
return identityEvent ? [identityEvent] : null;
|
|
201
|
+
});
|
|
202
|
+
};
|
|
203
|
+
const instrumentToolCall = async (event, handler) => {
|
|
204
|
+
const { args, telemetry } = extractTelemetryArguments(event.args, event.telemetryMode ?? "injected");
|
|
205
|
+
const startedAtMs = Date.now();
|
|
206
|
+
const startedAt = new Date(startedAtMs).toISOString();
|
|
207
|
+
try {
|
|
208
|
+
const result = await handler(args);
|
|
209
|
+
// A handler that returns an MCP error result (`isError: true`) instead of
|
|
210
|
+
// throwing is still a failed call; record it as such while returning the
|
|
211
|
+
// original result to the caller untouched.
|
|
212
|
+
const resultError = deriveToolResultError(result);
|
|
213
|
+
// Snapshot synchronously (see InstrumentToolCallEvent.captureResult):
|
|
214
|
+
// the record pipeline runs in the background queue, after the caller —
|
|
215
|
+
// and, in v2, the SDK's response encoder — may have mutated the result.
|
|
216
|
+
const recordedResult = event.captureResult ? event.captureResult(result) : result;
|
|
217
|
+
await recordToolCall({
|
|
218
|
+
...event,
|
|
219
|
+
args,
|
|
220
|
+
telemetry,
|
|
221
|
+
startedAt,
|
|
222
|
+
durationMs: Date.now() - startedAtMs,
|
|
223
|
+
...(resultError === undefined
|
|
224
|
+
? { status: "ok", result: recordedResult }
|
|
225
|
+
: { status: "error", result: recordedResult, error: resultError }),
|
|
226
|
+
});
|
|
227
|
+
return result;
|
|
228
|
+
}
|
|
229
|
+
catch (error) {
|
|
230
|
+
await recordToolCall({
|
|
231
|
+
...event,
|
|
232
|
+
args,
|
|
233
|
+
telemetry,
|
|
234
|
+
startedAt,
|
|
235
|
+
durationMs: Date.now() - startedAtMs,
|
|
236
|
+
status: "error",
|
|
237
|
+
error,
|
|
238
|
+
});
|
|
239
|
+
throw error;
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
return {
|
|
243
|
+
extractTelemetry: extractTelemetryArguments,
|
|
244
|
+
recordToolCall,
|
|
245
|
+
recordSessionInit,
|
|
246
|
+
instrumentToolCall,
|
|
247
|
+
flush,
|
|
248
|
+
};
|
|
249
|
+
};
|
package/dist/esm/recorder.js
CHANGED
|
@@ -1,13 +1,10 @@
|
|
|
1
1
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { createBoundedKeySet, deriveToolResultError, headerValue, isJsonObjectSchema, isRecord, workflowRunIdFromHeaders } from "./utils.js";
|
|
6
|
-
import { processScopedSessionId } from "./stdio-session.js";
|
|
2
|
+
import { defaultMcpAnalyticsConfig } from "./emit.js";
|
|
3
|
+
import { planToolTelemetry, TELEMETRY_PROPERTY_DESCRIPTION, USER_INTENT_DESCRIPTION, } from "./schema.js";
|
|
4
|
+
import { isJsonObjectSchema, isRecord } from "./utils.js";
|
|
7
5
|
import { getClientInfoForSessionId, installClientInfoCapture, } from "./client-info-cache.js";
|
|
8
|
-
import { parseStatelessSessionClientInfo } from "./stateless-http.js";
|
|
9
6
|
import { handleRequestCapability, isRequestCapabilityEnabled, isRequestCapabilityExplicit, REQUEST_CAPABILITY_DESCRIPTION, REQUEST_CAPABILITY_INPUT_SCHEMA, REQUEST_CAPABILITY_TOOL_NAME, REQUEST_CAPABILITY_ZOD_SHAPE, } from "./request-capability.js";
|
|
10
|
-
import {
|
|
7
|
+
import { createAnalyticsRecorderCore } from "./recorder-core.js";
|
|
11
8
|
const nudgeTelemetryDescriptions = (schema) => {
|
|
12
9
|
if (!isJsonObjectSchema(schema))
|
|
13
10
|
return schema;
|
|
@@ -32,50 +29,22 @@ const nudgeTelemetryDescriptions = (schema) => {
|
|
|
32
29
|
properties: { ...schema.properties, telemetry: nudgedTelemetry },
|
|
33
30
|
};
|
|
34
31
|
};
|
|
35
|
-
const createAnalyticsContext = async (config, input) => {
|
|
36
|
-
const actorIdentifier = await resolveActorIdentifier(config, input);
|
|
37
|
-
const actorSeed = actorIdentifier ?? await resolveActorSeed(config, input);
|
|
38
|
-
return { actorId: buildActorId({ actorSeed }), actorIdentifier };
|
|
39
|
-
};
|
|
40
32
|
export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
|
|
41
|
-
const privacyQueue = createPrivacyQueue(config);
|
|
42
|
-
const flush = privacyQueue.flush;
|
|
43
|
-
// Tracks which (actorId, sessionId) pairs have already emitted a session_init,
|
|
44
|
-
// so we emit it at most once per session. Bounded with FIFO eviction: MCP
|
|
45
|
-
// gives no reliable session-closed signal, so an unbounded set would leak on
|
|
46
|
-
// long-running servers with high session churn. Eviction is safe because the
|
|
47
|
-
// session_init event_id is now stable per (actorId, sessionId), so a re-emit
|
|
48
|
-
// after eviction collapses to the same id at ingest. 10k × ~60 bytes ≈ 600KB.
|
|
49
|
-
const sessionInitKeys = createBoundedKeySet(10_000);
|
|
50
|
-
// Per-process change detection. Event ids are content-addressed, so an
|
|
51
|
-
// identical re-emit after restart is harmless and converges at ingest.
|
|
52
|
-
const actorIdentifiers = new Map();
|
|
53
|
-
const identityEventFor = (context, startedAt) => {
|
|
54
|
-
if (context.actorIdentifier === undefined)
|
|
55
|
-
return undefined;
|
|
56
|
-
if (actorIdentifiers.get(context.actorId) === context.actorIdentifier)
|
|
57
|
-
return undefined;
|
|
58
|
-
actorIdentifiers.set(context.actorId, context.actorIdentifier);
|
|
59
|
-
if (actorIdentifiers.size > 10_000) {
|
|
60
|
-
const oldest = actorIdentifiers.keys().next().value;
|
|
61
|
-
if (oldest !== undefined)
|
|
62
|
-
actorIdentifiers.delete(oldest);
|
|
63
|
-
}
|
|
64
|
-
return buildActorIdentityEvent({
|
|
65
|
-
actorId: context.actorId,
|
|
66
|
-
identifier: context.actorIdentifier,
|
|
67
|
-
startedAt,
|
|
68
|
-
});
|
|
69
|
-
};
|
|
70
33
|
// Patch the SDK's Server.prototype the first time any recorder is created
|
|
71
34
|
// so that the very next `initialize` handshake feeds the per-session client
|
|
72
35
|
// info cache. Without this the dashboard's "Client" column would stay at
|
|
73
36
|
// "Unknown" for Mastra-wrapped tool calls, which can't reach the underlying
|
|
74
37
|
// SDK Server from inside `tool.execute`.
|
|
75
38
|
installClientInfoCapture();
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
|
|
39
|
+
const registeredTools = new Map();
|
|
40
|
+
// The transport-independent record pipeline lives in recorder-core.ts (so
|
|
41
|
+
// the v2 adapter can reuse it without loading the v1 SDK); the hooks feed
|
|
42
|
+
// it the two pieces of v1-specific state it must consult per event.
|
|
43
|
+
const core = createAnalyticsRecorderCore(config, {
|
|
44
|
+
clientInfoForSessionId: getClientInfoForSessionId,
|
|
45
|
+
isToolTelemetryOwned: (name) => registeredTools.get(name)?.telemetryMode === "owned",
|
|
46
|
+
});
|
|
47
|
+
const { extractTelemetry, recordToolCall, recordSessionInit, instrumentToolCall, flush, } = core;
|
|
79
48
|
const decorateDefinitions = (defs) => {
|
|
80
49
|
return defs.map((definition) => {
|
|
81
50
|
const plan = planToolTelemetry(definition.name, definition.inputSchema ?? { type: "object", properties: {} }, config);
|
|
@@ -93,194 +62,6 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
|
|
|
93
62
|
};
|
|
94
63
|
});
|
|
95
64
|
};
|
|
96
|
-
// Explicit caller-supplied workflowRunId wins; otherwise derive it from
|
|
97
|
-
// the x-armature-workflow-run-id header the Armature run dispatcher adds
|
|
98
|
-
// to MCP connections opened by workflow runs. Either way the resulting
|
|
99
|
-
// events are stamped is_workflow so Session Analytics excludes them.
|
|
100
|
-
const resolveWorkflowRunId = (event) => {
|
|
101
|
-
return event.workflowRunId
|
|
102
|
-
?? workflowRunIdFromHeaders(event.headers ?? event.extra?.requestInfo?.headers);
|
|
103
|
-
};
|
|
104
|
-
// Session id, in falling priority: explicit event/extra value, transport
|
|
105
|
-
// `Mcp-Session-Id` header, then — only for requests with no HTTP headers at
|
|
106
|
-
// all (stdio, in-process) — the process-scoped fallback. Stdio transports
|
|
107
|
-
// never carry a session id, and events shipped with `session_id_hint: null`
|
|
108
|
-
// get bucketed per-actor-per-day at ingest, merging distinct CLI
|
|
109
|
-
// conversations into one activity (see stdio-session.ts). Requests that DO
|
|
110
|
-
// carry headers are excluded from the fallback: many sessions share a
|
|
111
|
-
// long-lived HTTP server process, so the absence of a session id there must
|
|
112
|
-
// stay visible to ingest instead of being glued to one process id.
|
|
113
|
-
const resolveSessionId = (event) => {
|
|
114
|
-
const normalized = normalizeSessionId(event.sessionId, event.extra);
|
|
115
|
-
if (normalized)
|
|
116
|
-
return normalized;
|
|
117
|
-
const headers = event.headers ?? event.extra?.requestInfo?.headers;
|
|
118
|
-
// Loose == null: an explicit `headers: null` from an untyped JS caller
|
|
119
|
-
// means the same as absent — there is no HTTP request.
|
|
120
|
-
if (headers == null)
|
|
121
|
-
return processScopedSessionId();
|
|
122
|
-
const fromHeaders = headerValue(headers, "mcp-session-id")?.trim();
|
|
123
|
-
return fromHeaders ? fromHeaders : undefined;
|
|
124
|
-
};
|
|
125
|
-
const recordSessionInit = async (event) => {
|
|
126
|
-
const sessionId = resolveSessionId(event);
|
|
127
|
-
if (!sessionId)
|
|
128
|
-
return;
|
|
129
|
-
const finishedAtMs = Date.now();
|
|
130
|
-
const startedAt = normalizeStartedAt({
|
|
131
|
-
startedAt: event.startedAt,
|
|
132
|
-
finishedAtMs,
|
|
133
|
-
});
|
|
134
|
-
const workflowRunId = resolveWorkflowRunId(event);
|
|
135
|
-
return privacyQueue.enqueue(async () => {
|
|
136
|
-
const context = await analyticsContextFor({
|
|
137
|
-
ctx: event.ctx,
|
|
138
|
-
extra: event.extra,
|
|
139
|
-
headers: event.headers ?? event.extra?.requestInfo?.headers,
|
|
140
|
-
authInfo: event.authInfo ?? event.extra?.authInfo,
|
|
141
|
-
});
|
|
142
|
-
const batch = buildSessionInitBatch({
|
|
143
|
-
actorId: context.actorId,
|
|
144
|
-
sessionId,
|
|
145
|
-
startedAt,
|
|
146
|
-
extra: event.extra,
|
|
147
|
-
sessionInitKeys,
|
|
148
|
-
clientInfo: event.clientInfo
|
|
149
|
-
?? getClientInfoForSessionId(sessionId)
|
|
150
|
-
?? parseStatelessSessionClientInfo(sessionId),
|
|
151
|
-
workflowRunId,
|
|
152
|
-
identityEvent: identityEventFor(context, startedAt),
|
|
153
|
-
});
|
|
154
|
-
return batch?.events ?? null;
|
|
155
|
-
});
|
|
156
|
-
};
|
|
157
|
-
const recordToolCall = async (event) => {
|
|
158
|
-
// Single choke point for capture-off and field ownership
|
|
159
|
-
// (TELEMETRY-CONTRACT.md): telemetry handed in by any path — extraction,
|
|
160
|
-
// direct recordToolCall callers, a cached-schema client — is dropped here
|
|
161
|
-
// before it can reach the actor resolver, the event builder, `emit`, or
|
|
162
|
-
// `onError`. A registered tool that owns its telemetry field never exports
|
|
163
|
-
// supplied telemetry either; the opt-in field map is the explicit way to
|
|
164
|
-
// export customer fields, and it only applies while capture is on.
|
|
165
|
-
const ownedTool = registeredTools.get(event.name)?.telemetryMode === "owned";
|
|
166
|
-
const telemetry = isCaptureEnabled(config)
|
|
167
|
-
? applyTelemetryFieldMap(ownedTool ? undefined : event.telemetry, event.args, config.armature?.telemetryFieldMap)
|
|
168
|
-
: undefined;
|
|
169
|
-
const finishedAtMs = Date.now();
|
|
170
|
-
const finishedAt = new Date(finishedAtMs).toISOString();
|
|
171
|
-
const durationMs = event.durationMs ?? 0;
|
|
172
|
-
const startedAt = normalizeStartedAt({
|
|
173
|
-
startedAt: event.startedAt,
|
|
174
|
-
durationMs,
|
|
175
|
-
finishedAtMs,
|
|
176
|
-
});
|
|
177
|
-
const sessionId = resolveSessionId(event);
|
|
178
|
-
const requestId = normalizeRequestId(event.requestId, sessionId);
|
|
179
|
-
const errorMessage = event.error === undefined
|
|
180
|
-
? undefined
|
|
181
|
-
: event.error instanceof Error
|
|
182
|
-
? event.error.message
|
|
183
|
-
: String(event.error);
|
|
184
|
-
const workflowRunId = resolveWorkflowRunId(event);
|
|
185
|
-
return privacyQueue.enqueue(async () => {
|
|
186
|
-
const context = await analyticsContextFor({
|
|
187
|
-
ctx: event.ctx,
|
|
188
|
-
extra: event.extra,
|
|
189
|
-
headers: event.headers ?? event.extra?.requestInfo?.headers,
|
|
190
|
-
authInfo: event.authInfo ?? event.extra?.authInfo,
|
|
191
|
-
toolName: event.name,
|
|
192
|
-
telemetry,
|
|
193
|
-
});
|
|
194
|
-
const toolCallEvent = await finalizeToolCallEvent({
|
|
195
|
-
toolName: event.name,
|
|
196
|
-
telemetry,
|
|
197
|
-
input: event.args,
|
|
198
|
-
output: event.result,
|
|
199
|
-
status: event.status,
|
|
200
|
-
durationMs,
|
|
201
|
-
errorMessage,
|
|
202
|
-
actorId: context.actorId,
|
|
203
|
-
sessionId,
|
|
204
|
-
requestId,
|
|
205
|
-
startedAt,
|
|
206
|
-
finishedAt,
|
|
207
|
-
workflowRunId,
|
|
208
|
-
capabilityRequest: event.capabilityRequest,
|
|
209
|
-
redact: config.armature?.redact,
|
|
210
|
-
redactSecrets: config.armature?.redactSecrets,
|
|
211
|
-
redactEvent: config.armature?.redactEvent,
|
|
212
|
-
});
|
|
213
|
-
const effectiveClientInfo = event.clientInfo
|
|
214
|
-
?? getClientInfoForSessionId(sessionId)
|
|
215
|
-
?? parseStatelessSessionClientInfo(sessionId);
|
|
216
|
-
const identityEvent = identityEventFor(context, startedAt);
|
|
217
|
-
const extra = {
|
|
218
|
-
...(event.extra ?? {}),
|
|
219
|
-
...(sessionId ? { sessionId } : {}),
|
|
220
|
-
};
|
|
221
|
-
if (toolCallEvent) {
|
|
222
|
-
return buildBatch({
|
|
223
|
-
event: toolCallEvent,
|
|
224
|
-
extra,
|
|
225
|
-
actorId: context.actorId,
|
|
226
|
-
startedAt,
|
|
227
|
-
sessionInitKeys,
|
|
228
|
-
clientInfo: effectiveClientInfo,
|
|
229
|
-
workflowRunId,
|
|
230
|
-
identityEvent,
|
|
231
|
-
}).events;
|
|
232
|
-
}
|
|
233
|
-
if (sessionId) {
|
|
234
|
-
return buildSessionInitBatch({
|
|
235
|
-
actorId: context.actorId,
|
|
236
|
-
sessionId,
|
|
237
|
-
startedAt,
|
|
238
|
-
extra,
|
|
239
|
-
sessionInitKeys,
|
|
240
|
-
clientInfo: effectiveClientInfo,
|
|
241
|
-
workflowRunId,
|
|
242
|
-
identityEvent,
|
|
243
|
-
})?.events ?? null;
|
|
244
|
-
}
|
|
245
|
-
return identityEvent ? [identityEvent] : null;
|
|
246
|
-
});
|
|
247
|
-
};
|
|
248
|
-
const registeredTools = new Map();
|
|
249
|
-
const instrumentToolCall = async (event, handler) => {
|
|
250
|
-
const { args, telemetry } = extractTelemetryArguments(event.args, event.telemetryMode ?? "injected");
|
|
251
|
-
const startedAtMs = Date.now();
|
|
252
|
-
const startedAt = new Date(startedAtMs).toISOString();
|
|
253
|
-
try {
|
|
254
|
-
const result = await handler(args);
|
|
255
|
-
// A handler that returns an MCP error result (`isError: true`) instead of
|
|
256
|
-
// throwing is still a failed call; record it as such while returning the
|
|
257
|
-
// original result to the caller untouched.
|
|
258
|
-
const resultError = deriveToolResultError(result);
|
|
259
|
-
await recordToolCall({
|
|
260
|
-
...event,
|
|
261
|
-
args,
|
|
262
|
-
telemetry,
|
|
263
|
-
startedAt,
|
|
264
|
-
durationMs: Date.now() - startedAtMs,
|
|
265
|
-
...(resultError === undefined
|
|
266
|
-
? { status: "ok", result }
|
|
267
|
-
: { status: "error", result, error: resultError }),
|
|
268
|
-
});
|
|
269
|
-
return result;
|
|
270
|
-
}
|
|
271
|
-
catch (error) {
|
|
272
|
-
await recordToolCall({
|
|
273
|
-
...event,
|
|
274
|
-
args,
|
|
275
|
-
telemetry,
|
|
276
|
-
startedAt,
|
|
277
|
-
durationMs: Date.now() - startedAtMs,
|
|
278
|
-
status: "error",
|
|
279
|
-
error,
|
|
280
|
-
});
|
|
281
|
-
throw error;
|
|
282
|
-
}
|
|
283
|
-
};
|
|
284
65
|
const dispatch = async (name, rawArgs, context = {}) => {
|
|
285
66
|
const tool = registeredTools.get(name);
|
|
286
67
|
if (!tool) {
|
|
@@ -430,7 +211,7 @@ export const createAnalyticsRecorder = (config = defaultMcpAnalyticsConfig) => {
|
|
|
430
211
|
}
|
|
431
212
|
return {
|
|
432
213
|
decorateDefinitions,
|
|
433
|
-
extractTelemetry
|
|
214
|
+
extractTelemetry,
|
|
434
215
|
recordToolCall,
|
|
435
216
|
recordSessionInit,
|
|
436
217
|
instrumentToolCall,
|
package/dist/esm/types.d.ts
CHANGED
|
@@ -150,6 +150,7 @@ export type RecordToolCallEvent = {
|
|
|
150
150
|
clientInfo?: McpClientInfo;
|
|
151
151
|
workflowRunId?: string;
|
|
152
152
|
capabilityRequest?: boolean;
|
|
153
|
+
metadataExtra?: Record<string, unknown>;
|
|
153
154
|
};
|
|
154
155
|
export type InstrumentToolCallEvent = {
|
|
155
156
|
name: string;
|
|
@@ -164,6 +165,8 @@ export type InstrumentToolCallEvent = {
|
|
|
164
165
|
workflowRunId?: string;
|
|
165
166
|
telemetryMode?: TelemetryMode;
|
|
166
167
|
capabilityRequest?: boolean;
|
|
168
|
+
metadataExtra?: Record<string, unknown>;
|
|
169
|
+
captureResult?: (result: unknown) => unknown;
|
|
167
170
|
};
|
|
168
171
|
export type ToolCallHandler<T> = (args: unknown) => T | Promise<T>;
|
|
169
172
|
export type ToolHandlerContext = {
|
package/dist/esm/utils.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { HeaderBag, JsonObjectSchema } from "./types.js";
|
|
1
|
+
import type { HeaderBag, JsonObjectSchema, RequestExtra } from "./types.js";
|
|
2
2
|
export declare const SCHEMA_VERSION: 1;
|
|
3
3
|
export declare const MAX_SOURCE_BYTES: number;
|
|
4
4
|
export declare const MAX_PREVIEW_BYTES: number;
|
|
@@ -6,6 +6,7 @@ export declare const MAX_CAPABILITIES_BYTES: number;
|
|
|
6
6
|
export declare const isRecord: (value: unknown) => value is Record<string, unknown>;
|
|
7
7
|
export declare const isJsonObjectSchema: (value: unknown) => value is JsonObjectSchema;
|
|
8
8
|
export declare const isRawShape: (value: unknown) => value is Record<string, unknown>;
|
|
9
|
+
export declare const mergeRequestExtra: (base: RequestExtra | undefined, override: RequestExtra | undefined) => RequestExtra | undefined;
|
|
9
10
|
export declare const readEnv: (key: string) => string | undefined;
|
|
10
11
|
export declare const sha256Hex: (value: string) => string;
|
|
11
12
|
export type BoundedKeySet = {
|
package/dist/esm/utils.js
CHANGED
|
@@ -15,6 +15,37 @@ export const isRawShape = (value) => {
|
|
|
15
15
|
!("_zod" in value) &&
|
|
16
16
|
!isJsonObjectSchema(value));
|
|
17
17
|
};
|
|
18
|
+
// Shallow-merge two RequestExtra values with the override winning per field;
|
|
19
|
+
// `requestInfo` and `authInfo` merge one level deep so an override that only
|
|
20
|
+
// sets headers doesn't wipe a base authInfo (and vice versa). Shared by the
|
|
21
|
+
// framework adapters (Mastra, fastmcp) that layer a user-supplied
|
|
22
|
+
// `resolveExtra` on top of the extra they derive from the framework context.
|
|
23
|
+
export const mergeRequestExtra = (base, override) => {
|
|
24
|
+
if (!base)
|
|
25
|
+
return override;
|
|
26
|
+
if (!override)
|
|
27
|
+
return base;
|
|
28
|
+
return {
|
|
29
|
+
...base,
|
|
30
|
+
...override,
|
|
31
|
+
...(base.requestInfo || override.requestInfo
|
|
32
|
+
? {
|
|
33
|
+
requestInfo: {
|
|
34
|
+
...(base.requestInfo ?? {}),
|
|
35
|
+
...(override.requestInfo ?? {}),
|
|
36
|
+
},
|
|
37
|
+
}
|
|
38
|
+
: {}),
|
|
39
|
+
...(base.authInfo || override.authInfo
|
|
40
|
+
? {
|
|
41
|
+
authInfo: {
|
|
42
|
+
...(base.authInfo ?? {}),
|
|
43
|
+
...(override.authInfo ?? {}),
|
|
44
|
+
},
|
|
45
|
+
}
|
|
46
|
+
: {}),
|
|
47
|
+
};
|
|
48
|
+
};
|
|
18
49
|
export const readEnv = (key) => {
|
|
19
50
|
return typeof process !== "undefined" ? process.env[key] : undefined;
|
|
20
51
|
};
|