@armature-tech/mcp-analytics 0.6.32 → 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/doctor.js +3 -1
- package/dist/cjs/emit.d.ts +3 -1
- package/dist/cjs/emit.js +12 -2
- 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 +8 -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/cjs/version.d.ts +1 -0
- package/dist/cjs/version.js +3 -0
- package/dist/esm/doctor.js +3 -1
- package/dist/esm/emit.d.ts +3 -1
- package/dist/esm/emit.js +11 -1
- 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 +8 -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/dist/esm/version.d.ts +1 -0
- package/dist/esm/version.js +1 -0
- package/package.json +51 -5
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { createAnalyticsRecorderCore, } from "./recorder-core.js";
|
|
2
|
+
import { defaultMcpAnalyticsConfig } from "./emit.js";
|
|
3
|
+
import { resolveStatelessHttpSession } from "./stateless-http.js";
|
|
4
|
+
import { isRecord } from "./utils.js";
|
|
5
|
+
const SESSION_ID_HEADER = "mcp-session-id";
|
|
6
|
+
// Keyed on the config object so every request shares one recorder (privacy
|
|
7
|
+
// queue + session_init dedupe) — hoist the config, same contract as the v2
|
|
8
|
+
// adapter. A fresh config per call still converges at ingest (session_init
|
|
9
|
+
// event ids are content-addressed per (actor, session)).
|
|
10
|
+
const recorderStatesByConfig = new WeakMap();
|
|
11
|
+
let defaultRecorderState;
|
|
12
|
+
const recorderStateFor = (config) => {
|
|
13
|
+
if (config === undefined || config === defaultMcpAnalyticsConfig) {
|
|
14
|
+
defaultRecorderState ??= { core: createAnalyticsRecorderCore(defaultMcpAnalyticsConfig) };
|
|
15
|
+
return defaultRecorderState;
|
|
16
|
+
}
|
|
17
|
+
let state = recorderStatesByConfig.get(config);
|
|
18
|
+
if (!state) {
|
|
19
|
+
state = { core: createAnalyticsRecorderCore(config) };
|
|
20
|
+
recorderStatesByConfig.set(config, state);
|
|
21
|
+
}
|
|
22
|
+
return state;
|
|
23
|
+
};
|
|
24
|
+
/** Drain the analytics pipeline tied to a config object (or the default config). */
|
|
25
|
+
export const flushMcpHandlerAnalytics = (config) => {
|
|
26
|
+
return recorderStateFor(config).core.flush();
|
|
27
|
+
};
|
|
28
|
+
const trimOrUndefined = (value) => {
|
|
29
|
+
if (typeof value !== "string")
|
|
30
|
+
return undefined;
|
|
31
|
+
const trimmed = value.trim();
|
|
32
|
+
return trimmed.length > 0 ? trimmed : undefined;
|
|
33
|
+
};
|
|
34
|
+
// Full-fidelity clientInfo from the initialize body itself (name, version,
|
|
35
|
+
// protocolVersion, capabilities) — richer than what the minted id can carry,
|
|
36
|
+
// so the session_init recorded at initialize matches what a stateful v1
|
|
37
|
+
// deployment would report.
|
|
38
|
+
const clientInfoFromInitializeBody = (body) => {
|
|
39
|
+
const messages = Array.isArray(body) ? body : [body];
|
|
40
|
+
const initialize = messages.find((message) => isRecord(message) && message.method === "initialize");
|
|
41
|
+
const params = isRecord(initialize?.params) ? initialize.params : undefined;
|
|
42
|
+
if (!params)
|
|
43
|
+
return undefined;
|
|
44
|
+
const info = isRecord(params.clientInfo) ? params.clientInfo : undefined;
|
|
45
|
+
const name = trimOrUndefined(info?.name);
|
|
46
|
+
if (name === undefined)
|
|
47
|
+
return undefined;
|
|
48
|
+
const version = trimOrUndefined(info?.version);
|
|
49
|
+
const protocolVersion = trimOrUndefined(params.protocolVersion);
|
|
50
|
+
return {
|
|
51
|
+
name,
|
|
52
|
+
...(version !== undefined ? { version } : {}),
|
|
53
|
+
...(protocolVersion !== undefined ? { protocolVersion } : {}),
|
|
54
|
+
capabilities: isRecord(params.capabilities) ? params.capabilities : null,
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
const withSessionIdHeader = (response, sessionId) => {
|
|
58
|
+
if (response.headers.get(SESSION_ID_HEADER))
|
|
59
|
+
return response;
|
|
60
|
+
const headers = new Headers(response.headers);
|
|
61
|
+
headers.set(SESSION_ID_HEADER, sessionId);
|
|
62
|
+
return new Response(response.body, {
|
|
63
|
+
status: response.status,
|
|
64
|
+
statusText: response.statusText,
|
|
65
|
+
headers,
|
|
66
|
+
});
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Wrap the handler returned by mcp-handler's `createMcpHandler` so MCP client
|
|
70
|
+
* and session identity survive its stateless transport. Pass the SAME config
|
|
71
|
+
* object here and to the `withMcpAnalytics` call inside your initialize
|
|
72
|
+
* callback so both share one delivery pipeline configuration:
|
|
73
|
+
*
|
|
74
|
+
* ~~~ts
|
|
75
|
+
* const handler = withMcpHandlerAnalytics(
|
|
76
|
+
* createMcpHandler((server) => {
|
|
77
|
+
* withMcpAnalytics(analyticsConfig, () => {
|
|
78
|
+
* server.tool(...); // instrumented by the package root's patch
|
|
79
|
+
* return server;
|
|
80
|
+
* });
|
|
81
|
+
* }),
|
|
82
|
+
* analyticsConfig,
|
|
83
|
+
* );
|
|
84
|
+
* export { handler as POST };
|
|
85
|
+
* ~~~
|
|
86
|
+
*
|
|
87
|
+
* Serverless note: `createMcpHandler` runs the initialize callback PER
|
|
88
|
+
* REQUEST, so use `delivery: "await"` (or a `schedule`/`waitUntil` hook) —
|
|
89
|
+
* a per-request background queue may be frozen before it delivers.
|
|
90
|
+
*/
|
|
91
|
+
export const withMcpHandlerAnalytics = (handler, config) => {
|
|
92
|
+
const state = recorderStateFor(config);
|
|
93
|
+
const wrapped = async (request, ...rest) => {
|
|
94
|
+
let session;
|
|
95
|
+
let body;
|
|
96
|
+
if (request.method === "POST") {
|
|
97
|
+
try {
|
|
98
|
+
const raw = await request.clone().text();
|
|
99
|
+
body = raw ? JSON.parse(raw) : undefined;
|
|
100
|
+
session = resolveStatelessHttpSession({ body, headers: request.headers });
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
session = undefined;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const response = await handler(request, ...rest);
|
|
107
|
+
if (session?.isInitialize && response.ok) {
|
|
108
|
+
try {
|
|
109
|
+
await state.core.recordSessionInit({
|
|
110
|
+
sessionId: session.sessionId,
|
|
111
|
+
headers: request.headers,
|
|
112
|
+
clientInfo: clientInfoFromInitializeBody(body),
|
|
113
|
+
extra: {
|
|
114
|
+
sessionId: session.sessionId,
|
|
115
|
+
requestInfo: { headers: request.headers },
|
|
116
|
+
},
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
// Recording is best-effort; never break the MCP response over it.
|
|
121
|
+
}
|
|
122
|
+
return withSessionIdHeader(response, session.sessionId);
|
|
123
|
+
}
|
|
124
|
+
// Echo an id the client is already carrying, so it keeps carrying it.
|
|
125
|
+
const echoed = request.headers.get(SESSION_ID_HEADER)?.trim();
|
|
126
|
+
if (echoed)
|
|
127
|
+
return withSessionIdHeader(response, echoed);
|
|
128
|
+
return response;
|
|
129
|
+
};
|
|
130
|
+
return wrapped;
|
|
131
|
+
};
|
|
132
|
+
export { defaultMcpAnalyticsConfig } from "./emit.js";
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { ExtractedToolArguments, InstrumentToolCallEvent, McpAnalyticsConfig, McpClientInfo, RecordSessionInitEvent, RecordToolCallEvent, TelemetryMode, ToolCallHandler } from "./types.js";
|
|
2
|
+
export type RecorderCoreHooks = {
|
|
3
|
+
/**
|
|
4
|
+
* Session-scoped client identity lookup consulted when an event carries no
|
|
5
|
+
* explicit clientInfo. The v1 recorder wires the `_onrequest`-patch cache
|
|
6
|
+
* here; the v2 adapter passes clientInfo per event (per-request envelope)
|
|
7
|
+
* and needs no hook. The identity-bearing stateless session id parse runs
|
|
8
|
+
* as a built-in last resort either way.
|
|
9
|
+
*/
|
|
10
|
+
clientInfoForSessionId?: (sessionId: string) => McpClientInfo | undefined;
|
|
11
|
+
/**
|
|
12
|
+
* True when the named tool owns its `telemetry` input field (mode "owned",
|
|
13
|
+
* TELEMETRY-CONTRACT.md): supplied telemetry must never be exported.
|
|
14
|
+
*/
|
|
15
|
+
isToolTelemetryOwned?: (name: string) => boolean;
|
|
16
|
+
};
|
|
17
|
+
export type AnalyticsRecorderCore = {
|
|
18
|
+
extractTelemetry: (args: unknown, mode?: TelemetryMode) => ExtractedToolArguments;
|
|
19
|
+
recordToolCall: (event: RecordToolCallEvent) => Promise<void>;
|
|
20
|
+
recordSessionInit: (event: RecordSessionInitEvent) => Promise<void>;
|
|
21
|
+
instrumentToolCall: <T>(event: InstrumentToolCallEvent, handler: ToolCallHandler<T>) => Promise<T>;
|
|
22
|
+
flush: () => Promise<void>;
|
|
23
|
+
};
|
|
24
|
+
export declare const createAnalyticsRecorderCore: (config?: McpAnalyticsConfig, hooks?: RecorderCoreHooks) => AnalyticsRecorderCore;
|
|
@@ -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
|
+
};
|