@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
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 = {
|
|
@@ -226,9 +229,14 @@ export type AnalyticsIngestEvent = {
|
|
|
226
229
|
is_workflow?: boolean;
|
|
227
230
|
workflow_run_id?: string;
|
|
228
231
|
};
|
|
232
|
+
export type AnalyticsBatchSdk = {
|
|
233
|
+
language: string;
|
|
234
|
+
version: string;
|
|
235
|
+
};
|
|
229
236
|
export type AnalyticsIngestBatch = {
|
|
230
237
|
schema_version: 1;
|
|
231
238
|
events: AnalyticsIngestEvent[];
|
|
239
|
+
sdk?: AnalyticsBatchSdk;
|
|
232
240
|
};
|
|
233
241
|
export type TelemetryEmitter = (batch: AnalyticsIngestBatch) => void | Promise<void>;
|
|
234
242
|
export type WithMcpAnalyticsResult<ServerFactoryResult> = {
|
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
|
};
|
package/dist/esm/v2.d.ts
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import type { McpAnalyticsConfig } from "./types.js";
|
|
2
|
+
/** Header a caller can set to pin the analytics session id (rung 2 of the ladder). */
|
|
3
|
+
export declare const SESSION_SEED_HEADER = "x-armature-session-seed";
|
|
4
|
+
/** Structural stand-in for a v2 `McpServer`: anything with `registerTool`. */
|
|
5
|
+
export type V2McpServerLike = {
|
|
6
|
+
registerTool: (name: string, config: never, cb: never) => unknown;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* v2-adapter behavior options, passed alongside the analytics config to
|
|
10
|
+
* `withMcpAnalytics` / `instrumentedFactory`. Kept separate from
|
|
11
|
+
* `McpAnalyticsConfig` because the recorder (delivery queue, session_init
|
|
12
|
+
* dedupe) is keyed on the config object; these options only shape how tools
|
|
13
|
+
* are wrapped and what metadata each event carries.
|
|
14
|
+
*/
|
|
15
|
+
export type V2AdapterOptions = {
|
|
16
|
+
/**
|
|
17
|
+
* Advertise the Armature `telemetry` input property on every instrumented
|
|
18
|
+
* tool's schema (v1 parity, opt-in). The adapter rebuilds each tool's
|
|
19
|
+
* ADVERTISED schema from the SDK's own JSON conversion
|
|
20
|
+
* (`toolInputSchemaJson`) plus the telemetry property (byte-identical
|
|
21
|
+
* descriptions to the v1 integration) via `fromJsonSchema`, and swaps it in
|
|
22
|
+
* with `RegisteredTool.update({ paramsSchema })` — so `tools/list`
|
|
23
|
+
* advertises telemetry AND the SDK's pre-dispatch Ajv validation accepts it
|
|
24
|
+
* before the analytics wrapper strips it. A top-level
|
|
25
|
+
* `additionalProperties: false` in the customer schema is preserved:
|
|
26
|
+
* `telemetry` becomes a declared property (so it passes), while every other
|
|
27
|
+
* undeclared key is still rejected exactly as before.
|
|
28
|
+
*
|
|
29
|
+
* Tradeoff: validation then runs against the JSON Schema projection of the
|
|
30
|
+
* original schema. Zod runtime effects that don't survive JSON Schema
|
|
31
|
+
* conversion (`.transform()`, `.refine()`, applied `.default()` values) no
|
|
32
|
+
* longer run inside the SDK's validation step — which is why this is
|
|
33
|
+
* opt-in. Tools whose schema cannot be projected to a JSON object schema
|
|
34
|
+
* are left undecorated (telemetry is still stripped and exported when a
|
|
35
|
+
* client sends it). Tools that declare their own `telemetry` property stay
|
|
36
|
+
* customer-owned and untouched.
|
|
37
|
+
*/
|
|
38
|
+
declareTelemetry?: boolean;
|
|
39
|
+
/**
|
|
40
|
+
* Per-event metadata hook: called once per tool call with the handler
|
|
41
|
+
* context, and its returned keys are merged into the tool_call event's
|
|
42
|
+
* metadata alongside the adapter's own keys (`protocol_era`, client
|
|
43
|
+
* identity, `request_meta`, …). Hook keys win over adapter-derived keys;
|
|
44
|
+
* contract-defined keys (`tool_name`, `user_intent`, …) always win over
|
|
45
|
+
* both (see events.ts metadataExtra). A throwing hook is ignored — it never
|
|
46
|
+
* breaks recording or the tool call.
|
|
47
|
+
*/
|
|
48
|
+
metadata?: (ctx: unknown) => Record<string, unknown> | undefined;
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Parse `gen_ai.conversation.id` out of a W3C `baggage` value: comma-separated
|
|
52
|
+
* `key=value` list entries, each optionally carrying `;`-separated properties,
|
|
53
|
+
* values URL-decoded. Rung 1 of the session-id ladder.
|
|
54
|
+
*/
|
|
55
|
+
export declare const conversationIdFromBaggage: (baggage: unknown) => string | undefined;
|
|
56
|
+
/**
|
|
57
|
+
* Drain the analytics pipeline tied to a config object (or the default
|
|
58
|
+
* config). Call before process exit / serverless freeze when not using
|
|
59
|
+
* `delivery: "await"` or a `schedule` hook.
|
|
60
|
+
*/
|
|
61
|
+
export declare const flushMcpAnalytics: (config?: McpAnalyticsConfig) => Promise<void>;
|
|
62
|
+
/**
|
|
63
|
+
* Instrument a v2 `McpServer` instance: every tool registered on it (before or
|
|
64
|
+
* after this call) records a `tool_call` analytics event with the same wire
|
|
65
|
+
* shape as the v1 SDK integration, plus a `session_init` on first sight of
|
|
66
|
+
* each session key. Returns the same (mutated) server instance.
|
|
67
|
+
*
|
|
68
|
+
* Under `createMcpHandler` the factory runs per request — prefer
|
|
69
|
+
* `instrumentedFactory`, or hoist the config object so every request shares
|
|
70
|
+
* one recorder (delivery queue + session_init dedupe are keyed on it).
|
|
71
|
+
*
|
|
72
|
+
* `options` (see V2AdapterOptions): `declareTelemetry` advertises the
|
|
73
|
+
* Armature telemetry property on each tool's schema (v1 parity, opt-in);
|
|
74
|
+
* `metadata` adds per-event metadata keys.
|
|
75
|
+
*/
|
|
76
|
+
export declare const withMcpAnalytics: <S extends V2McpServerLike>(server: S, config?: McpAnalyticsConfig, options?: V2AdapterOptions) => S;
|
|
77
|
+
/**
|
|
78
|
+
* Wrap a `createMcpHandler` / `serveStdio` factory so every server it produces
|
|
79
|
+
* is instrumented with `withMcpAnalytics`. One recorder (privacy queue +
|
|
80
|
+
* session_init dedupe) is shared across all servers the wrapped factory
|
|
81
|
+
* creates, and the factory's `McpRequestContext` (`requestInfo`, `authInfo`)
|
|
82
|
+
* backfills header-based capture when the handler ctx carries no HTTP request
|
|
83
|
+
* (the low-level `Server` sets `ctx.http.authInfo` without `req`).
|
|
84
|
+
*/
|
|
85
|
+
export declare const instrumentedFactory: <TArgs extends unknown[], TResult>(factory: (...args: TArgs) => TResult, config?: McpAnalyticsConfig, options?: V2AdapterOptions) => ((...args: TArgs) => TResult | Promise<Awaited<TResult>>);
|
|
86
|
+
/** Structural stand-in for the object `createMcpHandler` returns. */
|
|
87
|
+
export type V2McpHandlerLike = {
|
|
88
|
+
fetch: (request: Request, options?: never) => Promise<Response>;
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* Wrap a `createMcpHandler` handler's `fetch`.
|
|
92
|
+
*
|
|
93
|
+
* v2's `createMcpHandler` serves 2025-era clients through its stateless legacy
|
|
94
|
+
* leg, which mints NO `Mcp-Session-Id` (and offers no option to) — so a
|
|
95
|
+
* legacy client through a v2 handler silently loses session attribution.
|
|
96
|
+
* This wrapper repairs that: on a legacy `initialize` request it mints an
|
|
97
|
+
* identity-bearing session id (`mcp_<name>_v_<version>_<uuid>`, honoring
|
|
98
|
+
* `X-Armature-Session-Seed` as the uuid seed — the same scheme as
|
|
99
|
+
* `resolveStatelessHttpSession` in the v1 integration), attaches it as the
|
|
100
|
+
* response's `Mcp-Session-Id`, records the session_init, and echoes the id on
|
|
101
|
+
* later legacy responses. Conforming legacy clients echo the header on every
|
|
102
|
+
* subsequent request, where rung 3 of the session-id ladder picks it up.
|
|
103
|
+
*
|
|
104
|
+
* Composable and optional: `withMcpAnalytics` / `instrumentedFactory` work
|
|
105
|
+
* standalone (modern-era attribution needs no handler wrapper); pass the SAME
|
|
106
|
+
* config object to both so they share one recorder. Modern-era requests pass
|
|
107
|
+
* through this wrapper untouched (they carry no `initialize`).
|
|
108
|
+
*/
|
|
109
|
+
export declare const wrapMcpHandler: <H extends V2McpHandlerLike>(handler: H, config?: McpAnalyticsConfig) => H;
|
|
110
|
+
export type { AnalyticsRecorderCore } from "./recorder-core.js";
|
|
111
|
+
export type { AnalyticsEventKind, AnalyticsIngestBatch, AnalyticsIngestEvent, McpAnalyticsConfig, McpClientInfo, TelemetryArgs, TelemetryEmitter, } from "./types.js";
|
|
112
|
+
export { defaultMcpAnalyticsConfig } from "./emit.js";
|