@kometolabs/mcp-analytics 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/NOTICE +2 -0
- package/OTLP.md +81 -0
- package/README.md +194 -2
- package/dist/analytics.d.ts +172 -0
- package/dist/analytics.d.ts.map +1 -0
- package/dist/analytics.js +799 -0
- package/dist/analytics.js.map +1 -0
- package/dist/cli.d.ts +10 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +72 -0
- package/dist/cli.js.map +1 -0
- package/dist/clients.d.ts +5 -0
- package/dist/clients.d.ts.map +1 -0
- package/dist/clients.js +29 -0
- package/dist/clients.js.map +1 -0
- package/dist/doctor.d.ts +27 -0
- package/dist/doctor.d.ts.map +1 -0
- package/dist/doctor.js +108 -0
- package/dist/doctor.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp.d.ts +87 -0
- package/dist/mcp.d.ts.map +1 -0
- package/dist/mcp.js +291 -0
- package/dist/mcp.js.map +1 -0
- package/dist/otlp-protocol.d.ts +10 -0
- package/dist/otlp-protocol.d.ts.map +1 -0
- package/dist/otlp-protocol.js +485 -0
- package/dist/otlp-protocol.js.map +1 -0
- package/dist/otlp.d.ts +24 -0
- package/dist/otlp.d.ts.map +1 -0
- package/dist/otlp.js +174 -0
- package/dist/otlp.js.map +1 -0
- package/package.json +59 -3
|
@@ -0,0 +1,799 @@
|
|
|
1
|
+
import { createHmac, randomUUID } from 'node:crypto';
|
|
2
|
+
import { performance } from 'node:perf_hooks';
|
|
3
|
+
import { builtInAliases, DEFAULT_CLIENTS } from './clients.js';
|
|
4
|
+
import { createOtlpTransport, getOtlpFailure, otlpLogsUrl } from './otlp.js';
|
|
5
|
+
function validatedSink(transport) {
|
|
6
|
+
return async (events) => {
|
|
7
|
+
const canonical = Object.freeze(events.map(validateEvent));
|
|
8
|
+
await transport(canonical);
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
/** Standard OTLP export, also available as an explicit sink for advanced use. */
|
|
12
|
+
export function createOtlpSink(options) {
|
|
13
|
+
return validatedSink(createOtlpTransport(options));
|
|
14
|
+
}
|
|
15
|
+
const SLUG = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/;
|
|
16
|
+
const HASH = /^[a-f0-9]{64}$/;
|
|
17
|
+
const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;
|
|
18
|
+
const OUTCOMES = new Set(['ok', 'tool_error', 'exception', 'input_required']);
|
|
19
|
+
const KINDS = new Set(['tool_call', 'authorization', 'value_completed']);
|
|
20
|
+
const SUBJECT_TYPES = new Set(['user', 'account', 'service']);
|
|
21
|
+
const EVENT_KEYS = new Set([
|
|
22
|
+
'schemaVersion', 'eventId', 'projectId', 'serverId', 'environment', 'occurredAt', 'kind',
|
|
23
|
+
'toolName', 'outcome', 'durationMs', 'subjectHash', 'identityKeyVersion', 'subjectType',
|
|
24
|
+
'clientApplication', 'sourceTag', 'operationHash',
|
|
25
|
+
]);
|
|
26
|
+
function invalidEvent() {
|
|
27
|
+
throw new TypeError('Invalid analytics event');
|
|
28
|
+
}
|
|
29
|
+
function isSlug(value) {
|
|
30
|
+
return typeof value === 'string' && SLUG.test(value);
|
|
31
|
+
}
|
|
32
|
+
function rawString(value) {
|
|
33
|
+
return typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) <= 4096;
|
|
34
|
+
}
|
|
35
|
+
function validSecret(secret) {
|
|
36
|
+
return typeof secret === 'string' && Buffer.byteLength(secret) >= 32 && Buffer.byteLength(secret) <= 4096;
|
|
37
|
+
}
|
|
38
|
+
/** Returns a detached, immutable allowlisted event; rejection messages never echo data. */
|
|
39
|
+
export function validateEvent(value) {
|
|
40
|
+
try {
|
|
41
|
+
if (value === null || typeof value !== 'object')
|
|
42
|
+
return invalidEvent();
|
|
43
|
+
const prototype = Object.getPrototypeOf(value);
|
|
44
|
+
if (prototype !== Object.prototype && prototype !== null)
|
|
45
|
+
return invalidEvent();
|
|
46
|
+
const record = {};
|
|
47
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
48
|
+
if (typeof key !== 'string' || !EVENT_KEYS.has(key))
|
|
49
|
+
return invalidEvent();
|
|
50
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
51
|
+
if (!descriptor || !('value' in descriptor))
|
|
52
|
+
return invalidEvent();
|
|
53
|
+
if (descriptor.value !== undefined)
|
|
54
|
+
record[key] = descriptor.value;
|
|
55
|
+
}
|
|
56
|
+
if (record.schemaVersion !== 1 || typeof record.eventId !== 'string' || !UUID.test(record.eventId))
|
|
57
|
+
return invalidEvent();
|
|
58
|
+
if (!isSlug(record.projectId) || !isSlug(record.serverId) || !isSlug(record.environment))
|
|
59
|
+
return invalidEvent();
|
|
60
|
+
if (typeof record.occurredAt !== 'string' || new Date(record.occurredAt).toISOString() !== record.occurredAt)
|
|
61
|
+
return invalidEvent();
|
|
62
|
+
if (!KINDS.has(record.kind))
|
|
63
|
+
return invalidEvent();
|
|
64
|
+
for (const key of ['toolName', 'identityKeyVersion', 'clientApplication', 'sourceTag']) {
|
|
65
|
+
if (record[key] !== undefined && !isSlug(record[key]))
|
|
66
|
+
return invalidEvent();
|
|
67
|
+
}
|
|
68
|
+
for (const key of ['subjectHash', 'operationHash']) {
|
|
69
|
+
if (record[key] !== undefined && (typeof record[key] !== 'string' || !HASH.test(record[key])))
|
|
70
|
+
return invalidEvent();
|
|
71
|
+
}
|
|
72
|
+
if (record.subjectType !== undefined && !SUBJECT_TYPES.has(record.subjectType))
|
|
73
|
+
return invalidEvent();
|
|
74
|
+
const identityFields = ['subjectHash', 'identityKeyVersion', 'subjectType'].filter((key) => record[key] !== undefined).length;
|
|
75
|
+
if (identityFields !== 0 && identityFields !== 3)
|
|
76
|
+
return invalidEvent();
|
|
77
|
+
if (record.outcome !== undefined && !OUTCOMES.has(record.outcome))
|
|
78
|
+
return invalidEvent();
|
|
79
|
+
if (record.durationMs !== undefined && (typeof record.durationMs !== 'number' || !Number.isFinite(record.durationMs) || record.durationMs < 0 || record.durationMs > Number.MAX_SAFE_INTEGER))
|
|
80
|
+
return invalidEvent();
|
|
81
|
+
if (record.kind === 'tool_call') {
|
|
82
|
+
if (record.toolName === undefined || record.outcome === undefined || record.durationMs === undefined)
|
|
83
|
+
return invalidEvent();
|
|
84
|
+
}
|
|
85
|
+
else if (record.outcome !== undefined || record.durationMs !== undefined)
|
|
86
|
+
return invalidEvent();
|
|
87
|
+
return Object.freeze(record);
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return invalidEvent();
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/** The tuple is hashed locally; the secret and original subject never enter an event. */
|
|
94
|
+
export function hashSubject(secret, projectId, subject) {
|
|
95
|
+
try {
|
|
96
|
+
if (!validSecret(secret) || !isSlug(projectId) || !subject || typeof subject !== 'object')
|
|
97
|
+
throw new Error();
|
|
98
|
+
const { issuer, tenant, id, type = 'user' } = subject;
|
|
99
|
+
if (!rawString(issuer) || !rawString(id) || (tenant !== undefined && !rawString(tenant)) || !SUBJECT_TYPES.has(type))
|
|
100
|
+
throw new Error();
|
|
101
|
+
return createHmac('sha256', secret).update(JSON.stringify(['subject', projectId, type, issuer, tenant ?? null, id])).digest('hex');
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
throw new TypeError('Invalid subject configuration');
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const ALIAS_RULE = 'must be 1-64 ASCII letters, digits, underscores, dots, or hyphens, starting with a letter, digit, or underscore';
|
|
108
|
+
const INTEGER_LIMIT = 2_147_483_647;
|
|
109
|
+
const MAX_TOOLS = 1000;
|
|
110
|
+
const MAX_CLIENT_LABEL = 256;
|
|
111
|
+
// Messages name the field and its rule only, never the configured value.
|
|
112
|
+
const configurationFailure = (problem) => {
|
|
113
|
+
throw new TypeError(`Invalid analytics configuration: ${problem}`);
|
|
114
|
+
};
|
|
115
|
+
/** An explicit option wins; an empty environment variable counts as unset. */
|
|
116
|
+
function fromEnvironment(value, env, name, variable) {
|
|
117
|
+
if (value !== undefined)
|
|
118
|
+
return { value, label: name };
|
|
119
|
+
const fallback = env[variable];
|
|
120
|
+
return fallback === undefined || fallback === '' ? { value: undefined, label: name } : { value: fallback, label: variable };
|
|
121
|
+
}
|
|
122
|
+
function optionalAlias(value, env, name, variable) {
|
|
123
|
+
const option = fromEnvironment(value, env, name, variable);
|
|
124
|
+
return option.value === undefined ? undefined : aliasOption(option.label, option.value);
|
|
125
|
+
}
|
|
126
|
+
function aliasOption(name, value) {
|
|
127
|
+
if (!isSlug(value))
|
|
128
|
+
configurationFailure(`${name} ${ALIAS_RULE}`);
|
|
129
|
+
return value;
|
|
130
|
+
}
|
|
131
|
+
/** Common spellings of an enabled flag; anything else, including unset, is off. */
|
|
132
|
+
export function enabledFlag(value) {
|
|
133
|
+
return value !== undefined && ['1', 'true', 'yes', 'on'].includes(value.trim().toLowerCase());
|
|
134
|
+
}
|
|
135
|
+
const CONNECTION_RULE = 'must look like https://<write-key>@<host>[:port][/base-path]/<project-id>, without a password, query, or fragment';
|
|
136
|
+
/**
|
|
137
|
+
* Splits a connection string into the OTLP logs endpoint (credentials
|
|
138
|
+
* removed), the write key, and the project. Messages never echo the value.
|
|
139
|
+
*/
|
|
140
|
+
function parseConnection(label, value) {
|
|
141
|
+
if (typeof value !== 'string' || value.length > 4096)
|
|
142
|
+
configurationFailure(`${label} ${CONNECTION_RULE}`);
|
|
143
|
+
let url;
|
|
144
|
+
try {
|
|
145
|
+
url = new URL(value);
|
|
146
|
+
}
|
|
147
|
+
catch { /* reported below */ }
|
|
148
|
+
if (!url || !['https:', 'http:'].includes(url.protocol) || !url.username || url.password || url.search || url.hash) {
|
|
149
|
+
return configurationFailure(`${label} ${CONNECTION_RULE}`);
|
|
150
|
+
}
|
|
151
|
+
const segments = url.pathname.split('/').filter((segment) => segment.length > 0);
|
|
152
|
+
const project = segments.pop();
|
|
153
|
+
if (project === undefined)
|
|
154
|
+
configurationFailure(`${label} ${CONNECTION_RULE}`);
|
|
155
|
+
let projectId;
|
|
156
|
+
let writeKey;
|
|
157
|
+
try {
|
|
158
|
+
projectId = decodeURIComponent(project);
|
|
159
|
+
writeKey = decodeURIComponent(url.username);
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return configurationFailure(`${label} ${CONNECTION_RULE}`);
|
|
163
|
+
}
|
|
164
|
+
if (!isSlug(projectId))
|
|
165
|
+
configurationFailure(`${label} project ID ${ALIAS_RULE}`);
|
|
166
|
+
const basePath = segments.length === 0 ? '' : `/${segments.join('/')}`;
|
|
167
|
+
return { endpoint: `${url.protocol}//${url.host}${basePath}/v1/logs`, writeKey, projectId };
|
|
168
|
+
}
|
|
169
|
+
function integerOption(name, value, fallback, min) {
|
|
170
|
+
const actual = value ?? fallback;
|
|
171
|
+
if (!Number.isSafeInteger(actual) || actual < min || actual > INTEGER_LIMIT) {
|
|
172
|
+
configurationFailure(`${name} must be an integer from ${min} to ${INTEGER_LIMIT}`);
|
|
173
|
+
}
|
|
174
|
+
return actual;
|
|
175
|
+
}
|
|
176
|
+
function configuredList(name, value) {
|
|
177
|
+
if (value !== undefined && (!Array.isArray(value) || value.length > MAX_TOOLS)) {
|
|
178
|
+
configurationFailure(`${name} must be an array of at most ${MAX_TOOLS} aliases`);
|
|
179
|
+
}
|
|
180
|
+
const values = value ?? [];
|
|
181
|
+
values.forEach((item, index) => { if (!isSlug(item))
|
|
182
|
+
configurationFailure(`${name}[${index}] ${ALIAS_RULE}`); });
|
|
183
|
+
return values;
|
|
184
|
+
}
|
|
185
|
+
function secretOption(name, value) {
|
|
186
|
+
if (value === undefined)
|
|
187
|
+
return undefined;
|
|
188
|
+
if (typeof value !== 'string')
|
|
189
|
+
configurationFailure(`${name} must be a string of at least 32 bytes`);
|
|
190
|
+
const bytes = Buffer.byteLength(value);
|
|
191
|
+
if (bytes < 32)
|
|
192
|
+
configurationFailure(`${name} must contain at least 32 bytes`);
|
|
193
|
+
if (bytes > 4096)
|
|
194
|
+
configurationFailure(`${name} must contain at most 4096 bytes`);
|
|
195
|
+
return value;
|
|
196
|
+
}
|
|
197
|
+
/** Case-insensitive lookup from observed client names to configured client aliases. */
|
|
198
|
+
function clientLookup(clients, aliases) {
|
|
199
|
+
const lookup = new Map();
|
|
200
|
+
clients.forEach((client, index) => {
|
|
201
|
+
const key = client.toLowerCase();
|
|
202
|
+
if (lookup.has(key))
|
|
203
|
+
configurationFailure(`clients[${index}] duplicates another client when compared ignoring case`);
|
|
204
|
+
lookup.set(key, client);
|
|
205
|
+
});
|
|
206
|
+
// Built-in reported names never shadow a configured client, and explicit
|
|
207
|
+
// aliases may override them.
|
|
208
|
+
const builtIn = new Set();
|
|
209
|
+
for (const client of clients) {
|
|
210
|
+
for (const name of builtInAliases(client)) {
|
|
211
|
+
const key = name.toLowerCase();
|
|
212
|
+
if (!lookup.has(key)) {
|
|
213
|
+
lookup.set(key, client);
|
|
214
|
+
builtIn.add(key);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (aliases === undefined)
|
|
219
|
+
return lookup;
|
|
220
|
+
if (aliases === null || typeof aliases !== 'object' || Array.isArray(aliases))
|
|
221
|
+
configurationFailure('clientAliases must be an object');
|
|
222
|
+
Object.entries(aliases).forEach(([name, target], index) => {
|
|
223
|
+
if (name.length === 0 || name.length > MAX_CLIENT_LABEL)
|
|
224
|
+
configurationFailure(`clientAliases entry ${index} must have a name of 1-${MAX_CLIENT_LABEL} characters`);
|
|
225
|
+
if (typeof target !== 'string' || !clients.includes(target))
|
|
226
|
+
configurationFailure(`clientAliases entry ${index} must map to a configured client`);
|
|
227
|
+
const key = name.toLowerCase();
|
|
228
|
+
const existing = lookup.get(key);
|
|
229
|
+
if (existing !== undefined && existing !== target && !builtIn.has(key))
|
|
230
|
+
configurationFailure(`clientAliases entry ${index} conflicts with another client or alias when compared ignoring case`);
|
|
231
|
+
builtIn.delete(key);
|
|
232
|
+
lookup.set(key, target);
|
|
233
|
+
});
|
|
234
|
+
return lookup;
|
|
235
|
+
}
|
|
236
|
+
function isThenable(value) {
|
|
237
|
+
return value !== null && (typeof value === 'object' || typeof value === 'function')
|
|
238
|
+
&& typeof value.then === 'function';
|
|
239
|
+
}
|
|
240
|
+
// Configuration-class codes warn once per instance when no callback is set.
|
|
241
|
+
// Transient delivery failures do not warn.
|
|
242
|
+
const WARNINGS = {
|
|
243
|
+
authentication_failed: 'the analytics receiver rejected the write key (HTTP 401). Check the write key in MCP_ANALYTICS_URL against the receiver MCP_ANALYTICS_WRITE_KEY.',
|
|
244
|
+
project_rejected: 'the analytics receiver rejected the project (HTTP 403). Check the project in MCP_ANALYTICS_URL against the receiver MCP_ANALYTICS_PROJECT_ID.',
|
|
245
|
+
delivery_rejected: 'the analytics receiver permanently rejected a batch, which was discarded. Check the endpoint and the receiver logs.',
|
|
246
|
+
unknown_tool: 'a tool name is not in the tools allowlist; it was recorded as __unknown_tool__.',
|
|
247
|
+
invalid_context: 'an event context was invalid or its resolver failed; the event was dropped.',
|
|
248
|
+
identity_unavailable: 'identitySecret is not configured; subject and operation hashes were omitted.',
|
|
249
|
+
};
|
|
250
|
+
function warningCode(code) {
|
|
251
|
+
return `MCP_ANALYTICS_${code.toUpperCase()}`;
|
|
252
|
+
}
|
|
253
|
+
/** Marks a failure of customer context resolution, not of the SDK itself. */
|
|
254
|
+
class ContextFailure extends Error {
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Copies the supported context fields once, so later changes to the caller's
|
|
258
|
+
* objects cannot alter the event. Accessor errors surface as context failures.
|
|
259
|
+
*/
|
|
260
|
+
function snapshot(value) {
|
|
261
|
+
if (value === undefined)
|
|
262
|
+
return undefined;
|
|
263
|
+
if (value === null || typeof value !== 'object')
|
|
264
|
+
throw new ContextFailure();
|
|
265
|
+
try {
|
|
266
|
+
const { subject, clientApplication, sourceTag, operationId } = value;
|
|
267
|
+
const copy = {};
|
|
268
|
+
if (typeof subject === 'string')
|
|
269
|
+
copy.subject = subject;
|
|
270
|
+
else if (subject !== undefined) {
|
|
271
|
+
if (subject === null || typeof subject !== 'object')
|
|
272
|
+
throw new Error();
|
|
273
|
+
const { issuer, tenant, id, type } = subject;
|
|
274
|
+
copy.subject = { issuer, id };
|
|
275
|
+
if (tenant !== undefined)
|
|
276
|
+
copy.subject.tenant = tenant;
|
|
277
|
+
if (type !== undefined)
|
|
278
|
+
copy.subject.type = type;
|
|
279
|
+
}
|
|
280
|
+
if (clientApplication !== undefined)
|
|
281
|
+
copy.clientApplication = clientApplication;
|
|
282
|
+
if (sourceTag !== undefined)
|
|
283
|
+
copy.sourceTag = sourceTag;
|
|
284
|
+
if (operationId !== undefined)
|
|
285
|
+
copy.operationId = operationId;
|
|
286
|
+
return copy;
|
|
287
|
+
}
|
|
288
|
+
catch {
|
|
289
|
+
throw new ContextFailure();
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
function waitFor(promise, timeoutMs) {
|
|
293
|
+
if (timeoutMs <= 0)
|
|
294
|
+
return Promise.resolve(false);
|
|
295
|
+
return new Promise((resolve) => {
|
|
296
|
+
const timer = setTimeout(() => resolve(false), Math.ceil(timeoutMs));
|
|
297
|
+
void promise.then(() => {
|
|
298
|
+
clearTimeout(timer);
|
|
299
|
+
resolve(true);
|
|
300
|
+
}, () => {
|
|
301
|
+
clearTimeout(timer);
|
|
302
|
+
resolve(true);
|
|
303
|
+
});
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
function sleep(timeoutMs) {
|
|
307
|
+
return new Promise((resolve) => setTimeout(resolve, timeoutMs));
|
|
308
|
+
}
|
|
309
|
+
function outcomeOf(result) {
|
|
310
|
+
if (result !== null && typeof result === 'object') {
|
|
311
|
+
const candidate = result;
|
|
312
|
+
if (candidate.isError === true)
|
|
313
|
+
return 'tool_error';
|
|
314
|
+
if (candidate.resultType === 'input_required')
|
|
315
|
+
return 'input_required';
|
|
316
|
+
}
|
|
317
|
+
return 'ok';
|
|
318
|
+
}
|
|
319
|
+
/** Writes one diagnostic line to stderr, which stdio MCP servers keep free of protocol messages. */
|
|
320
|
+
export function debugLine(text) {
|
|
321
|
+
try {
|
|
322
|
+
process.stderr.write(`mcp-analytics: ${text}\n`);
|
|
323
|
+
}
|
|
324
|
+
catch { /* output must never affect telemetry or tools */ }
|
|
325
|
+
}
|
|
326
|
+
/** Metadata only: the kind, tool alias, outcome, duration, client label, and a subject-hash prefix. */
|
|
327
|
+
function describeEvent(event) {
|
|
328
|
+
const parts = [event.kind];
|
|
329
|
+
if (event.toolName !== undefined)
|
|
330
|
+
parts.push(event.toolName);
|
|
331
|
+
if (event.outcome !== undefined)
|
|
332
|
+
parts.push(event.outcome);
|
|
333
|
+
if (event.durationMs !== undefined)
|
|
334
|
+
parts.push(`${event.durationMs.toFixed(1)} ms`);
|
|
335
|
+
parts.push(`client=${event.clientApplication ?? 'unknown'}`);
|
|
336
|
+
if (event.sourceTag !== undefined)
|
|
337
|
+
parts.push(`source=${event.sourceTag}`);
|
|
338
|
+
parts.push(`user=${event.subjectHash === undefined ? '-' : event.subjectHash.slice(0, 12)}`);
|
|
339
|
+
return parts.join(' ');
|
|
340
|
+
}
|
|
341
|
+
const instances = new WeakMap();
|
|
342
|
+
/** @internal The project and whether identity hashing is enabled, for instances made by createAnalytics. */
|
|
343
|
+
export function instanceInfo(analytics) {
|
|
344
|
+
return instances.get(analytics);
|
|
345
|
+
}
|
|
346
|
+
export function createAnalytics(config = {}) {
|
|
347
|
+
if (config === null || typeof config !== 'object')
|
|
348
|
+
configurationFailure('options must be an object');
|
|
349
|
+
if (config.env !== undefined && (config.env === null || typeof config.env !== 'object'))
|
|
350
|
+
configurationFailure('env must be an object');
|
|
351
|
+
const env = config.env ?? process.env;
|
|
352
|
+
// The connection string supplies the endpoint, write key, and project. With
|
|
353
|
+
// a custom sink it is not read from the environment at all.
|
|
354
|
+
const custom = config.sink !== undefined;
|
|
355
|
+
if (custom && (config.url !== undefined || config.endpoint !== undefined || config.writeKey !== undefined || config.requestTimeoutMs !== undefined)) {
|
|
356
|
+
configurationFailure('sink cannot be combined with url, endpoint, writeKey, or requestTimeoutMs');
|
|
357
|
+
}
|
|
358
|
+
const url = custom ? { value: undefined, label: 'url' } : fromEnvironment(config.url, env, 'url', 'MCP_ANALYTICS_URL');
|
|
359
|
+
const connection = url.value === undefined ? undefined : parseConnection(url.label, url.value);
|
|
360
|
+
const endpoint = config.endpoint !== undefined || connection === undefined
|
|
361
|
+
? fromEnvironment(config.endpoint, env, 'endpoint', 'MCP_ANALYTICS_ENDPOINT')
|
|
362
|
+
: { value: connection.endpoint, label: `${url.label} endpoint` };
|
|
363
|
+
const writeKey = config.writeKey !== undefined || connection === undefined
|
|
364
|
+
? fromEnvironment(config.writeKey, env, 'writeKey', 'MCP_ANALYTICS_WRITE_KEY')
|
|
365
|
+
: { value: connection.writeKey, label: `${url.label} write key` };
|
|
366
|
+
if (!custom && endpoint.value === undefined && writeKey.value === undefined) {
|
|
367
|
+
configurationFailure('MCP_ANALYTICS_URL is not set (or pass url, or endpoint and writeKey)');
|
|
368
|
+
}
|
|
369
|
+
const projectId = config.projectId === undefined && connection !== undefined ? connection.projectId
|
|
370
|
+
: optionalAlias(config.projectId, env, 'projectId', 'MCP_ANALYTICS_PROJECT_ID')
|
|
371
|
+
?? configurationFailure(`projectId is required (set ${custom ? '' : 'MCP_ANALYTICS_URL, '}the option, or MCP_ANALYTICS_PROJECT_ID)`);
|
|
372
|
+
const serverId = optionalAlias(config.serverId, env, 'serverId', 'MCP_ANALYTICS_SERVER_ID') ?? 'default';
|
|
373
|
+
const environment = optionalAlias(config.environment, env, 'environment', 'MCP_ANALYTICS_ENVIRONMENT')
|
|
374
|
+
?? optionalAlias(undefined, env, 'environment', 'NODE_ENV') ?? 'production';
|
|
375
|
+
if (config.debug !== undefined && typeof config.debug !== 'boolean')
|
|
376
|
+
configurationFailure('debug must be a boolean');
|
|
377
|
+
const debug = config.debug ?? enabledFlag(env.MCP_ANALYTICS_DEBUG);
|
|
378
|
+
const secret = fromEnvironment(config.identitySecret, env, 'identitySecret', 'MCP_ANALYTICS_IDENTITY_SECRET');
|
|
379
|
+
const identitySecret = secretOption(secret.label, secret.value);
|
|
380
|
+
const identityKeyVersion = aliasOption('identityKeyVersion', config.identityKeyVersion ?? 'v1');
|
|
381
|
+
if (config.now !== undefined && typeof config.now !== 'function')
|
|
382
|
+
configurationFailure('now must be a function');
|
|
383
|
+
if (config.onDiagnostic !== undefined && typeof config.onDiagnostic !== 'function')
|
|
384
|
+
configurationFailure('onDiagnostic must be a function');
|
|
385
|
+
const tools = new Set(configuredList('tools', config.tools));
|
|
386
|
+
const clients = clientLookup(config.clients === undefined ? DEFAULT_CLIENTS : configuredList('clients', config.clients), config.clientAliases);
|
|
387
|
+
const sources = new Set(configuredList('sources', config.sources));
|
|
388
|
+
const maxQueueEvents = integerOption('maxQueueEvents', config.maxQueueEvents, 1000, 1);
|
|
389
|
+
const maxQueueBytes = integerOption('maxQueueBytes', config.maxQueueBytes, 1_048_576, 1);
|
|
390
|
+
const batchSize = Math.min(integerOption('batchSize', config.batchSize, 100, 1), maxQueueEvents);
|
|
391
|
+
const flushIntervalMs = integerOption('flushIntervalMs', config.flushIntervalMs, 1000, 0);
|
|
392
|
+
const maxRetries = integerOption('maxRetries', config.maxRetries, 3, 0);
|
|
393
|
+
const retryDelayMs = integerOption('retryDelayMs', config.retryDelayMs, 100, 1);
|
|
394
|
+
const maxRetryAgeMs = integerOption('maxRetryAgeMs', config.maxRetryAgeMs, 30_000, 1);
|
|
395
|
+
const sinkTimeoutMs = integerOption('sinkTimeoutMs', config.sinkTimeoutMs, 2000, 1);
|
|
396
|
+
const flushTimeoutMs = integerOption('flushTimeoutMs', config.flushTimeoutMs, 5000, 1);
|
|
397
|
+
let sink;
|
|
398
|
+
let delivery;
|
|
399
|
+
if (config.sink !== undefined) {
|
|
400
|
+
if (typeof config.sink !== 'function')
|
|
401
|
+
configurationFailure('sink must be a function');
|
|
402
|
+
sink = config.sink;
|
|
403
|
+
}
|
|
404
|
+
else {
|
|
405
|
+
if (endpoint.value === undefined)
|
|
406
|
+
configurationFailure('endpoint is required unless sink is supplied (set MCP_ANALYTICS_URL, the option, or MCP_ANALYTICS_ENDPOINT)');
|
|
407
|
+
if (writeKey.value === undefined)
|
|
408
|
+
configurationFailure('writeKey is required unless sink is supplied (set MCP_ANALYTICS_URL, the option, or MCP_ANALYTICS_WRITE_KEY)');
|
|
409
|
+
const timeoutMs = integerOption('requestTimeoutMs', config.requestTimeoutMs, sinkTimeoutMs, 1);
|
|
410
|
+
// Rule messages name the environment variable when the value came from one.
|
|
411
|
+
const fail = problem => configurationFailure(problem
|
|
412
|
+
.replace(/^endpoint /, `${endpoint.label} `).replace(/^writeKey /, `${writeKey.label} `));
|
|
413
|
+
// Queued events were validated and frozen at enqueue, so the internal
|
|
414
|
+
// transport sends them without validating each one again.
|
|
415
|
+
sink = createOtlpTransport({ endpoint: endpoint.value, writeKey: writeKey.value, timeoutMs }, fail, 'requestTimeoutMs');
|
|
416
|
+
delivery = { endpoint: otlpLogsUrl(endpoint.value), writeKey: writeKey.value };
|
|
417
|
+
}
|
|
418
|
+
const now = config.now ?? (() => new Date());
|
|
419
|
+
const onDiagnostic = config.onDiagnostic;
|
|
420
|
+
const counts = { sent: 0, dropped: 0, retries: 0, sinkErrors: 0, unknownTools: 0, unknownClients: 0 };
|
|
421
|
+
const warned = new Set();
|
|
422
|
+
let queue = [];
|
|
423
|
+
let queueBytes = 0;
|
|
424
|
+
let accepting = true;
|
|
425
|
+
let activeSink;
|
|
426
|
+
let activePump;
|
|
427
|
+
let closePromise;
|
|
428
|
+
// A flush sends events queued up to its latest call. Under continuous load,
|
|
429
|
+
// later arrivals wait for the next flush and form full batches instead of a
|
|
430
|
+
// stream of tiny requests.
|
|
431
|
+
let flushCutoff = 0;
|
|
432
|
+
function diagnose(code, events, status) {
|
|
433
|
+
if (events <= 0)
|
|
434
|
+
return;
|
|
435
|
+
if (debug)
|
|
436
|
+
debugLine(`${code} (${events} event${events === 1 ? '' : 's'}${status === undefined ? '' : `, HTTP ${status}`})`);
|
|
437
|
+
if (onDiagnostic) {
|
|
438
|
+
const diagnostic = Object.freeze(status === undefined ? { code, events } : { code, events, status });
|
|
439
|
+
// Deliver outside the SDK's own state changes and the caller's tool path.
|
|
440
|
+
queueMicrotask(() => { try {
|
|
441
|
+
onDiagnostic(diagnostic);
|
|
442
|
+
}
|
|
443
|
+
catch { /* callback errors never affect telemetry */ } });
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
const message = WARNINGS[code];
|
|
447
|
+
if (message === undefined || warned.has(code))
|
|
448
|
+
return;
|
|
449
|
+
warned.add(code);
|
|
450
|
+
try {
|
|
451
|
+
process.emitWarning(`MCP analytics: ${message} Later ${code} diagnostics from this instance are not repeated; pass onDiagnostic to handle or silence them.`, { type: 'McpAnalyticsWarning', code: warningCode(code) });
|
|
452
|
+
}
|
|
453
|
+
catch { /* a warning must never affect telemetry or tools */ }
|
|
454
|
+
}
|
|
455
|
+
function drop(code, events = 1, status) {
|
|
456
|
+
counts.dropped += events;
|
|
457
|
+
diagnose(code, events, status);
|
|
458
|
+
}
|
|
459
|
+
function remove(entries, reason) {
|
|
460
|
+
if (entries.length === 0)
|
|
461
|
+
return 0;
|
|
462
|
+
const selected = new Set(entries);
|
|
463
|
+
let removed = 0;
|
|
464
|
+
queue = queue.filter((entry) => {
|
|
465
|
+
if (!selected.has(entry))
|
|
466
|
+
return true;
|
|
467
|
+
queueBytes -= entry.bytes;
|
|
468
|
+
counts[reason] += 1;
|
|
469
|
+
removed += 1;
|
|
470
|
+
return false;
|
|
471
|
+
});
|
|
472
|
+
return removed;
|
|
473
|
+
}
|
|
474
|
+
function expire() {
|
|
475
|
+
// Entries keep their insertion order and original queuedAt, so the oldest
|
|
476
|
+
// is first and an unexpired head means nothing has expired.
|
|
477
|
+
const head = queue[0];
|
|
478
|
+
if (head === undefined)
|
|
479
|
+
return;
|
|
480
|
+
const time = performance.now();
|
|
481
|
+
if (time - head.queuedAt < maxRetryAgeMs)
|
|
482
|
+
return;
|
|
483
|
+
let count = 1;
|
|
484
|
+
while (count < queue.length && time - queue[count].queuedAt >= maxRetryAgeMs)
|
|
485
|
+
count += 1;
|
|
486
|
+
for (const entry of queue.splice(0, count))
|
|
487
|
+
queueBytes -= entry.bytes;
|
|
488
|
+
drop('delivery_failed', count);
|
|
489
|
+
}
|
|
490
|
+
function enqueue(event) {
|
|
491
|
+
expire();
|
|
492
|
+
if (!accepting) {
|
|
493
|
+
drop('closed');
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
const bytes = Buffer.byteLength(JSON.stringify(event));
|
|
497
|
+
if (queue.length >= maxQueueEvents || bytes > maxQueueBytes - queueBytes) {
|
|
498
|
+
drop('queue_full');
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
const time = performance.now();
|
|
502
|
+
queue.push({ event, bytes, queuedAt: time, nextAttemptAt: time, attempts: 0 });
|
|
503
|
+
queueBytes += bytes;
|
|
504
|
+
if (debug)
|
|
505
|
+
debugLine(describeEvent(event));
|
|
506
|
+
}
|
|
507
|
+
/** Captures the time and starts context resolution; async resolvers run concurrently with the handler. */
|
|
508
|
+
function begin(context) {
|
|
509
|
+
let resolved;
|
|
510
|
+
let pendingContext;
|
|
511
|
+
try {
|
|
512
|
+
resolved = typeof context === 'function' ? context() : context;
|
|
513
|
+
if (isThenable(resolved)) {
|
|
514
|
+
const promise = Promise.resolve(resolved).then(snapshot);
|
|
515
|
+
promise.catch(() => { }); // Observed by finish(); never an unhandled rejection.
|
|
516
|
+
pendingContext = promise;
|
|
517
|
+
}
|
|
518
|
+
else
|
|
519
|
+
pendingContext = snapshot(resolved);
|
|
520
|
+
}
|
|
521
|
+
catch {
|
|
522
|
+
throw new ContextFailure();
|
|
523
|
+
}
|
|
524
|
+
// A clock failure is an SDK failure, not a context failure.
|
|
525
|
+
return { occurredAt: now().toISOString(), context: pendingContext };
|
|
526
|
+
}
|
|
527
|
+
function buildEvent(kind, resolved, occurredAt, toolName, outcome, durationMs) {
|
|
528
|
+
const event = {
|
|
529
|
+
schemaVersion: 1, eventId: randomUUID(), projectId, serverId, environment, occurredAt, kind,
|
|
530
|
+
clientApplication: 'unknown',
|
|
531
|
+
};
|
|
532
|
+
const unknownTool = toolName !== undefined && !tools.has(toolName);
|
|
533
|
+
if (toolName !== undefined)
|
|
534
|
+
event.toolName = unknownTool ? '__unknown_tool__' : toolName;
|
|
535
|
+
if (outcome !== undefined)
|
|
536
|
+
event.outcome = outcome;
|
|
537
|
+
if (durationMs !== undefined)
|
|
538
|
+
event.durationMs = durationMs;
|
|
539
|
+
let unknownClient = false;
|
|
540
|
+
let identityUnavailable = false;
|
|
541
|
+
if (resolved !== undefined) {
|
|
542
|
+
try {
|
|
543
|
+
const { subject, clientApplication, sourceTag, operationId } = resolved;
|
|
544
|
+
if (clientApplication !== undefined) {
|
|
545
|
+
const label = typeof clientApplication === 'string' && clientApplication.length <= MAX_CLIENT_LABEL
|
|
546
|
+
? clientApplication.toLowerCase() : undefined;
|
|
547
|
+
const configured = label === undefined ? undefined : clients.get(label);
|
|
548
|
+
if (configured !== undefined)
|
|
549
|
+
event.clientApplication = configured;
|
|
550
|
+
// An explicit 'unknown' is an honest answer, not a missing alias.
|
|
551
|
+
else
|
|
552
|
+
unknownClient = label !== 'unknown';
|
|
553
|
+
}
|
|
554
|
+
if (sourceTag !== undefined && sources.has(sourceTag))
|
|
555
|
+
event.sourceTag = sourceTag;
|
|
556
|
+
if (subject !== undefined) {
|
|
557
|
+
if (identitySecret === undefined)
|
|
558
|
+
identityUnavailable = true;
|
|
559
|
+
else {
|
|
560
|
+
// A plain user ID belongs to the project's own namespace.
|
|
561
|
+
const { issuer, tenant, id, type = 'user' } = typeof subject === 'string' ? { issuer: projectId, id: subject } : subject;
|
|
562
|
+
const identity = { issuer, id, type };
|
|
563
|
+
if (tenant !== undefined)
|
|
564
|
+
identity.tenant = tenant;
|
|
565
|
+
event.subjectHash = hashSubject(identitySecret, projectId, identity);
|
|
566
|
+
event.subjectType = type;
|
|
567
|
+
event.identityKeyVersion = identityKeyVersion;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
if (operationId !== undefined) {
|
|
571
|
+
if (!rawString(operationId))
|
|
572
|
+
throw new Error();
|
|
573
|
+
if (identitySecret === undefined)
|
|
574
|
+
identityUnavailable = true;
|
|
575
|
+
else
|
|
576
|
+
event.operationHash = createHmac('sha256', identitySecret).update(JSON.stringify(['operation', projectId, operationId])).digest('hex');
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
catch {
|
|
580
|
+
throw new ContextFailure();
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
const validated = validateEvent(event);
|
|
584
|
+
// Count allowlist misses only for events that are actually built.
|
|
585
|
+
if (unknownTool) {
|
|
586
|
+
counts.unknownTools += 1;
|
|
587
|
+
diagnose('unknown_tool', 1);
|
|
588
|
+
}
|
|
589
|
+
if (unknownClient) {
|
|
590
|
+
counts.unknownClients += 1;
|
|
591
|
+
diagnose('unknown_client', 1);
|
|
592
|
+
}
|
|
593
|
+
if (identityUnavailable)
|
|
594
|
+
diagnose('identity_unavailable', 1);
|
|
595
|
+
return validated;
|
|
596
|
+
}
|
|
597
|
+
/** Context failures are diagnosed; clock and validation failures only count as drops. */
|
|
598
|
+
function dropFailedEvent(error) {
|
|
599
|
+
if (error instanceof ContextFailure)
|
|
600
|
+
drop('invalid_context');
|
|
601
|
+
else
|
|
602
|
+
counts.dropped += 1;
|
|
603
|
+
}
|
|
604
|
+
/** Builds and enqueues the event once its context is available; never blocks the caller. */
|
|
605
|
+
function finish(pending, kind, toolName, outcome, durationMs) {
|
|
606
|
+
const complete = (resolved) => {
|
|
607
|
+
try {
|
|
608
|
+
enqueue(buildEvent(kind, resolved, pending.occurredAt, toolName, outcome, durationMs));
|
|
609
|
+
}
|
|
610
|
+
catch (error) {
|
|
611
|
+
dropFailedEvent(error);
|
|
612
|
+
}
|
|
613
|
+
};
|
|
614
|
+
if (pending.context instanceof Promise)
|
|
615
|
+
pending.context.then(complete, () => drop('invalid_context'));
|
|
616
|
+
else
|
|
617
|
+
complete(pending.context);
|
|
618
|
+
}
|
|
619
|
+
function startSink(entries) {
|
|
620
|
+
for (const entry of entries)
|
|
621
|
+
entry.attempts += 1;
|
|
622
|
+
if (entries.some((entry) => entry.attempts > 1))
|
|
623
|
+
counts.retries += 1;
|
|
624
|
+
const attempt = { entries, startedAt: performance.now(), timeoutCounted: false, promise: Promise.resolve() };
|
|
625
|
+
activeSink = attempt;
|
|
626
|
+
const batch = Object.freeze(entries.map((entry) => entry.event));
|
|
627
|
+
attempt.promise = Promise.resolve().then(() => sink(batch)).then(() => {
|
|
628
|
+
const sent = remove(entries, 'sent');
|
|
629
|
+
if (debug && sent > 0)
|
|
630
|
+
debugLine(`sent ${sent} event${sent === 1 ? '' : 's'}`);
|
|
631
|
+
}, (error) => {
|
|
632
|
+
if (!attempt.timeoutCounted)
|
|
633
|
+
counts.sinkErrors += 1;
|
|
634
|
+
const failure = getOtlpFailure(error);
|
|
635
|
+
if (failure?.retryable === false) {
|
|
636
|
+
const removed = remove(entries, 'dropped');
|
|
637
|
+
const code = failure.status === 401 ? 'authentication_failed'
|
|
638
|
+
: failure.status === 403 ? 'project_rejected' : 'delivery_rejected';
|
|
639
|
+
diagnose(code, removed, failure.status);
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
const time = performance.now();
|
|
643
|
+
const exhausted = entries.filter((entry) => entry.attempts > maxRetries || time - entry.queuedAt >= maxRetryAgeMs);
|
|
644
|
+
diagnose('delivery_failed', remove(exhausted, 'dropped'));
|
|
645
|
+
for (const entry of entries) {
|
|
646
|
+
const backoff = retryDelayMs * 2 ** Math.min(entry.attempts - 1, 20);
|
|
647
|
+
const remaining = Math.max(0, maxRetryAgeMs - (time - entry.queuedAt));
|
|
648
|
+
entry.nextAttemptAt = time + Math.min(Math.max(backoff, failure?.retryAfterMs ?? 0), remaining);
|
|
649
|
+
}
|
|
650
|
+
}).finally(() => {
|
|
651
|
+
if (activeSink === attempt)
|
|
652
|
+
activeSink = undefined;
|
|
653
|
+
});
|
|
654
|
+
}
|
|
655
|
+
/** Entries covered by the current flush; the queue is ordered by queuedAt. */
|
|
656
|
+
function flushable() {
|
|
657
|
+
let count = 0;
|
|
658
|
+
while (count < queue.length && queue[count].queuedAt <= flushCutoff)
|
|
659
|
+
count += 1;
|
|
660
|
+
return queue.slice(0, count);
|
|
661
|
+
}
|
|
662
|
+
async function pump(deadline) {
|
|
663
|
+
while (performance.now() < deadline) {
|
|
664
|
+
expire();
|
|
665
|
+
if (queue.length === 0 || queue[0].queuedAt > flushCutoff)
|
|
666
|
+
return;
|
|
667
|
+
if (activeSink) {
|
|
668
|
+
const attempt = activeSink;
|
|
669
|
+
const sinkDeadline = attempt.startedAt + sinkTimeoutMs;
|
|
670
|
+
const time = performance.now();
|
|
671
|
+
if (time >= sinkDeadline && !attempt.timeoutCounted) {
|
|
672
|
+
counts.sinkErrors += 1;
|
|
673
|
+
attempt.timeoutCounted = true;
|
|
674
|
+
}
|
|
675
|
+
// A timed-out attempt may still acknowledge during a later bounded
|
|
676
|
+
// flush. Give that promise time to settle without starting a new write.
|
|
677
|
+
const waitDeadline = attempt.timeoutCounted ? Math.min(time + sinkTimeoutMs, deadline) : Math.min(sinkDeadline, deadline);
|
|
678
|
+
const completed = await waitFor(attempt.promise, Math.max(0, waitDeadline - time));
|
|
679
|
+
if (!completed) {
|
|
680
|
+
// A caller can stop waiting before a healthy sink's own deadline.
|
|
681
|
+
// Count only an actual sink timeout, across all subsequent flushes.
|
|
682
|
+
if (performance.now() >= sinkDeadline && !attempt.timeoutCounted) {
|
|
683
|
+
counts.sinkErrors += 1;
|
|
684
|
+
attempt.timeoutCounted = true;
|
|
685
|
+
}
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
continue;
|
|
689
|
+
}
|
|
690
|
+
const time = performance.now();
|
|
691
|
+
const eligible = flushable();
|
|
692
|
+
const ready = eligible.filter((entry) => entry.nextAttemptAt <= time).slice(0, batchSize);
|
|
693
|
+
if (ready.length > 0) {
|
|
694
|
+
startSink(ready);
|
|
695
|
+
continue;
|
|
696
|
+
}
|
|
697
|
+
const next = Math.min(...eligible.map((entry) => entry.nextAttemptAt));
|
|
698
|
+
await sleep(Math.max(1, Math.min(next - time, deadline - time)));
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
async function flush(options = {}) {
|
|
702
|
+
const timeoutMs = options.timeoutMs ?? flushTimeoutMs;
|
|
703
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs < 0)
|
|
704
|
+
return;
|
|
705
|
+
const deadline = performance.now() + Math.min(timeoutMs, 2_147_483_647);
|
|
706
|
+
flushCutoff = performance.now();
|
|
707
|
+
if (!activePump) {
|
|
708
|
+
const task = pump(deadline);
|
|
709
|
+
activePump = task;
|
|
710
|
+
void task.finally(() => {
|
|
711
|
+
if (activePump === task)
|
|
712
|
+
activePump = undefined;
|
|
713
|
+
}).catch(() => { });
|
|
714
|
+
}
|
|
715
|
+
await waitFor(activePump, Math.max(0, deadline - performance.now()));
|
|
716
|
+
}
|
|
717
|
+
const timer = flushIntervalMs > 0 ? setInterval(() => { void flush().catch(() => { }); }, flushIntervalMs) : undefined;
|
|
718
|
+
timer?.unref();
|
|
719
|
+
const instance = {
|
|
720
|
+
async observeTool(toolName, handler, context) {
|
|
721
|
+
let pending;
|
|
722
|
+
try {
|
|
723
|
+
if (accepting)
|
|
724
|
+
pending = begin(context);
|
|
725
|
+
else
|
|
726
|
+
drop('closed');
|
|
727
|
+
}
|
|
728
|
+
catch (error) {
|
|
729
|
+
dropFailedEvent(error);
|
|
730
|
+
}
|
|
731
|
+
const started = performance.now();
|
|
732
|
+
let result;
|
|
733
|
+
try {
|
|
734
|
+
result = await handler();
|
|
735
|
+
}
|
|
736
|
+
catch (error) {
|
|
737
|
+
if (pending)
|
|
738
|
+
finish(pending, 'tool_call', toolName, 'exception', Math.max(0, performance.now() - started));
|
|
739
|
+
throw error;
|
|
740
|
+
}
|
|
741
|
+
if (pending) {
|
|
742
|
+
const durationMs = Math.max(0, performance.now() - started);
|
|
743
|
+
let outcome;
|
|
744
|
+
try {
|
|
745
|
+
outcome = outcomeOf(result);
|
|
746
|
+
}
|
|
747
|
+
catch {
|
|
748
|
+
counts.dropped += 1;
|
|
749
|
+
}
|
|
750
|
+
if (outcome !== undefined)
|
|
751
|
+
finish(pending, 'tool_call', toolName, outcome, durationMs);
|
|
752
|
+
}
|
|
753
|
+
return result;
|
|
754
|
+
},
|
|
755
|
+
recordMilestone(kind, context, options = {}) {
|
|
756
|
+
try {
|
|
757
|
+
if (kind !== 'authorization' && kind !== 'value_completed')
|
|
758
|
+
throw new Error();
|
|
759
|
+
if (!accepting) {
|
|
760
|
+
drop('closed');
|
|
761
|
+
return;
|
|
762
|
+
}
|
|
763
|
+
finish(begin(context), kind, options.toolName);
|
|
764
|
+
}
|
|
765
|
+
catch (error) {
|
|
766
|
+
dropFailedEvent(error);
|
|
767
|
+
}
|
|
768
|
+
},
|
|
769
|
+
allowTools(names) {
|
|
770
|
+
if (!Array.isArray(names))
|
|
771
|
+
configurationFailure('allowTools expects an array of tool aliases');
|
|
772
|
+
names.forEach((name, index) => { if (!isSlug(name))
|
|
773
|
+
configurationFailure(`tool name ${index} ${ALIAS_RULE}`); });
|
|
774
|
+
const added = names.filter((name) => !tools.has(name));
|
|
775
|
+
if (tools.size + new Set(added).size > MAX_TOOLS)
|
|
776
|
+
configurationFailure(`tools must contain at most ${MAX_TOOLS} aliases`);
|
|
777
|
+
for (const name of added)
|
|
778
|
+
tools.add(name);
|
|
779
|
+
},
|
|
780
|
+
flush,
|
|
781
|
+
close(options = {}) {
|
|
782
|
+
if (!closePromise) {
|
|
783
|
+
accepting = false;
|
|
784
|
+
if (timer)
|
|
785
|
+
clearInterval(timer);
|
|
786
|
+
closePromise = flush(options).finally(() => { diagnose('closed', remove([...queue], 'dropped')); });
|
|
787
|
+
}
|
|
788
|
+
return closePromise;
|
|
789
|
+
},
|
|
790
|
+
getStats() {
|
|
791
|
+
expire();
|
|
792
|
+
return { queued: queue.length, queuedBytes: queueBytes, ...counts };
|
|
793
|
+
},
|
|
794
|
+
};
|
|
795
|
+
instances.set(instance, Object.freeze({ projectId, serverId, environment, identity: identitySecret !== undefined,
|
|
796
|
+
...(delivery === undefined ? {} : { delivery: Object.freeze(delivery) }) }));
|
|
797
|
+
return instance;
|
|
798
|
+
}
|
|
799
|
+
//# sourceMappingURL=analytics.js.map
|