@frontmcp/observability 1.10.8 → 1.10.9-rc.2
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/esm/index.mjs +1 -3657
- package/esm/package.json +3 -3
- package/index.js +1 -3700
- package/package.json +3 -3
package/esm/index.mjs
CHANGED
|
@@ -1,3660 +1,4 @@
|
|
|
1
1
|
var __frontmcpModule = typeof process !== "undefined" && typeof process.getBuiltinModule === "function" ? process.getBuiltinModule("module") : undefined;
|
|
2
2
|
const require = __frontmcpModule ? __frontmcpModule.createRequire(import.meta.url || 'file:///') : undefined;
|
|
3
3
|
// __frontmcpCreateRequire
|
|
4
|
-
var __defProp = Object.defineProperty;
|
|
5
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
9
|
-
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
10
|
-
}) : x)(function(x) {
|
|
11
|
-
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
12
|
-
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
13
|
-
});
|
|
14
|
-
var __esm = (fn, res, err) => function __init() {
|
|
15
|
-
if (err) throw err[0];
|
|
16
|
-
try {
|
|
17
|
-
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
18
|
-
} catch (e) {
|
|
19
|
-
throw err = [e], e;
|
|
20
|
-
}
|
|
21
|
-
};
|
|
22
|
-
var __export = (target, all) => {
|
|
23
|
-
for (var name in all)
|
|
24
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
25
|
-
};
|
|
26
|
-
var __copyProps = (to, from, except, desc) => {
|
|
27
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
28
|
-
for (let key of __getOwnPropNames(from))
|
|
29
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
30
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
31
|
-
}
|
|
32
|
-
return to;
|
|
33
|
-
};
|
|
34
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
35
|
-
var __decorateClass = (decorators, target, key, kind) => {
|
|
36
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
37
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
38
|
-
if (decorator = decorators[i])
|
|
39
|
-
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
40
|
-
if (kind && result) __defProp(target, key, result);
|
|
41
|
-
return result;
|
|
42
|
-
};
|
|
43
|
-
|
|
44
|
-
// libs/observability/src/logging/sinks/winston.sink.ts
|
|
45
|
-
var winston_sink_exports = {};
|
|
46
|
-
__export(winston_sink_exports, {
|
|
47
|
-
WinstonSink: () => WinstonSink
|
|
48
|
-
});
|
|
49
|
-
function mapToWinstonLevel(level) {
|
|
50
|
-
switch (level) {
|
|
51
|
-
case "debug":
|
|
52
|
-
case "verbose":
|
|
53
|
-
return "debug";
|
|
54
|
-
case "info":
|
|
55
|
-
return "info";
|
|
56
|
-
case "warn":
|
|
57
|
-
return "warn";
|
|
58
|
-
case "error":
|
|
59
|
-
return "error";
|
|
60
|
-
default:
|
|
61
|
-
return "info";
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
var WinstonSink;
|
|
65
|
-
var init_winston_sink = __esm({
|
|
66
|
-
"libs/observability/src/logging/sinks/winston.sink.ts"() {
|
|
67
|
-
"use strict";
|
|
68
|
-
WinstonSink = class {
|
|
69
|
-
constructor(logger) {
|
|
70
|
-
this.logger = logger;
|
|
71
|
-
}
|
|
72
|
-
write(entry) {
|
|
73
|
-
const { message, level, ...meta } = entry;
|
|
74
|
-
const winstonLevel = mapToWinstonLevel(level);
|
|
75
|
-
switch (winstonLevel) {
|
|
76
|
-
case "debug":
|
|
77
|
-
this.logger.debug(message, meta);
|
|
78
|
-
break;
|
|
79
|
-
case "info":
|
|
80
|
-
this.logger.info(message, meta);
|
|
81
|
-
break;
|
|
82
|
-
case "warn":
|
|
83
|
-
this.logger.warn(message, meta);
|
|
84
|
-
break;
|
|
85
|
-
case "error":
|
|
86
|
-
this.logger.error(message, meta);
|
|
87
|
-
break;
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
};
|
|
91
|
-
}
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
// libs/observability/src/logging/sinks/pino.sink.ts
|
|
95
|
-
var pino_sink_exports = {};
|
|
96
|
-
__export(pino_sink_exports, {
|
|
97
|
-
PinoSink: () => PinoSink
|
|
98
|
-
});
|
|
99
|
-
function mapToPinoLevel(level) {
|
|
100
|
-
switch (level) {
|
|
101
|
-
case "debug":
|
|
102
|
-
case "verbose":
|
|
103
|
-
return "debug";
|
|
104
|
-
case "info":
|
|
105
|
-
return "info";
|
|
106
|
-
case "warn":
|
|
107
|
-
return "warn";
|
|
108
|
-
case "error":
|
|
109
|
-
return "error";
|
|
110
|
-
default:
|
|
111
|
-
return "info";
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
var PinoSink;
|
|
115
|
-
var init_pino_sink = __esm({
|
|
116
|
-
"libs/observability/src/logging/sinks/pino.sink.ts"() {
|
|
117
|
-
"use strict";
|
|
118
|
-
PinoSink = class {
|
|
119
|
-
constructor(logger) {
|
|
120
|
-
this.logger = logger;
|
|
121
|
-
}
|
|
122
|
-
write(entry) {
|
|
123
|
-
const { message, level, ...obj } = entry;
|
|
124
|
-
const pinoLevel = mapToPinoLevel(level);
|
|
125
|
-
switch (pinoLevel) {
|
|
126
|
-
case "debug":
|
|
127
|
-
this.logger.debug(obj, message);
|
|
128
|
-
break;
|
|
129
|
-
case "info":
|
|
130
|
-
this.logger.info(obj, message);
|
|
131
|
-
break;
|
|
132
|
-
case "warn":
|
|
133
|
-
this.logger.warn(obj, message);
|
|
134
|
-
break;
|
|
135
|
-
case "error":
|
|
136
|
-
this.logger.error(obj, message);
|
|
137
|
-
break;
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
};
|
|
141
|
-
}
|
|
142
|
-
});
|
|
143
|
-
|
|
144
|
-
// libs/observability/src/logging/sinks/otlp.sink.ts
|
|
145
|
-
var otlp_sink_exports = {};
|
|
146
|
-
__export(otlp_sink_exports, {
|
|
147
|
-
OtlpSink: () => OtlpSink
|
|
148
|
-
});
|
|
149
|
-
var OtlpSink;
|
|
150
|
-
var init_otlp_sink = __esm({
|
|
151
|
-
"libs/observability/src/logging/sinks/otlp.sink.ts"() {
|
|
152
|
-
"use strict";
|
|
153
|
-
OtlpSink = class {
|
|
154
|
-
constructor(options) {
|
|
155
|
-
this.batch = [];
|
|
156
|
-
let base = options.endpoint;
|
|
157
|
-
while (base.endsWith("/")) {
|
|
158
|
-
base = base.slice(0, -1);
|
|
159
|
-
}
|
|
160
|
-
this.endpoint = `${base}/v1/logs`;
|
|
161
|
-
this.headers = {
|
|
162
|
-
"Content-Type": "application/json",
|
|
163
|
-
...options.headers ?? {}
|
|
164
|
-
};
|
|
165
|
-
this.batchSize = options.batchSize ?? 100;
|
|
166
|
-
this.maxQueueSize = options.maxQueueSize ?? 5e3;
|
|
167
|
-
this.serviceName = options.serviceName ?? (typeof process !== "undefined" ? process.env?.["OTEL_SERVICE_NAME"] : void 0) ?? "frontmcp-server";
|
|
168
|
-
const flushMs = options.flushIntervalMs ?? 5e3;
|
|
169
|
-
if (flushMs > 0) {
|
|
170
|
-
this.flushTimer = setInterval(() => {
|
|
171
|
-
void this.flush();
|
|
172
|
-
}, flushMs);
|
|
173
|
-
if (this.flushTimer && typeof this.flushTimer === "object" && "unref" in this.flushTimer) {
|
|
174
|
-
this.flushTimer.unref();
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
write(entry) {
|
|
179
|
-
this.batch.push(entry);
|
|
180
|
-
this.enforceCapacity();
|
|
181
|
-
if (this.batch.length >= this.batchSize) {
|
|
182
|
-
void this.flush();
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
async flush() {
|
|
186
|
-
if (this.batch.length === 0) return;
|
|
187
|
-
const entries = this.batch.splice(0);
|
|
188
|
-
const payload = this.buildOtlpPayload(entries);
|
|
189
|
-
try {
|
|
190
|
-
const controller = new AbortController();
|
|
191
|
-
const timeout = setTimeout(() => controller.abort(), 1e4);
|
|
192
|
-
try {
|
|
193
|
-
const response = await fetch(this.endpoint, {
|
|
194
|
-
method: "POST",
|
|
195
|
-
headers: this.headers,
|
|
196
|
-
body: JSON.stringify(payload),
|
|
197
|
-
signal: controller.signal
|
|
198
|
-
});
|
|
199
|
-
clearTimeout(timeout);
|
|
200
|
-
if (!response.ok) {
|
|
201
|
-
const body = await response.text().catch(() => "");
|
|
202
|
-
console.error(`[OtlpSink] Export failed: HTTP ${response.status} \u2014 ${body.slice(0, 200)}`);
|
|
203
|
-
this.requeue(entries);
|
|
204
|
-
}
|
|
205
|
-
} catch (err) {
|
|
206
|
-
clearTimeout(timeout);
|
|
207
|
-
console.debug(
|
|
208
|
-
`[OtlpSink] Export error (${entries.length} entries): ${err instanceof Error ? err.message : err}`
|
|
209
|
-
);
|
|
210
|
-
this.requeue(entries);
|
|
211
|
-
}
|
|
212
|
-
} catch {
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
requeue(entries) {
|
|
216
|
-
this.batch.unshift(...entries);
|
|
217
|
-
this.enforceCapacity();
|
|
218
|
-
}
|
|
219
|
-
enforceCapacity() {
|
|
220
|
-
if (this.batch.length > this.maxQueueSize) {
|
|
221
|
-
this.batch.splice(0, this.batch.length - this.maxQueueSize);
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
async close() {
|
|
225
|
-
if (this.flushTimer) {
|
|
226
|
-
clearInterval(this.flushTimer);
|
|
227
|
-
this.flushTimer = void 0;
|
|
228
|
-
}
|
|
229
|
-
await this.flush();
|
|
230
|
-
}
|
|
231
|
-
/**
|
|
232
|
-
* Build OTLP Logs JSON payload per the OTel spec.
|
|
233
|
-
*
|
|
234
|
-
* @see https://opentelemetry.io/docs/specs/otlp/#otlphttp-request
|
|
235
|
-
* @see https://opentelemetry.io/docs/specs/otel/logs/data-model/
|
|
236
|
-
*/
|
|
237
|
-
buildOtlpPayload(entries) {
|
|
238
|
-
return {
|
|
239
|
-
resourceLogs: [
|
|
240
|
-
{
|
|
241
|
-
resource: {
|
|
242
|
-
attributes: [{ key: "service.name", value: { stringValue: this.serviceName } }]
|
|
243
|
-
},
|
|
244
|
-
scopeLogs: [
|
|
245
|
-
{
|
|
246
|
-
scope: { name: "@frontmcp/observability" },
|
|
247
|
-
logRecords: entries.map((entry) => this.entryToLogRecord(entry))
|
|
248
|
-
}
|
|
249
|
-
]
|
|
250
|
-
}
|
|
251
|
-
]
|
|
252
|
-
};
|
|
253
|
-
}
|
|
254
|
-
entryToLogRecord(entry) {
|
|
255
|
-
const attrs = [];
|
|
256
|
-
const record = {
|
|
257
|
-
timeUnixNano: String(new Date(entry.timestamp).getTime() * 1e6),
|
|
258
|
-
severityNumber: entry.severity_number,
|
|
259
|
-
severityText: entry.level.toUpperCase(),
|
|
260
|
-
body: { stringValue: entry.message },
|
|
261
|
-
attributes: attrs
|
|
262
|
-
};
|
|
263
|
-
if (entry.trace_id) {
|
|
264
|
-
record.traceId = entry.trace_id;
|
|
265
|
-
}
|
|
266
|
-
if (entry.span_id) {
|
|
267
|
-
record.spanId = entry.span_id;
|
|
268
|
-
}
|
|
269
|
-
if (entry.trace_flags !== void 0) {
|
|
270
|
-
record.flags = entry.trace_flags;
|
|
271
|
-
}
|
|
272
|
-
if (entry.request_id) {
|
|
273
|
-
attrs.push({ key: "frontmcp.request.id", value: { stringValue: entry.request_id } });
|
|
274
|
-
}
|
|
275
|
-
if (entry.session_id_hash) {
|
|
276
|
-
attrs.push({ key: "mcp.session.id", value: { stringValue: entry.session_id_hash } });
|
|
277
|
-
}
|
|
278
|
-
if (entry.scope_id) {
|
|
279
|
-
attrs.push({ key: "frontmcp.scope.id", value: { stringValue: entry.scope_id } });
|
|
280
|
-
}
|
|
281
|
-
if (entry.flow_name) {
|
|
282
|
-
attrs.push({ key: "frontmcp.flow.name", value: { stringValue: entry.flow_name } });
|
|
283
|
-
}
|
|
284
|
-
if (entry.prefix) {
|
|
285
|
-
attrs.push({ key: "log.prefix", value: { stringValue: entry.prefix } });
|
|
286
|
-
}
|
|
287
|
-
if (entry.elapsed_ms !== void 0) {
|
|
288
|
-
attrs.push({
|
|
289
|
-
key: "elapsed_ms",
|
|
290
|
-
value: Number.isInteger(entry.elapsed_ms) ? { intValue: String(entry.elapsed_ms) } : { doubleValue: entry.elapsed_ms }
|
|
291
|
-
});
|
|
292
|
-
}
|
|
293
|
-
if (entry.error) {
|
|
294
|
-
attrs.push({ key: "error.type", value: { stringValue: entry.error.type } });
|
|
295
|
-
attrs.push({ key: "error.message", value: { stringValue: entry.error.message } });
|
|
296
|
-
if (entry.error.code) {
|
|
297
|
-
attrs.push({ key: "error.code", value: { stringValue: entry.error.code } });
|
|
298
|
-
}
|
|
299
|
-
if (entry.error.error_id) {
|
|
300
|
-
attrs.push({ key: "error.id", value: { stringValue: entry.error.error_id } });
|
|
301
|
-
}
|
|
302
|
-
if (entry.error.stack) {
|
|
303
|
-
attrs.push({ key: "error.stack", value: { stringValue: entry.error.stack } });
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
if (entry.attributes) {
|
|
307
|
-
for (const [key, value] of Object.entries(entry.attributes)) {
|
|
308
|
-
if (value == null) continue;
|
|
309
|
-
if (typeof value === "string") {
|
|
310
|
-
attrs.push({ key, value: { stringValue: value } });
|
|
311
|
-
} else if (typeof value === "number") {
|
|
312
|
-
attrs.push({
|
|
313
|
-
key,
|
|
314
|
-
value: Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value }
|
|
315
|
-
});
|
|
316
|
-
} else if (typeof value === "boolean") {
|
|
317
|
-
attrs.push({ key, value: { boolValue: value } });
|
|
318
|
-
} else {
|
|
319
|
-
attrs.push({ key, value: { stringValue: JSON.stringify(value) } });
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
return record;
|
|
324
|
-
}
|
|
325
|
-
};
|
|
326
|
-
}
|
|
327
|
-
});
|
|
328
|
-
|
|
329
|
-
// libs/observability/src/plugin/observability.plugin.ts
|
|
330
|
-
import { trace as trace6 } from "@opentelemetry/api";
|
|
331
|
-
import {
|
|
332
|
-
AgentCallHook,
|
|
333
|
-
DynamicPlugin,
|
|
334
|
-
FlowHooksOf,
|
|
335
|
-
FRONTMCP_CONTEXT as FRONTMCP_CONTEXT2,
|
|
336
|
-
HttpHook,
|
|
337
|
-
ListResourcesHook,
|
|
338
|
-
ListResourceTemplatesHook,
|
|
339
|
-
ListToolsHook,
|
|
340
|
-
Plugin,
|
|
341
|
-
ProviderScope,
|
|
342
|
-
ResourceHook,
|
|
343
|
-
ToolHook
|
|
344
|
-
} from "@frontmcp/sdk";
|
|
345
|
-
|
|
346
|
-
// libs/observability/src/logging/sinks/stdout.sink.ts
|
|
347
|
-
function defaultStream() {
|
|
348
|
-
const flag = typeof process !== "undefined" ? process.env?.["FRONTMCP_STDIO"] : void 0;
|
|
349
|
-
return flag === "1" || flag === "true" ? process.stderr : process.stdout;
|
|
350
|
-
}
|
|
351
|
-
var StdoutSink = class {
|
|
352
|
-
constructor(options) {
|
|
353
|
-
this.stream = options?.stream ?? defaultStream();
|
|
354
|
-
this.pretty = options?.pretty ?? false;
|
|
355
|
-
}
|
|
356
|
-
write(entry) {
|
|
357
|
-
const line = this.pretty ? JSON.stringify(entry, null, 2) : JSON.stringify(entry);
|
|
358
|
-
this.stream.write(line + "\n");
|
|
359
|
-
}
|
|
360
|
-
};
|
|
361
|
-
|
|
362
|
-
// libs/observability/src/logging/sinks/console.sink.ts
|
|
363
|
-
var ConsoleSink = class {
|
|
364
|
-
write(entry) {
|
|
365
|
-
const method = levelToConsoleMethod(entry.level);
|
|
366
|
-
const formatted = formatEntry(entry);
|
|
367
|
-
method(formatted);
|
|
368
|
-
}
|
|
369
|
-
};
|
|
370
|
-
function formatEntry(entry) {
|
|
371
|
-
const useAnsi = typeof process !== "undefined" && !!process.stdout?.isTTY;
|
|
372
|
-
const ts = entry.timestamp.slice(11, 23);
|
|
373
|
-
const level = entry.level.toUpperCase().padEnd(7);
|
|
374
|
-
const traceShort = entry.trace_id ? entry.trace_id.slice(0, 8) : "";
|
|
375
|
-
const reqShort = entry.request_id ? entry.request_id.slice(0, 8) : "";
|
|
376
|
-
const parts = [];
|
|
377
|
-
const DIM2 = useAnsi ? "\x1B[2m" : "";
|
|
378
|
-
const BOLD2 = useAnsi ? "\x1B[1m" : "";
|
|
379
|
-
const RESET2 = useAnsi ? "\x1B[0m" : "";
|
|
380
|
-
const levelColor = useAnsi ? LEVEL_COLORS[entry.level] ?? "" : "";
|
|
381
|
-
parts.push(`${DIM2}[${ts}]${RESET2}`);
|
|
382
|
-
parts.push(`${BOLD2}${levelColor}${level}${RESET2}`);
|
|
383
|
-
if (traceShort || reqShort) {
|
|
384
|
-
parts.push(`${DIM2}[${traceShort}${reqShort ? ":" + reqShort : ""}]${RESET2}`);
|
|
385
|
-
}
|
|
386
|
-
if (entry.prefix) parts.push(`${DIM2}[${entry.prefix}]${RESET2}`);
|
|
387
|
-
parts.push(entry.message);
|
|
388
|
-
if (entry.attributes && Object.keys(entry.attributes).length > 0) {
|
|
389
|
-
const attrs = Object.entries(entry.attributes).map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`).join(" ");
|
|
390
|
-
parts.push(`${DIM2}{ ${attrs} }${RESET2}`);
|
|
391
|
-
}
|
|
392
|
-
if (entry.error) {
|
|
393
|
-
parts.push(`[${entry.error.type}: ${entry.error.message}]`);
|
|
394
|
-
}
|
|
395
|
-
if (entry.elapsed_ms !== void 0) {
|
|
396
|
-
parts.push(`${DIM2}(${entry.elapsed_ms}ms)${RESET2}`);
|
|
397
|
-
}
|
|
398
|
-
return parts.join(" ");
|
|
399
|
-
}
|
|
400
|
-
var LEVEL_COLORS = {
|
|
401
|
-
debug: "\x1B[34m",
|
|
402
|
-
verbose: "\x1B[90m",
|
|
403
|
-
info: "\x1B[32m",
|
|
404
|
-
warn: "\x1B[33m",
|
|
405
|
-
error: "\x1B[31m"
|
|
406
|
-
};
|
|
407
|
-
function levelToConsoleMethod(level) {
|
|
408
|
-
switch (level) {
|
|
409
|
-
case "debug":
|
|
410
|
-
case "verbose":
|
|
411
|
-
return console.debug;
|
|
412
|
-
case "info":
|
|
413
|
-
return console.info;
|
|
414
|
-
case "warn":
|
|
415
|
-
return console.warn;
|
|
416
|
-
case "error":
|
|
417
|
-
return console.error;
|
|
418
|
-
default:
|
|
419
|
-
return console.log;
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
// libs/observability/src/logging/sinks/callback.sink.ts
|
|
424
|
-
var CallbackSink = class {
|
|
425
|
-
constructor(fn) {
|
|
426
|
-
this.fn = fn;
|
|
427
|
-
}
|
|
428
|
-
write(entry) {
|
|
429
|
-
this.fn(entry);
|
|
430
|
-
}
|
|
431
|
-
};
|
|
432
|
-
|
|
433
|
-
// libs/observability/src/logging/sink.factory.ts
|
|
434
|
-
function createSink(config) {
|
|
435
|
-
switch (config.type) {
|
|
436
|
-
case "stdout":
|
|
437
|
-
return new StdoutSink({ stream: config.stream, pretty: config.pretty });
|
|
438
|
-
case "console":
|
|
439
|
-
return new ConsoleSink();
|
|
440
|
-
case "winston": {
|
|
441
|
-
const { WinstonSink: WinstonSink2 } = (init_winston_sink(), __toCommonJS(winston_sink_exports));
|
|
442
|
-
return new WinstonSink2(config.logger);
|
|
443
|
-
}
|
|
444
|
-
case "pino": {
|
|
445
|
-
const { PinoSink: PinoSink2 } = (init_pino_sink(), __toCommonJS(pino_sink_exports));
|
|
446
|
-
return new PinoSink2(config.logger);
|
|
447
|
-
}
|
|
448
|
-
case "callback":
|
|
449
|
-
return new CallbackSink(config.fn);
|
|
450
|
-
case "otlp": {
|
|
451
|
-
const { OtlpSink: OtlpSink2 } = (init_otlp_sink(), __toCommonJS(otlp_sink_exports));
|
|
452
|
-
return new OtlpSink2({
|
|
453
|
-
endpoint: config.endpoint ?? (typeof process !== "undefined" ? process.env?.["OTEL_EXPORTER_OTLP_ENDPOINT"] : void 0) ?? "http://localhost:4318",
|
|
454
|
-
headers: config.headers,
|
|
455
|
-
batchSize: config.batchSize,
|
|
456
|
-
flushIntervalMs: config.flushIntervalMs,
|
|
457
|
-
serviceName: config.serviceName
|
|
458
|
-
});
|
|
459
|
-
}
|
|
460
|
-
default:
|
|
461
|
-
throw new Error(`Unknown sink type: ${config.type}`);
|
|
462
|
-
}
|
|
463
|
-
}
|
|
464
|
-
function createSinks(configs) {
|
|
465
|
-
if (configs && configs.length > 0) {
|
|
466
|
-
return configs.map(createSink);
|
|
467
|
-
}
|
|
468
|
-
return [];
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
// libs/observability/src/logging/structured-log-transport.ts
|
|
472
|
-
import { LogTransportInterface, LogLevelName, LogTransport } from "@frontmcp/sdk";
|
|
473
|
-
|
|
474
|
-
// libs/observability/src/logging/structured-log.types.ts
|
|
475
|
-
var LOG_LEVEL_TO_OTEL_SEVERITY = {
|
|
476
|
-
debug: 5,
|
|
477
|
-
// DEBUG
|
|
478
|
-
verbose: 6,
|
|
479
|
-
// DEBUG2
|
|
480
|
-
info: 9,
|
|
481
|
-
// INFO
|
|
482
|
-
warn: 13,
|
|
483
|
-
// WARN
|
|
484
|
-
error: 17
|
|
485
|
-
// ERROR
|
|
486
|
-
};
|
|
487
|
-
|
|
488
|
-
// libs/observability/src/logging/redaction.ts
|
|
489
|
-
var REDACTED = "[REDACTED]";
|
|
490
|
-
function redactFields(obj, fields, maxDepth = 5) {
|
|
491
|
-
if (fields.length === 0) return obj;
|
|
492
|
-
const lowerFields = new Set(fields.map((f) => f.toLowerCase()));
|
|
493
|
-
return redactRecursive(obj, lowerFields, 0, maxDepth);
|
|
494
|
-
}
|
|
495
|
-
function redactRecursive(obj, fields, depth, maxDepth) {
|
|
496
|
-
if (depth >= maxDepth) return obj;
|
|
497
|
-
const result = {};
|
|
498
|
-
for (const [key, value] of Object.entries(obj)) {
|
|
499
|
-
if (fields.has(key.toLowerCase())) {
|
|
500
|
-
result[key] = REDACTED;
|
|
501
|
-
} else if (isPlainObject(value)) {
|
|
502
|
-
result[key] = redactRecursive(value, fields, depth + 1, maxDepth);
|
|
503
|
-
} else if (Array.isArray(value)) {
|
|
504
|
-
result[key] = value.map(
|
|
505
|
-
(item) => isPlainObject(item) ? redactRecursive(item, fields, depth + 1, maxDepth) : item
|
|
506
|
-
);
|
|
507
|
-
} else {
|
|
508
|
-
result[key] = value;
|
|
509
|
-
}
|
|
510
|
-
}
|
|
511
|
-
return result;
|
|
512
|
-
}
|
|
513
|
-
function isPlainObject(value) {
|
|
514
|
-
if (typeof value !== "object" || value === null) return false;
|
|
515
|
-
const proto = Object.getPrototypeOf(value);
|
|
516
|
-
return proto === Object.prototype || proto === null;
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
// libs/observability/src/logging/structured-log-transport.ts
|
|
520
|
-
var StructuredLogTransport = class extends LogTransportInterface {
|
|
521
|
-
constructor(sinks, options, contextAccessor) {
|
|
522
|
-
super();
|
|
523
|
-
this.sinks = sinks;
|
|
524
|
-
this.redactFieldNames = options?.redactFields ?? [];
|
|
525
|
-
this.includeStacks = options?.includeStacks ?? true;
|
|
526
|
-
this.staticFields = options?.staticFields ?? {};
|
|
527
|
-
this.getContext = contextAccessor;
|
|
528
|
-
}
|
|
529
|
-
log(rec) {
|
|
530
|
-
const entry = this.buildEntry(rec);
|
|
531
|
-
if (this.onEntry) {
|
|
532
|
-
try {
|
|
533
|
-
this.onEntry(entry);
|
|
534
|
-
} catch {
|
|
535
|
-
}
|
|
536
|
-
}
|
|
537
|
-
for (const sink of this.sinks) {
|
|
538
|
-
try {
|
|
539
|
-
sink.write(entry);
|
|
540
|
-
} catch {
|
|
541
|
-
}
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
buildEntry(rec) {
|
|
545
|
-
const levelName = LogLevelName[rec.level] ?? "info";
|
|
546
|
-
const entry = {
|
|
547
|
-
...this.staticFields,
|
|
548
|
-
timestamp: rec.timestamp.toISOString(),
|
|
549
|
-
level: levelName,
|
|
550
|
-
severity_number: LOG_LEVEL_TO_OTEL_SEVERITY[levelName] ?? 9,
|
|
551
|
-
message: String(rec.message)
|
|
552
|
-
};
|
|
553
|
-
if (rec.prefix) {
|
|
554
|
-
entry.prefix = rec.prefix;
|
|
555
|
-
}
|
|
556
|
-
const ctx = this.getContext?.();
|
|
557
|
-
if (ctx) {
|
|
558
|
-
entry.trace_id = ctx.traceContext.traceId;
|
|
559
|
-
entry.span_id = ctx.traceContext.parentId;
|
|
560
|
-
entry.trace_flags = ctx.traceContext.traceFlags;
|
|
561
|
-
entry.request_id = ctx.requestId;
|
|
562
|
-
entry.session_id_hash = ctx.sessionIdHash;
|
|
563
|
-
entry.scope_id = ctx.scopeId;
|
|
564
|
-
if (ctx.flowName) {
|
|
565
|
-
entry.flow_name = ctx.flowName;
|
|
566
|
-
}
|
|
567
|
-
entry.elapsed_ms = ctx.elapsed;
|
|
568
|
-
}
|
|
569
|
-
this.processArgs(rec.args, entry);
|
|
570
|
-
return entry;
|
|
571
|
-
}
|
|
572
|
-
processArgs(args, entry) {
|
|
573
|
-
const attributes = {};
|
|
574
|
-
let hasAttributes = false;
|
|
575
|
-
for (const arg of args) {
|
|
576
|
-
if (arg instanceof Error) {
|
|
577
|
-
entry.error = this.buildError(arg);
|
|
578
|
-
} else if (typeof arg === "object" && arg !== null && !Array.isArray(arg)) {
|
|
579
|
-
const obj = arg;
|
|
580
|
-
const redacted = this.redactFieldNames.length > 0 ? redactFields(obj, this.redactFieldNames) : obj;
|
|
581
|
-
Object.assign(attributes, redacted);
|
|
582
|
-
hasAttributes = true;
|
|
583
|
-
}
|
|
584
|
-
}
|
|
585
|
-
if (hasAttributes) {
|
|
586
|
-
entry.attributes = attributes;
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
buildError(err) {
|
|
590
|
-
const result = {
|
|
591
|
-
type: err.constructor.name,
|
|
592
|
-
message: err.message
|
|
593
|
-
};
|
|
594
|
-
if ("code" in err && typeof err.code === "number") {
|
|
595
|
-
result.code = String(err.code);
|
|
596
|
-
}
|
|
597
|
-
if ("errorId" in err && typeof err.errorId === "string") {
|
|
598
|
-
result.error_id = err.errorId;
|
|
599
|
-
}
|
|
600
|
-
if (this.includeStacks && err.stack) {
|
|
601
|
-
result.stack = err.stack;
|
|
602
|
-
}
|
|
603
|
-
return result;
|
|
604
|
-
}
|
|
605
|
-
};
|
|
606
|
-
StructuredLogTransport = __decorateClass([
|
|
607
|
-
LogTransport({
|
|
608
|
-
name: "StructuredLogTransport",
|
|
609
|
-
description: "Produces structured log objects and forwards to configurable sinks"
|
|
610
|
-
})
|
|
611
|
-
], StructuredLogTransport);
|
|
612
|
-
|
|
613
|
-
// libs/observability/src/otel/otel.tokens.ts
|
|
614
|
-
var OTEL_TRACER = /* @__PURE__ */ Symbol.for("frontmcp:observability:otel-tracer");
|
|
615
|
-
var OTEL_CONFIG = /* @__PURE__ */ Symbol.for("frontmcp:observability:otel-config");
|
|
616
|
-
|
|
617
|
-
// libs/observability/src/request-log/request-log.collector.ts
|
|
618
|
-
var RequestLogCollector = class {
|
|
619
|
-
constructor(context, options) {
|
|
620
|
-
this.entries = [];
|
|
621
|
-
this.hooksTriggered = /* @__PURE__ */ new Set();
|
|
622
|
-
this.authenticated = false;
|
|
623
|
-
this.status = "ok";
|
|
624
|
-
this.finalized = false;
|
|
625
|
-
this.requestId = context.requestId;
|
|
626
|
-
this.traceId = context.traceId;
|
|
627
|
-
this.sessionIdHash = context.sessionIdHash;
|
|
628
|
-
this.scopeId = context.scopeId;
|
|
629
|
-
this.startTime = /* @__PURE__ */ new Date();
|
|
630
|
-
this.maxEntries = options?.maxEntries ?? 500;
|
|
631
|
-
this.onComplete = options?.onRequestComplete;
|
|
632
|
-
}
|
|
633
|
-
/**
|
|
634
|
-
* Add a structured log entry to this request's log.
|
|
635
|
-
* Called by StructuredLogTransport for each log record that
|
|
636
|
-
* matches this request's requestId.
|
|
637
|
-
*/
|
|
638
|
-
addEntry(entry) {
|
|
639
|
-
if (this.finalized || this.entries.length >= this.maxEntries) return;
|
|
640
|
-
const logEntry = {
|
|
641
|
-
timestamp: entry.timestamp,
|
|
642
|
-
level: entry.level,
|
|
643
|
-
message: entry.message
|
|
644
|
-
};
|
|
645
|
-
if (entry.flow_name) {
|
|
646
|
-
logEntry.stage = entry.flow_name;
|
|
647
|
-
}
|
|
648
|
-
if (entry.elapsed_ms !== void 0) {
|
|
649
|
-
logEntry.elapsed_ms = entry.elapsed_ms;
|
|
650
|
-
}
|
|
651
|
-
if (entry.attributes && Object.keys(entry.attributes).length > 0) {
|
|
652
|
-
logEntry.attributes = entry.attributes;
|
|
653
|
-
}
|
|
654
|
-
this.entries.push(logEntry);
|
|
655
|
-
}
|
|
656
|
-
/**
|
|
657
|
-
* Record a hook stage that was triggered during this request.
|
|
658
|
-
*/
|
|
659
|
-
addHook(stage) {
|
|
660
|
-
this.hooksTriggered.add(stage);
|
|
661
|
-
}
|
|
662
|
-
/**
|
|
663
|
-
* Set HTTP request metadata.
|
|
664
|
-
*/
|
|
665
|
-
setHttpInfo(method, path) {
|
|
666
|
-
this.httpMethod = method;
|
|
667
|
-
this.httpPath = path;
|
|
668
|
-
}
|
|
669
|
-
/**
|
|
670
|
-
* Set the MCP JSON-RPC method being invoked.
|
|
671
|
-
*/
|
|
672
|
-
setRpcMethod(method) {
|
|
673
|
-
this.rpcMethod = method;
|
|
674
|
-
}
|
|
675
|
-
/**
|
|
676
|
-
* Set the tool name being invoked.
|
|
677
|
-
*/
|
|
678
|
-
setToolName(name) {
|
|
679
|
-
this.toolName = name;
|
|
680
|
-
}
|
|
681
|
-
/**
|
|
682
|
-
* Set the resource URI being read.
|
|
683
|
-
*/
|
|
684
|
-
setResourceUri(uri) {
|
|
685
|
-
this.resourceUri = uri;
|
|
686
|
-
}
|
|
687
|
-
/**
|
|
688
|
-
* Set the prompt name being invoked.
|
|
689
|
-
*/
|
|
690
|
-
setPromptName(name) {
|
|
691
|
-
this.promptName = name;
|
|
692
|
-
}
|
|
693
|
-
/**
|
|
694
|
-
* Set authentication info.
|
|
695
|
-
*/
|
|
696
|
-
setAuthInfo(type, authenticated) {
|
|
697
|
-
this.authType = type;
|
|
698
|
-
this.authenticated = authenticated;
|
|
699
|
-
}
|
|
700
|
-
/**
|
|
701
|
-
* Set request status.
|
|
702
|
-
*/
|
|
703
|
-
setStatus(status, statusCode) {
|
|
704
|
-
this.status = status;
|
|
705
|
-
this.statusCode = statusCode;
|
|
706
|
-
}
|
|
707
|
-
/**
|
|
708
|
-
* Set the HTTP status the request was answered with; one of 400 or more marks it failed.
|
|
709
|
-
*/
|
|
710
|
-
setStatusCode(statusCode) {
|
|
711
|
-
this.statusCode = statusCode;
|
|
712
|
-
if (statusCode >= 400) this.status = "error";
|
|
713
|
-
}
|
|
714
|
-
/**
|
|
715
|
-
* Set error details.
|
|
716
|
-
*/
|
|
717
|
-
setError(error) {
|
|
718
|
-
this.error = error;
|
|
719
|
-
this.status = "error";
|
|
720
|
-
}
|
|
721
|
-
/**
|
|
722
|
-
* Finalize and produce the complete RequestLog.
|
|
723
|
-
* Fires the onRequestComplete callback if configured.
|
|
724
|
-
*/
|
|
725
|
-
async finalize() {
|
|
726
|
-
if (this.finalized) {
|
|
727
|
-
return this.finalizedLog;
|
|
728
|
-
}
|
|
729
|
-
this.finalized = true;
|
|
730
|
-
const log = this.toRequestLog();
|
|
731
|
-
this.finalizedLog = log;
|
|
732
|
-
if (this.onComplete) {
|
|
733
|
-
try {
|
|
734
|
-
await this.onComplete(log);
|
|
735
|
-
} catch {
|
|
736
|
-
}
|
|
737
|
-
}
|
|
738
|
-
return log;
|
|
739
|
-
}
|
|
740
|
-
/**
|
|
741
|
-
* Build the RequestLog object from accumulated state.
|
|
742
|
-
*/
|
|
743
|
-
toRequestLog() {
|
|
744
|
-
const endTime = /* @__PURE__ */ new Date();
|
|
745
|
-
return {
|
|
746
|
-
request_id: this.requestId,
|
|
747
|
-
trace_id: this.traceId,
|
|
748
|
-
session_id_hash: this.sessionIdHash,
|
|
749
|
-
scope_id: this.scopeId,
|
|
750
|
-
start_time: this.startTime.toISOString(),
|
|
751
|
-
end_time: endTime.toISOString(),
|
|
752
|
-
duration_ms: endTime.getTime() - this.startTime.getTime(),
|
|
753
|
-
http_method: this.httpMethod,
|
|
754
|
-
http_path: this.httpPath,
|
|
755
|
-
rpc_method: this.rpcMethod,
|
|
756
|
-
tool_name: this.toolName,
|
|
757
|
-
resource_uri: this.resourceUri,
|
|
758
|
-
prompt_name: this.promptName,
|
|
759
|
-
auth_type: this.authType,
|
|
760
|
-
authenticated: this.authenticated,
|
|
761
|
-
status: this.status,
|
|
762
|
-
status_code: this.statusCode,
|
|
763
|
-
error: this.error,
|
|
764
|
-
hooks_triggered: Array.from(this.hooksTriggered),
|
|
765
|
-
entries: [...this.entries]
|
|
766
|
-
};
|
|
767
|
-
}
|
|
768
|
-
/**
|
|
769
|
-
* Check if the collector has been finalized.
|
|
770
|
-
*/
|
|
771
|
-
isFinalized() {
|
|
772
|
-
return this.finalized;
|
|
773
|
-
}
|
|
774
|
-
/**
|
|
775
|
-
* Get the number of accumulated entries.
|
|
776
|
-
*/
|
|
777
|
-
getEntryCount() {
|
|
778
|
-
return this.entries.length;
|
|
779
|
-
}
|
|
780
|
-
};
|
|
781
|
-
|
|
782
|
-
// libs/observability/src/request-log/request-log.hooks.ts
|
|
783
|
-
import { isAnonymousSubject } from "@frontmcp/sdk";
|
|
784
|
-
|
|
785
|
-
// libs/observability/src/plugin/observability.hooks.ts
|
|
786
|
-
import {
|
|
787
|
-
context as otelContext3,
|
|
788
|
-
SpanKind as SpanKind12,
|
|
789
|
-
SpanStatusCode as SpanStatusCode2,
|
|
790
|
-
trace as trace3
|
|
791
|
-
} from "@opentelemetry/api";
|
|
792
|
-
import { FlowControl, InternalMcpError, toMcpError } from "@frontmcp/sdk";
|
|
793
|
-
import { sha256Hex } from "@frontmcp/utils";
|
|
794
|
-
|
|
795
|
-
// libs/observability/src/otel/otel.types.ts
|
|
796
|
-
var McpAttributes = {
|
|
797
|
-
/** MCP protocol method name (e.g., "tools/call", "resources/read") */
|
|
798
|
-
METHOD_NAME: "mcp.method.name",
|
|
799
|
-
/** MCP session identifier (hashed for privacy) */
|
|
800
|
-
SESSION_ID: "mcp.session.id",
|
|
801
|
-
/** MCP resource URI */
|
|
802
|
-
RESOURCE_URI: "mcp.resource.uri",
|
|
803
|
-
/** MCP component type: "tool" | "resource" | "prompt" | "resource_template" */
|
|
804
|
-
COMPONENT_TYPE: "mcp.component.type",
|
|
805
|
-
/** MCP component key (e.g., "tool:get_weather", "resource:config://db") */
|
|
806
|
-
COMPONENT_KEY: "mcp.component.key"
|
|
807
|
-
};
|
|
808
|
-
var FrontMcpAttributes = {
|
|
809
|
-
/** Scope identifier */
|
|
810
|
-
SCOPE_ID: "frontmcp.scope.id",
|
|
811
|
-
/** Server/scope name */
|
|
812
|
-
SERVER_NAME: "frontmcp.server.name",
|
|
813
|
-
/** Tool name being executed */
|
|
814
|
-
TOOL_NAME: "frontmcp.tool.name",
|
|
815
|
-
/** Tool owner class name */
|
|
816
|
-
TOOL_OWNER: "frontmcp.tool.owner",
|
|
817
|
-
/** Resource URI being read */
|
|
818
|
-
RESOURCE_URI: "frontmcp.resource.uri",
|
|
819
|
-
/** Resource name */
|
|
820
|
-
RESOURCE_NAME: "frontmcp.resource.name",
|
|
821
|
-
/** Prompt name being invoked */
|
|
822
|
-
PROMPT_NAME: "frontmcp.prompt.name",
|
|
823
|
-
/** Flow name (e.g., "tools:call-tool") */
|
|
824
|
-
FLOW_NAME: "frontmcp.flow.name",
|
|
825
|
-
/** Flow stage (e.g., "willExecute") */
|
|
826
|
-
FLOW_STAGE: "frontmcp.flow.stage",
|
|
827
|
-
/** Hook stage (e.g., "willValidateInput") */
|
|
828
|
-
HOOK_STAGE: "frontmcp.hook.stage",
|
|
829
|
-
/** Hook owner identifier */
|
|
830
|
-
HOOK_OWNER: "frontmcp.hook.owner",
|
|
831
|
-
/** Hashed session ID (for trace correlation, not the real session ID) */
|
|
832
|
-
SESSION_ID_HASH: "frontmcp.session.id_hash",
|
|
833
|
-
/** Authentication type */
|
|
834
|
-
AUTH_TYPE: "frontmcp.auth.type",
|
|
835
|
-
/** Request identifier */
|
|
836
|
-
REQUEST_ID: "frontmcp.request.id",
|
|
837
|
-
/** Provider type (e.g., "local", "adapter", "remote") */
|
|
838
|
-
PROVIDER_TYPE: "frontmcp.provider.type",
|
|
839
|
-
/** Delegation — original name before namespacing */
|
|
840
|
-
DELEGATE_ORIGINAL_NAME: "frontmcp.delegate.original_name",
|
|
841
|
-
// ── Transport ──
|
|
842
|
-
/** Transport type: "legacy-sse" | "streamable-http" | "stateless-http" */
|
|
843
|
-
TRANSPORT_TYPE: "frontmcp.transport.type",
|
|
844
|
-
/** Transport request type: "initialize" | "message" | "elicitResult" | "sseListener" | "extApps" */
|
|
845
|
-
TRANSPORT_REQUEST_TYPE: "frontmcp.transport.request_type",
|
|
846
|
-
/** Session protocol */
|
|
847
|
-
SESSION_PROTOCOL: "frontmcp.session.protocol",
|
|
848
|
-
/** Whether a new session was created */
|
|
849
|
-
SESSION_CREATED: "frontmcp.session.created",
|
|
850
|
-
// ── Auth ──
|
|
851
|
-
/** Auth mode: "public" | "transparent" | "orchestrated" */
|
|
852
|
-
AUTH_MODE: "frontmcp.auth.mode",
|
|
853
|
-
/** Auth result: "authorized" | "unauthorized" | "anonymous" */
|
|
854
|
-
AUTH_RESULT: "frontmcp.auth.result",
|
|
855
|
-
// ── OAuth ──
|
|
856
|
-
/** OAuth grant type: "authorization_code" | "refresh_token" | "anonymous" */
|
|
857
|
-
OAUTH_GRANT_TYPE: "frontmcp.oauth.grant_type",
|
|
858
|
-
// ── Elicitation ──
|
|
859
|
-
/** Elicitation request ID */
|
|
860
|
-
ELICITATION_ID: "frontmcp.elicitation.id",
|
|
861
|
-
// ── Agent ──
|
|
862
|
-
/** Agent name */
|
|
863
|
-
AGENT_NAME: "frontmcp.agent.name",
|
|
864
|
-
/** Agent execution loop iterations */
|
|
865
|
-
AGENT_ITERATIONS: "frontmcp.agent.iterations",
|
|
866
|
-
/** Agent execution duration in ms */
|
|
867
|
-
AGENT_EXECUTION_DURATION_MS: "frontmcp.agent.execution_duration_ms",
|
|
868
|
-
// ── Startup ──
|
|
869
|
-
/** Total tools registered at startup */
|
|
870
|
-
STARTUP_TOOLS_COUNT: "frontmcp.startup.tools_count",
|
|
871
|
-
/** Total resources registered at startup */
|
|
872
|
-
STARTUP_RESOURCES_COUNT: "frontmcp.startup.resources_count",
|
|
873
|
-
/** Total prompts registered at startup */
|
|
874
|
-
STARTUP_PROMPTS_COUNT: "frontmcp.startup.prompts_count",
|
|
875
|
-
/** Total plugins loaded at startup */
|
|
876
|
-
STARTUP_PLUGINS_COUNT: "frontmcp.startup.plugins_count",
|
|
877
|
-
/** Startup initialization duration in ms */
|
|
878
|
-
STARTUP_DURATION_MS: "frontmcp.startup.duration_ms"
|
|
879
|
-
};
|
|
880
|
-
var HttpAttributes = {
|
|
881
|
-
METHOD: "http.request.method",
|
|
882
|
-
STATUS_CODE: "http.response.status_code",
|
|
883
|
-
URL_PATH: "url.path",
|
|
884
|
-
URL_FULL: "url.full",
|
|
885
|
-
URL_SCHEME: "url.scheme",
|
|
886
|
-
SERVER_ADDRESS: "server.address",
|
|
887
|
-
SERVER_PORT: "server.port"
|
|
888
|
-
};
|
|
889
|
-
var RpcAttributes = {
|
|
890
|
-
/** RPC system — "mcp" for MCP protocol */
|
|
891
|
-
SYSTEM: "rpc.system",
|
|
892
|
-
/** RPC service name */
|
|
893
|
-
SERVICE: "rpc.service",
|
|
894
|
-
/** RPC method */
|
|
895
|
-
METHOD: "rpc.method",
|
|
896
|
-
/** JSON-RPC version */
|
|
897
|
-
JSONRPC_VERSION: "rpc.jsonrpc.version",
|
|
898
|
-
/** JSON-RPC request ID */
|
|
899
|
-
JSONRPC_REQUEST_ID: "rpc.jsonrpc.request_id"
|
|
900
|
-
};
|
|
901
|
-
var EnduserAttributes = {
|
|
902
|
-
/** Client/user ID from auth token */
|
|
903
|
-
ID: "enduser.id",
|
|
904
|
-
/** OAuth scopes (space-separated) */
|
|
905
|
-
SCOPE: "enduser.scope"
|
|
906
|
-
};
|
|
907
|
-
|
|
908
|
-
// libs/observability/src/otel/spans/auth.span.ts
|
|
909
|
-
import { SpanKind as SpanKind2 } from "@opentelemetry/api";
|
|
910
|
-
|
|
911
|
-
// libs/observability/src/otel/spans/span.utils.ts
|
|
912
|
-
import {
|
|
913
|
-
SpanKind,
|
|
914
|
-
SpanStatusCode,
|
|
915
|
-
context as otelContext,
|
|
916
|
-
trace
|
|
917
|
-
} from "@opentelemetry/api";
|
|
918
|
-
function startSpan(tracer, options) {
|
|
919
|
-
const parentCtx = options.parentContext ?? otelContext.active();
|
|
920
|
-
const span = tracer.startSpan(
|
|
921
|
-
options.name,
|
|
922
|
-
{
|
|
923
|
-
kind: options.kind ?? SpanKind.INTERNAL,
|
|
924
|
-
attributes: options.attributes
|
|
925
|
-
},
|
|
926
|
-
parentCtx
|
|
927
|
-
);
|
|
928
|
-
const spanContext = trace.setSpan(parentCtx, span);
|
|
929
|
-
return { span, context: spanContext };
|
|
930
|
-
}
|
|
931
|
-
function endSpanOk(span) {
|
|
932
|
-
span.setStatus({ code: SpanStatusCode.OK });
|
|
933
|
-
span.end();
|
|
934
|
-
}
|
|
935
|
-
function endSpanError(span, error) {
|
|
936
|
-
const message = typeof error === "string" ? error : error.message;
|
|
937
|
-
span.setStatus({ code: SpanStatusCode.ERROR, message });
|
|
938
|
-
if (error instanceof Error) {
|
|
939
|
-
span.recordException(error);
|
|
940
|
-
}
|
|
941
|
-
span.end();
|
|
942
|
-
}
|
|
943
|
-
async function withSpan(tracer, options, fn) {
|
|
944
|
-
const { span, context: spanContext } = startSpan(tracer, options);
|
|
945
|
-
return otelContext.with(spanContext, async () => {
|
|
946
|
-
try {
|
|
947
|
-
const result = await fn(span);
|
|
948
|
-
endSpanOk(span);
|
|
949
|
-
return result;
|
|
950
|
-
} catch (err) {
|
|
951
|
-
endSpanError(span, err instanceof Error ? err : String(err));
|
|
952
|
-
throw err;
|
|
953
|
-
}
|
|
954
|
-
});
|
|
955
|
-
}
|
|
956
|
-
|
|
957
|
-
// libs/observability/src/otel/spans/auth.span.ts
|
|
958
|
-
function startAuthSpan(tracer, options) {
|
|
959
|
-
return startSpan(tracer, {
|
|
960
|
-
name: `auth ${options.flowName}`,
|
|
961
|
-
kind: SpanKind2.INTERNAL,
|
|
962
|
-
attributes: {
|
|
963
|
-
[FrontMcpAttributes.FLOW_NAME]: options.flowName
|
|
964
|
-
},
|
|
965
|
-
parentContext: options.parentContext
|
|
966
|
-
});
|
|
967
|
-
}
|
|
968
|
-
function setAuthMode(span, mode) {
|
|
969
|
-
span.setAttribute(FrontMcpAttributes.AUTH_MODE, mode);
|
|
970
|
-
}
|
|
971
|
-
function setAuthResult(span, result) {
|
|
972
|
-
span.setAttribute(FrontMcpAttributes.AUTH_RESULT, result);
|
|
973
|
-
}
|
|
974
|
-
|
|
975
|
-
// libs/observability/src/otel/spans/fetch.span.ts
|
|
976
|
-
import { SpanKind as SpanKind3 } from "@opentelemetry/api";
|
|
977
|
-
function startFetchSpan(tracer, options) {
|
|
978
|
-
return startSpan(tracer, {
|
|
979
|
-
name: options.method.toUpperCase(),
|
|
980
|
-
kind: SpanKind3.CLIENT,
|
|
981
|
-
attributes: {
|
|
982
|
-
[HttpAttributes.METHOD]: options.method.toUpperCase(),
|
|
983
|
-
[HttpAttributes.URL_FULL]: options.url
|
|
984
|
-
},
|
|
985
|
-
parentContext: options.parentContext
|
|
986
|
-
});
|
|
987
|
-
}
|
|
988
|
-
function setFetchResponseStatus(span, statusCode) {
|
|
989
|
-
span.setAttribute(HttpAttributes.STATUS_CODE, statusCode);
|
|
990
|
-
}
|
|
991
|
-
|
|
992
|
-
// libs/observability/src/otel/spans/hook.span.ts
|
|
993
|
-
import { SpanKind as SpanKind4 } from "@opentelemetry/api";
|
|
994
|
-
function recordHookEvent(parentSpan, stage, owner) {
|
|
995
|
-
const attributes = {};
|
|
996
|
-
if (owner) {
|
|
997
|
-
attributes[FrontMcpAttributes.HOOK_OWNER] = owner;
|
|
998
|
-
}
|
|
999
|
-
parentSpan.addEvent(`hook.${stage}`, attributes);
|
|
1000
|
-
}
|
|
1001
|
-
function startHookSpan(tracer, options) {
|
|
1002
|
-
const attributes = {
|
|
1003
|
-
[FrontMcpAttributes.HOOK_STAGE]: options.stage
|
|
1004
|
-
};
|
|
1005
|
-
if (options.owner) {
|
|
1006
|
-
attributes[FrontMcpAttributes.HOOK_OWNER] = options.owner;
|
|
1007
|
-
}
|
|
1008
|
-
if (options.flowName) {
|
|
1009
|
-
attributes[FrontMcpAttributes.FLOW_NAME] = options.flowName;
|
|
1010
|
-
}
|
|
1011
|
-
return startSpan(tracer, {
|
|
1012
|
-
name: `hook ${options.stage}`,
|
|
1013
|
-
kind: SpanKind4.INTERNAL,
|
|
1014
|
-
attributes,
|
|
1015
|
-
parentContext: options.parentContext
|
|
1016
|
-
});
|
|
1017
|
-
}
|
|
1018
|
-
|
|
1019
|
-
// libs/observability/src/otel/spans/http-server.span.ts
|
|
1020
|
-
import { SpanKind as SpanKind5 } from "@opentelemetry/api";
|
|
1021
|
-
function startHttpServerSpan(tracer, options) {
|
|
1022
|
-
const attributes = {
|
|
1023
|
-
[HttpAttributes.METHOD]: options.method.toUpperCase(),
|
|
1024
|
-
[HttpAttributes.URL_PATH]: options.path
|
|
1025
|
-
};
|
|
1026
|
-
if (options.scheme) {
|
|
1027
|
-
attributes[HttpAttributes.URL_SCHEME] = options.scheme;
|
|
1028
|
-
}
|
|
1029
|
-
if (options.serverAddress) {
|
|
1030
|
-
attributes[HttpAttributes.SERVER_ADDRESS] = options.serverAddress;
|
|
1031
|
-
}
|
|
1032
|
-
if (options.serverPort) {
|
|
1033
|
-
attributes[HttpAttributes.SERVER_PORT] = options.serverPort;
|
|
1034
|
-
}
|
|
1035
|
-
if (options.scopeId) {
|
|
1036
|
-
attributes[FrontMcpAttributes.SCOPE_ID] = options.scopeId;
|
|
1037
|
-
}
|
|
1038
|
-
if (options.requestId) {
|
|
1039
|
-
attributes[FrontMcpAttributes.REQUEST_ID] = options.requestId;
|
|
1040
|
-
}
|
|
1041
|
-
return startSpan(tracer, {
|
|
1042
|
-
name: `${options.method.toUpperCase()} ${options.path}`,
|
|
1043
|
-
kind: SpanKind5.SERVER,
|
|
1044
|
-
attributes,
|
|
1045
|
-
parentContext: options.parentContext
|
|
1046
|
-
});
|
|
1047
|
-
}
|
|
1048
|
-
function setHttpResponseStatus(span, statusCode) {
|
|
1049
|
-
span.setAttribute(HttpAttributes.STATUS_CODE, statusCode);
|
|
1050
|
-
}
|
|
1051
|
-
|
|
1052
|
-
// libs/observability/src/otel/spans/prompt.span.ts
|
|
1053
|
-
import { SpanKind as SpanKind6 } from "@opentelemetry/api";
|
|
1054
|
-
function startPromptSpan(tracer, options) {
|
|
1055
|
-
return startSpan(tracer, {
|
|
1056
|
-
name: `prompt ${options.name}`,
|
|
1057
|
-
kind: SpanKind6.INTERNAL,
|
|
1058
|
-
attributes: {
|
|
1059
|
-
[FrontMcpAttributes.PROMPT_NAME]: options.name,
|
|
1060
|
-
[McpAttributes.COMPONENT_TYPE]: "prompt",
|
|
1061
|
-
[McpAttributes.COMPONENT_KEY]: `prompt:${options.name}`
|
|
1062
|
-
},
|
|
1063
|
-
parentContext: options.parentContext
|
|
1064
|
-
});
|
|
1065
|
-
}
|
|
1066
|
-
|
|
1067
|
-
// libs/observability/src/otel/spans/resource.span.ts
|
|
1068
|
-
import { SpanKind as SpanKind7 } from "@opentelemetry/api";
|
|
1069
|
-
function startResourceSpan(tracer, options) {
|
|
1070
|
-
const attributes = {
|
|
1071
|
-
[FrontMcpAttributes.RESOURCE_URI]: options.uri,
|
|
1072
|
-
[McpAttributes.RESOURCE_URI]: options.uri,
|
|
1073
|
-
[McpAttributes.COMPONENT_TYPE]: "resource",
|
|
1074
|
-
[McpAttributes.COMPONENT_KEY]: `resource:${options.uri}`
|
|
1075
|
-
};
|
|
1076
|
-
if (options.name) {
|
|
1077
|
-
attributes[FrontMcpAttributes.RESOURCE_NAME] = options.name;
|
|
1078
|
-
}
|
|
1079
|
-
return startSpan(tracer, {
|
|
1080
|
-
name: `resource ${options.uri}`,
|
|
1081
|
-
kind: SpanKind7.INTERNAL,
|
|
1082
|
-
attributes,
|
|
1083
|
-
parentContext: options.parentContext
|
|
1084
|
-
});
|
|
1085
|
-
}
|
|
1086
|
-
|
|
1087
|
-
// libs/observability/src/otel/spans/rpc.span.ts
|
|
1088
|
-
import { SpanKind as SpanKind8 } from "@opentelemetry/api";
|
|
1089
|
-
function startRpcSpan(tracer, options) {
|
|
1090
|
-
const attributes = {
|
|
1091
|
-
[RpcAttributes.SYSTEM]: "mcp",
|
|
1092
|
-
[RpcAttributes.METHOD]: options.method,
|
|
1093
|
-
[RpcAttributes.JSONRPC_VERSION]: "2.0",
|
|
1094
|
-
[McpAttributes.METHOD_NAME]: options.method
|
|
1095
|
-
};
|
|
1096
|
-
if (options.requestId !== void 0) {
|
|
1097
|
-
attributes[RpcAttributes.JSONRPC_REQUEST_ID] = String(options.requestId);
|
|
1098
|
-
}
|
|
1099
|
-
if (options.scopeId) {
|
|
1100
|
-
attributes[FrontMcpAttributes.SCOPE_ID] = options.scopeId;
|
|
1101
|
-
}
|
|
1102
|
-
if (options.serviceName) {
|
|
1103
|
-
attributes[RpcAttributes.SERVICE] = options.serviceName;
|
|
1104
|
-
attributes[FrontMcpAttributes.SERVER_NAME] = options.serviceName;
|
|
1105
|
-
}
|
|
1106
|
-
if (options.sessionIdHash) {
|
|
1107
|
-
attributes[McpAttributes.SESSION_ID] = options.sessionIdHash;
|
|
1108
|
-
attributes[FrontMcpAttributes.SESSION_ID_HASH] = options.sessionIdHash;
|
|
1109
|
-
}
|
|
1110
|
-
return startSpan(tracer, {
|
|
1111
|
-
name: options.method,
|
|
1112
|
-
kind: SpanKind8.SERVER,
|
|
1113
|
-
attributes,
|
|
1114
|
-
parentContext: options.parentContext
|
|
1115
|
-
});
|
|
1116
|
-
}
|
|
1117
|
-
|
|
1118
|
-
// libs/observability/src/otel/spans/startup.span.ts
|
|
1119
|
-
import { SpanKind as SpanKind9 } from "@opentelemetry/api";
|
|
1120
|
-
function emitStartupReport(tracer, data) {
|
|
1121
|
-
const attributes = {
|
|
1122
|
-
[FrontMcpAttributes.STARTUP_TOOLS_COUNT]: data.toolsCount,
|
|
1123
|
-
[FrontMcpAttributes.STARTUP_RESOURCES_COUNT]: data.resourcesCount,
|
|
1124
|
-
[FrontMcpAttributes.STARTUP_PROMPTS_COUNT]: data.promptsCount,
|
|
1125
|
-
[FrontMcpAttributes.STARTUP_PLUGINS_COUNT]: data.pluginsCount,
|
|
1126
|
-
[FrontMcpAttributes.STARTUP_DURATION_MS]: data.durationMs
|
|
1127
|
-
};
|
|
1128
|
-
if (data.scopeId) {
|
|
1129
|
-
attributes[FrontMcpAttributes.SCOPE_ID] = data.scopeId;
|
|
1130
|
-
}
|
|
1131
|
-
const { span } = startSpan(tracer, {
|
|
1132
|
-
name: "frontmcp.startup",
|
|
1133
|
-
kind: SpanKind9.INTERNAL,
|
|
1134
|
-
attributes
|
|
1135
|
-
});
|
|
1136
|
-
endSpanOk(span);
|
|
1137
|
-
}
|
|
1138
|
-
|
|
1139
|
-
// libs/observability/src/otel/spans/tool.span.ts
|
|
1140
|
-
import { SpanKind as SpanKind10 } from "@opentelemetry/api";
|
|
1141
|
-
function startToolSpan(tracer, options) {
|
|
1142
|
-
const attributes = {
|
|
1143
|
-
[FrontMcpAttributes.TOOL_NAME]: options.name,
|
|
1144
|
-
[McpAttributes.COMPONENT_TYPE]: "tool",
|
|
1145
|
-
[McpAttributes.COMPONENT_KEY]: `tool:${options.name}`
|
|
1146
|
-
};
|
|
1147
|
-
if (options.owner) {
|
|
1148
|
-
attributes[FrontMcpAttributes.TOOL_OWNER] = options.owner;
|
|
1149
|
-
}
|
|
1150
|
-
if (options.enduserId) {
|
|
1151
|
-
attributes[EnduserAttributes.ID] = options.enduserId;
|
|
1152
|
-
}
|
|
1153
|
-
if (options.enduserScope) {
|
|
1154
|
-
attributes[EnduserAttributes.SCOPE] = options.enduserScope;
|
|
1155
|
-
}
|
|
1156
|
-
return startSpan(tracer, {
|
|
1157
|
-
name: `tool ${options.name}`,
|
|
1158
|
-
kind: SpanKind10.INTERNAL,
|
|
1159
|
-
attributes,
|
|
1160
|
-
parentContext: options.parentContext
|
|
1161
|
-
});
|
|
1162
|
-
}
|
|
1163
|
-
|
|
1164
|
-
// libs/observability/src/otel/spans/transport.span.ts
|
|
1165
|
-
import { SpanKind as SpanKind11 } from "@opentelemetry/api";
|
|
1166
|
-
function startTransportSpan(tracer, options) {
|
|
1167
|
-
const attributes = {
|
|
1168
|
-
[FrontMcpAttributes.TRANSPORT_TYPE]: options.type
|
|
1169
|
-
};
|
|
1170
|
-
if (options.sessionIdHash) {
|
|
1171
|
-
attributes[FrontMcpAttributes.SESSION_ID_HASH] = options.sessionIdHash;
|
|
1172
|
-
}
|
|
1173
|
-
if (options.sessionCreated !== void 0) {
|
|
1174
|
-
attributes[FrontMcpAttributes.SESSION_CREATED] = options.sessionCreated;
|
|
1175
|
-
}
|
|
1176
|
-
return startSpan(tracer, {
|
|
1177
|
-
name: `transport ${options.type}`,
|
|
1178
|
-
kind: SpanKind11.INTERNAL,
|
|
1179
|
-
attributes,
|
|
1180
|
-
parentContext: options.parentContext
|
|
1181
|
-
});
|
|
1182
|
-
}
|
|
1183
|
-
function setTransportRequestType(span, requestType) {
|
|
1184
|
-
span.setAttribute(FrontMcpAttributes.TRANSPORT_REQUEST_TYPE, requestType);
|
|
1185
|
-
}
|
|
1186
|
-
|
|
1187
|
-
// libs/observability/src/otel/trace-context-bridge.ts
|
|
1188
|
-
import {
|
|
1189
|
-
TraceFlags,
|
|
1190
|
-
trace as trace2,
|
|
1191
|
-
context as otelContext2
|
|
1192
|
-
} from "@opentelemetry/api";
|
|
1193
|
-
function frontmcpToOTelSpanContext(tc) {
|
|
1194
|
-
return {
|
|
1195
|
-
traceId: tc.traceId,
|
|
1196
|
-
spanId: tc.parentId,
|
|
1197
|
-
traceFlags: tc.traceFlags & TraceFlags.SAMPLED ? TraceFlags.SAMPLED : TraceFlags.NONE,
|
|
1198
|
-
isRemote: true
|
|
1199
|
-
};
|
|
1200
|
-
}
|
|
1201
|
-
function otelToFrontmcpContext(sc) {
|
|
1202
|
-
const flags = sc.traceFlags.toString(16).padStart(2, "0");
|
|
1203
|
-
return {
|
|
1204
|
-
traceId: sc.traceId,
|
|
1205
|
-
parentId: sc.spanId,
|
|
1206
|
-
traceFlags: sc.traceFlags,
|
|
1207
|
-
raw: `00-${sc.traceId}-${sc.spanId}-${flags}`
|
|
1208
|
-
};
|
|
1209
|
-
}
|
|
1210
|
-
function createOTelContextFromTrace(tc) {
|
|
1211
|
-
const spanContext = frontmcpToOTelSpanContext(tc);
|
|
1212
|
-
const span = trace2.wrapSpanContext(spanContext);
|
|
1213
|
-
return trace2.setSpan(otelContext2.active(), span);
|
|
1214
|
-
}
|
|
1215
|
-
|
|
1216
|
-
// libs/observability/src/plugin/observability.hooks.ts
|
|
1217
|
-
var SPAN_KEY = /* @__PURE__ */ Symbol.for("frontmcp:otel:span");
|
|
1218
|
-
var SPAN_CTX_KEY = /* @__PURE__ */ Symbol.for("frontmcp:otel:span-ctx");
|
|
1219
|
-
var EXEC_SPAN_KEY = /* @__PURE__ */ Symbol.for("frontmcp:otel:exec-span");
|
|
1220
|
-
var ACTIVE_SPAN_KEY = /* @__PURE__ */ Symbol.for("frontmcp:otel:active-span");
|
|
1221
|
-
var ACTIVE_OTEL_CTX_KEY = /* @__PURE__ */ Symbol.for("frontmcp:otel:active-otel-ctx");
|
|
1222
|
-
var STAGE_TS_KEY = /* @__PURE__ */ Symbol.for("frontmcp:otel:stage-ts");
|
|
1223
|
-
var STAGE_EVENTS_KEY = /* @__PURE__ */ Symbol.for("frontmcp:otel:stage-events");
|
|
1224
|
-
var HTTP_SPAN_CTX_KEY = /* @__PURE__ */ Symbol.for("frontmcp:otel:http-span-ctx");
|
|
1225
|
-
function sessionTracingId(sessionId) {
|
|
1226
|
-
return sha256Hex(sessionId).slice(0, 16);
|
|
1227
|
-
}
|
|
1228
|
-
function getTracer() {
|
|
1229
|
-
return trace3.getTracer("@frontmcp/observability");
|
|
1230
|
-
}
|
|
1231
|
-
function extractContext(flowCtx) {
|
|
1232
|
-
try {
|
|
1233
|
-
const ctx = flowCtx.get?.(/* @__PURE__ */ Symbol.for("frontmcp:CONTEXT"));
|
|
1234
|
-
if (ctx) return ctx;
|
|
1235
|
-
} catch {
|
|
1236
|
-
}
|
|
1237
|
-
return flowCtx.state?.ctx ?? flowCtx.state?.frontmcpContext;
|
|
1238
|
-
}
|
|
1239
|
-
function storeActiveSpan(flowCtx, span, otelCtx) {
|
|
1240
|
-
try {
|
|
1241
|
-
const ctx = flowCtx.get?.(/* @__PURE__ */ Symbol.for("frontmcp:CONTEXT"));
|
|
1242
|
-
if (ctx && typeof ctx.set === "function") {
|
|
1243
|
-
ctx.set(ACTIVE_SPAN_KEY, span);
|
|
1244
|
-
ctx.set(ACTIVE_OTEL_CTX_KEY, otelCtx);
|
|
1245
|
-
}
|
|
1246
|
-
} catch {
|
|
1247
|
-
}
|
|
1248
|
-
}
|
|
1249
|
-
function clearActiveSpan(flowCtx) {
|
|
1250
|
-
try {
|
|
1251
|
-
const ctx = flowCtx.get?.(/* @__PURE__ */ Symbol.for("frontmcp:CONTEXT"));
|
|
1252
|
-
if (ctx && typeof ctx.delete === "function") {
|
|
1253
|
-
ctx.delete(ACTIVE_SPAN_KEY);
|
|
1254
|
-
ctx.delete(ACTIVE_OTEL_CTX_KEY);
|
|
1255
|
-
}
|
|
1256
|
-
} catch {
|
|
1257
|
-
}
|
|
1258
|
-
}
|
|
1259
|
-
function beginFlowSpan(flowCtx, options, span, spanCtx) {
|
|
1260
|
-
flowCtx.state[SPAN_KEY] = span;
|
|
1261
|
-
flowCtx.state[SPAN_CTX_KEY] = spanCtx;
|
|
1262
|
-
flowCtx.state[STAGE_TS_KEY] = Date.now();
|
|
1263
|
-
flowCtx.state[STAGE_EVENTS_KEY] = options.flowStageEvents !== false;
|
|
1264
|
-
}
|
|
1265
|
-
function parentContextOf(ctx) {
|
|
1266
|
-
return ctx.get?.(HTTP_SPAN_CTX_KEY) ?? createOTelContextFromTrace(ctx.traceContext);
|
|
1267
|
-
}
|
|
1268
|
-
function flowFailureOf(flowError) {
|
|
1269
|
-
const failed = flowError?.originalError;
|
|
1270
|
-
const error = flowError instanceof FlowControl ? failed instanceof Error ? failed : new InternalMcpError(`Flow ended with: ${flowError.type}`) : flowError instanceof Error ? flowError : new Error(String(flowError));
|
|
1271
|
-
const reported = toMcpError(error);
|
|
1272
|
-
return {
|
|
1273
|
-
error,
|
|
1274
|
-
type: reported.name,
|
|
1275
|
-
message: reported.getPublicMessage(),
|
|
1276
|
-
code: reported.code,
|
|
1277
|
-
errorId: reported.errorId
|
|
1278
|
-
};
|
|
1279
|
-
}
|
|
1280
|
-
function endFailedSpan(span, flowError) {
|
|
1281
|
-
const failure = flowFailureOf(flowError);
|
|
1282
|
-
span.setStatus({ code: SpanStatusCode2.ERROR, message: failure.message });
|
|
1283
|
-
span.recordException({
|
|
1284
|
-
name: failure.type,
|
|
1285
|
-
message: failure.message,
|
|
1286
|
-
code: failure.code,
|
|
1287
|
-
stack: failure.error.stack
|
|
1288
|
-
});
|
|
1289
|
-
span.end();
|
|
1290
|
-
}
|
|
1291
|
-
function traceparentOf(span) {
|
|
1292
|
-
const { traceId, spanId, traceFlags } = span.spanContext();
|
|
1293
|
-
return `00-${traceId}-${spanId}-${traceFlags.toString(16).padStart(2, "0")}`;
|
|
1294
|
-
}
|
|
1295
|
-
function recordStageEvent(span, stageName, state) {
|
|
1296
|
-
if (state[STAGE_EVENTS_KEY] === false) return;
|
|
1297
|
-
const now = Date.now();
|
|
1298
|
-
const prev = state[STAGE_TS_KEY];
|
|
1299
|
-
const attributes = {};
|
|
1300
|
-
if (prev) {
|
|
1301
|
-
attributes["duration_ms"] = now - prev;
|
|
1302
|
-
}
|
|
1303
|
-
state[STAGE_TS_KEY] = now;
|
|
1304
|
-
span.addEvent(`stage.${stageName}`, attributes);
|
|
1305
|
-
}
|
|
1306
|
-
function onHttpWillTrace(options, flowCtx) {
|
|
1307
|
-
if (options.httpSpans === false) return;
|
|
1308
|
-
const ctx = extractContext(flowCtx);
|
|
1309
|
-
if (!ctx) return;
|
|
1310
|
-
const tracer = getTracer();
|
|
1311
|
-
const parentOTelCtx = createOTelContextFromTrace(ctx.traceContext);
|
|
1312
|
-
const sessionHash = sessionTracingId(ctx.sessionId);
|
|
1313
|
-
const { span, context: spanCtx } = startHttpServerSpan(tracer, {
|
|
1314
|
-
method: ctx.metadata?.customHeaders?.["x-http-method"] ?? "POST",
|
|
1315
|
-
path: ctx.metadata?.customHeaders?.["x-url-path"] ?? "/",
|
|
1316
|
-
scopeId: ctx.scopeId,
|
|
1317
|
-
requestId: ctx.requestId,
|
|
1318
|
-
parentContext: parentOTelCtx
|
|
1319
|
-
});
|
|
1320
|
-
span.setAttribute(McpAttributes.SESSION_ID, sessionHash);
|
|
1321
|
-
span.setAttribute(FrontMcpAttributes.SESSION_ID_HASH, sessionHash);
|
|
1322
|
-
ctx.set?.(HTTP_SPAN_CTX_KEY, spanCtx);
|
|
1323
|
-
beginFlowSpan(flowCtx, options, span, spanCtx);
|
|
1324
|
-
recordStageEvent(span, "traceRequest", flowCtx.state);
|
|
1325
|
-
}
|
|
1326
|
-
function onHttpWillAcquireQuota(flowCtx) {
|
|
1327
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1328
|
-
if (span) recordStageEvent(span, "acquireQuota", flowCtx.state);
|
|
1329
|
-
}
|
|
1330
|
-
function onHttpDidAcquireQuota(flowCtx) {
|
|
1331
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1332
|
-
if (span) recordStageEvent(span, "acquireQuota.done", flowCtx.state);
|
|
1333
|
-
}
|
|
1334
|
-
function onHttpWillCheckAuth(flowCtx) {
|
|
1335
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1336
|
-
if (span) recordStageEvent(span, "checkAuthorization", flowCtx.state);
|
|
1337
|
-
}
|
|
1338
|
-
function onHttpDidCheckAuth(flowCtx) {
|
|
1339
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1340
|
-
if (span) recordStageEvent(span, "checkAuthorization.done", flowCtx.state);
|
|
1341
|
-
}
|
|
1342
|
-
function onHttpWillRoute(flowCtx) {
|
|
1343
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1344
|
-
if (span) recordStageEvent(span, "router", flowCtx.state);
|
|
1345
|
-
}
|
|
1346
|
-
function onHttpDidRoute(flowCtx) {
|
|
1347
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1348
|
-
if (span) recordStageEvent(span, "router.done", flowCtx.state);
|
|
1349
|
-
}
|
|
1350
|
-
function onHttpDidFinalize(flowCtx) {
|
|
1351
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1352
|
-
if (!span) return;
|
|
1353
|
-
recordStageEvent(span, "finalize", flowCtx.state);
|
|
1354
|
-
const statusCode = flowCtx.state?.statusCode ?? 200;
|
|
1355
|
-
setHttpResponseStatus(span, statusCode);
|
|
1356
|
-
if (statusCode >= 400) {
|
|
1357
|
-
endSpanError(span, `HTTP ${statusCode}`);
|
|
1358
|
-
} else {
|
|
1359
|
-
endSpanOk(span);
|
|
1360
|
-
}
|
|
1361
|
-
}
|
|
1362
|
-
function onToolWillParse(options, flowCtx) {
|
|
1363
|
-
if (options.executionSpans === false) return;
|
|
1364
|
-
const ctx = extractContext(flowCtx);
|
|
1365
|
-
if (!ctx) return;
|
|
1366
|
-
const tracer = getTracer();
|
|
1367
|
-
const parentOTelCtx = parentContextOf(ctx);
|
|
1368
|
-
const sessionHash = sessionTracingId(ctx.sessionId);
|
|
1369
|
-
const { span, context: spanCtx } = startRpcSpan(tracer, {
|
|
1370
|
-
method: "tools/call",
|
|
1371
|
-
scopeId: ctx.scopeId,
|
|
1372
|
-
sessionIdHash: sessionHash,
|
|
1373
|
-
parentContext: parentOTelCtx
|
|
1374
|
-
});
|
|
1375
|
-
beginFlowSpan(flowCtx, options, span, spanCtx);
|
|
1376
|
-
recordStageEvent(span, "parseInput", flowCtx.state);
|
|
1377
|
-
}
|
|
1378
|
-
function onToolWillFindTool(flowCtx) {
|
|
1379
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1380
|
-
if (span) recordStageEvent(span, "findTool", flowCtx.state);
|
|
1381
|
-
}
|
|
1382
|
-
function onToolWillCheckAuth(flowCtx) {
|
|
1383
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1384
|
-
if (span) recordStageEvent(span, "checkToolAuthorization", flowCtx.state);
|
|
1385
|
-
}
|
|
1386
|
-
function onEntryWillCheckAuthorities(flowCtx) {
|
|
1387
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1388
|
-
if (span) recordStageEvent(span, "checkEntryAuthorities", flowCtx.state);
|
|
1389
|
-
}
|
|
1390
|
-
function onEntryDidCheckAuthorities(flowCtx) {
|
|
1391
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1392
|
-
if (!span) return;
|
|
1393
|
-
recordStageEvent(span, "checkEntryAuthorities.done", flowCtx.state);
|
|
1394
|
-
span.setAttribute("auth.authorities.result", "granted");
|
|
1395
|
-
}
|
|
1396
|
-
function onToolWillCreateContext(flowCtx) {
|
|
1397
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1398
|
-
if (span) recordStageEvent(span, "createToolCallContext", flowCtx.state);
|
|
1399
|
-
}
|
|
1400
|
-
function onToolWillValidateInput(flowCtx) {
|
|
1401
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1402
|
-
if (span) recordStageEvent(span, "validateInput", flowCtx.state);
|
|
1403
|
-
}
|
|
1404
|
-
function onToolWillExecute(options, flowCtx) {
|
|
1405
|
-
if (options.executionSpans === false) return;
|
|
1406
|
-
const ctx = extractContext(flowCtx);
|
|
1407
|
-
const rpcCtx = flowCtx.state?.[SPAN_CTX_KEY];
|
|
1408
|
-
const tracer = getTracer();
|
|
1409
|
-
const toolName = flowCtx.state?.input?.name ?? "unknown";
|
|
1410
|
-
const toolOwner = flowCtx.state?._toolOwnerId;
|
|
1411
|
-
const enduser = ctx?.authInfo;
|
|
1412
|
-
const { span: toolSpan, context: toolOTelCtx } = startToolSpan(tracer, {
|
|
1413
|
-
name: toolName,
|
|
1414
|
-
owner: toolOwner,
|
|
1415
|
-
enduserId: enduser?.clientId ?? enduser?.extra?.sub,
|
|
1416
|
-
enduserScope: Array.isArray(enduser?.scopes) ? enduser.scopes.join(" ") : void 0,
|
|
1417
|
-
parentContext: rpcCtx
|
|
1418
|
-
});
|
|
1419
|
-
flowCtx.state[EXEC_SPAN_KEY] = toolSpan;
|
|
1420
|
-
flowCtx.state[STAGE_TS_KEY] = Date.now();
|
|
1421
|
-
recordStageEvent(toolSpan, "execute.start", flowCtx.state);
|
|
1422
|
-
storeActiveSpan(flowCtx, toolSpan, toolOTelCtx);
|
|
1423
|
-
}
|
|
1424
|
-
function onToolDidExecute(options, flowCtx) {
|
|
1425
|
-
const toolSpan = flowCtx.state?.[EXEC_SPAN_KEY];
|
|
1426
|
-
if (!toolSpan) return;
|
|
1427
|
-
recordStageEvent(toolSpan, "execute.done", flowCtx.state);
|
|
1428
|
-
endSpanOk(toolSpan);
|
|
1429
|
-
flowCtx.state[EXEC_SPAN_KEY] = void 0;
|
|
1430
|
-
clearActiveSpan(flowCtx);
|
|
1431
|
-
}
|
|
1432
|
-
function onToolWillValidateOutput(flowCtx) {
|
|
1433
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1434
|
-
if (span) recordStageEvent(span, "validateOutput", flowCtx.state);
|
|
1435
|
-
}
|
|
1436
|
-
function onToolWillApplyUI(flowCtx) {
|
|
1437
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1438
|
-
if (span) recordStageEvent(span, "applyUI", flowCtx.state);
|
|
1439
|
-
}
|
|
1440
|
-
function onToolDidFinalize(flowCtx) {
|
|
1441
|
-
const rpcSpan = flowCtx.state?.[SPAN_KEY];
|
|
1442
|
-
const toolSpan = flowCtx.state?.[EXEC_SPAN_KEY];
|
|
1443
|
-
const error = flowCtx.state?.flowError;
|
|
1444
|
-
if (error) {
|
|
1445
|
-
if (toolSpan) endFailedSpan(toolSpan, error);
|
|
1446
|
-
if (rpcSpan) endFailedSpan(rpcSpan, error);
|
|
1447
|
-
} else if (rpcSpan) {
|
|
1448
|
-
recordStageEvent(rpcSpan, "finalize", flowCtx.state);
|
|
1449
|
-
endSpanOk(rpcSpan);
|
|
1450
|
-
}
|
|
1451
|
-
}
|
|
1452
|
-
function onResourceWillParse(options, flowCtx) {
|
|
1453
|
-
if (options.executionSpans === false) return;
|
|
1454
|
-
const ctx = extractContext(flowCtx);
|
|
1455
|
-
if (!ctx) return;
|
|
1456
|
-
const tracer = getTracer();
|
|
1457
|
-
const parentOTelCtx = parentContextOf(ctx);
|
|
1458
|
-
const sessionHash = sessionTracingId(ctx.sessionId);
|
|
1459
|
-
const { span, context: spanCtx } = startRpcSpan(tracer, {
|
|
1460
|
-
method: "resources/read",
|
|
1461
|
-
scopeId: ctx.scopeId,
|
|
1462
|
-
sessionIdHash: sessionHash,
|
|
1463
|
-
parentContext: parentOTelCtx
|
|
1464
|
-
});
|
|
1465
|
-
beginFlowSpan(flowCtx, options, span, spanCtx);
|
|
1466
|
-
recordStageEvent(span, "parseInput", flowCtx.state);
|
|
1467
|
-
}
|
|
1468
|
-
function onResourceWillFind(flowCtx) {
|
|
1469
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1470
|
-
if (span) recordStageEvent(span, "findResource", flowCtx.state);
|
|
1471
|
-
}
|
|
1472
|
-
function onResourceWillExecute(options, flowCtx) {
|
|
1473
|
-
if (options.executionSpans === false) return;
|
|
1474
|
-
const rpcCtx = flowCtx.state?.[SPAN_CTX_KEY];
|
|
1475
|
-
const tracer = getTracer();
|
|
1476
|
-
const uri = flowCtx.state?.input?.uri ?? "unknown";
|
|
1477
|
-
const { span: resSpan, context: resOTelCtx } = startResourceSpan(tracer, { uri, parentContext: rpcCtx });
|
|
1478
|
-
flowCtx.state[EXEC_SPAN_KEY] = resSpan;
|
|
1479
|
-
flowCtx.state[STAGE_TS_KEY] = Date.now();
|
|
1480
|
-
recordStageEvent(resSpan, "execute.start", flowCtx.state);
|
|
1481
|
-
storeActiveSpan(flowCtx, resSpan, resOTelCtx);
|
|
1482
|
-
}
|
|
1483
|
-
function onResourceDidExecute(flowCtx) {
|
|
1484
|
-
const resSpan = flowCtx.state?.[EXEC_SPAN_KEY];
|
|
1485
|
-
if (!resSpan) return;
|
|
1486
|
-
recordStageEvent(resSpan, "execute.done", flowCtx.state);
|
|
1487
|
-
endSpanOk(resSpan);
|
|
1488
|
-
flowCtx.state[EXEC_SPAN_KEY] = void 0;
|
|
1489
|
-
clearActiveSpan(flowCtx);
|
|
1490
|
-
}
|
|
1491
|
-
function onResourceDidFinalize(flowCtx) {
|
|
1492
|
-
const rpcSpan = flowCtx.state?.[SPAN_KEY];
|
|
1493
|
-
const resSpan = flowCtx.state?.[EXEC_SPAN_KEY];
|
|
1494
|
-
const error = flowCtx.state?.flowError;
|
|
1495
|
-
if (error) {
|
|
1496
|
-
if (resSpan) endFailedSpan(resSpan, error);
|
|
1497
|
-
if (rpcSpan) endFailedSpan(rpcSpan, error);
|
|
1498
|
-
} else if (rpcSpan) {
|
|
1499
|
-
recordStageEvent(rpcSpan, "finalize", flowCtx.state);
|
|
1500
|
-
endSpanOk(rpcSpan);
|
|
1501
|
-
}
|
|
1502
|
-
}
|
|
1503
|
-
function onPromptWillParse(options, flowCtx) {
|
|
1504
|
-
if (options.executionSpans === false) return;
|
|
1505
|
-
const ctx = extractContext(flowCtx);
|
|
1506
|
-
if (!ctx) return;
|
|
1507
|
-
const tracer = getTracer();
|
|
1508
|
-
const parentOTelCtx = parentContextOf(ctx);
|
|
1509
|
-
const sessionHash = sessionTracingId(ctx.sessionId);
|
|
1510
|
-
const { span, context: spanCtx } = startRpcSpan(tracer, {
|
|
1511
|
-
method: "prompts/get",
|
|
1512
|
-
scopeId: ctx.scopeId,
|
|
1513
|
-
sessionIdHash: sessionHash,
|
|
1514
|
-
parentContext: parentOTelCtx
|
|
1515
|
-
});
|
|
1516
|
-
beginFlowSpan(flowCtx, options, span, spanCtx);
|
|
1517
|
-
recordStageEvent(span, "parseInput", flowCtx.state);
|
|
1518
|
-
}
|
|
1519
|
-
function onPromptWillFind(flowCtx) {
|
|
1520
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1521
|
-
if (span) recordStageEvent(span, "findPrompt", flowCtx.state);
|
|
1522
|
-
}
|
|
1523
|
-
function onPromptWillExecute(options, flowCtx) {
|
|
1524
|
-
if (options.executionSpans === false) return;
|
|
1525
|
-
const rpcCtx = flowCtx.state?.[SPAN_CTX_KEY];
|
|
1526
|
-
const tracer = getTracer();
|
|
1527
|
-
const promptName = flowCtx.state?.input?.name ?? "unknown";
|
|
1528
|
-
const { span: promptSpan, context: promptOTelCtx } = startPromptSpan(tracer, {
|
|
1529
|
-
name: promptName,
|
|
1530
|
-
parentContext: rpcCtx
|
|
1531
|
-
});
|
|
1532
|
-
flowCtx.state[EXEC_SPAN_KEY] = promptSpan;
|
|
1533
|
-
flowCtx.state[STAGE_TS_KEY] = Date.now();
|
|
1534
|
-
recordStageEvent(promptSpan, "execute.start", flowCtx.state);
|
|
1535
|
-
storeActiveSpan(flowCtx, promptSpan, promptOTelCtx);
|
|
1536
|
-
}
|
|
1537
|
-
function onPromptDidExecute(flowCtx) {
|
|
1538
|
-
const promptSpan = flowCtx.state?.[EXEC_SPAN_KEY];
|
|
1539
|
-
if (!promptSpan) return;
|
|
1540
|
-
recordStageEvent(promptSpan, "execute.done", flowCtx.state);
|
|
1541
|
-
endSpanOk(promptSpan);
|
|
1542
|
-
flowCtx.state[EXEC_SPAN_KEY] = void 0;
|
|
1543
|
-
clearActiveSpan(flowCtx);
|
|
1544
|
-
}
|
|
1545
|
-
function onPromptDidFinalize(flowCtx) {
|
|
1546
|
-
const rpcSpan = flowCtx.state?.[SPAN_KEY];
|
|
1547
|
-
const promptSpan = flowCtx.state?.[EXEC_SPAN_KEY];
|
|
1548
|
-
const error = flowCtx.state?.flowError;
|
|
1549
|
-
if (error) {
|
|
1550
|
-
if (promptSpan) endFailedSpan(promptSpan, error);
|
|
1551
|
-
if (rpcSpan) endFailedSpan(rpcSpan, error);
|
|
1552
|
-
} else if (rpcSpan) {
|
|
1553
|
-
recordStageEvent(rpcSpan, "finalize", flowCtx.state);
|
|
1554
|
-
endSpanOk(rpcSpan);
|
|
1555
|
-
}
|
|
1556
|
-
}
|
|
1557
|
-
function onAgentWillParse(options, flowCtx) {
|
|
1558
|
-
if (options.executionSpans === false) return;
|
|
1559
|
-
const ctx = extractContext(flowCtx);
|
|
1560
|
-
if (!ctx) return;
|
|
1561
|
-
const tracer = getTracer();
|
|
1562
|
-
const parentOTelCtx = parentContextOf(ctx);
|
|
1563
|
-
const sessionHash = sessionTracingId(ctx.sessionId);
|
|
1564
|
-
const { span, context: spanCtx } = startRpcSpan(tracer, {
|
|
1565
|
-
method: "agents/call",
|
|
1566
|
-
scopeId: ctx.scopeId,
|
|
1567
|
-
sessionIdHash: sessionHash,
|
|
1568
|
-
parentContext: parentOTelCtx
|
|
1569
|
-
});
|
|
1570
|
-
beginFlowSpan(flowCtx, options, span, spanCtx);
|
|
1571
|
-
recordStageEvent(span, "parseInput", flowCtx.state);
|
|
1572
|
-
}
|
|
1573
|
-
function onAgentWillFind(flowCtx) {
|
|
1574
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1575
|
-
if (span) recordStageEvent(span, "findAgent", flowCtx.state);
|
|
1576
|
-
}
|
|
1577
|
-
function onAgentWillExecute(options, flowCtx) {
|
|
1578
|
-
if (options.executionSpans === false) return;
|
|
1579
|
-
const rpcCtx = flowCtx.state?.[SPAN_CTX_KEY];
|
|
1580
|
-
const tracer = getTracer();
|
|
1581
|
-
const agentName = flowCtx.state?.input?.name ?? "unknown";
|
|
1582
|
-
const { span: agentSpan } = startSpan(tracer, {
|
|
1583
|
-
name: `agent ${agentName}`,
|
|
1584
|
-
kind: SpanKind12.INTERNAL,
|
|
1585
|
-
attributes: {
|
|
1586
|
-
[FrontMcpAttributes.FLOW_NAME]: "agents:call-agent",
|
|
1587
|
-
[McpAttributes.COMPONENT_TYPE]: "agent",
|
|
1588
|
-
[McpAttributes.COMPONENT_KEY]: `agent:${agentName}`
|
|
1589
|
-
},
|
|
1590
|
-
parentContext: rpcCtx
|
|
1591
|
-
});
|
|
1592
|
-
const agentOTelCtx = trace3.setSpan(rpcCtx ?? otelContext3.active(), agentSpan);
|
|
1593
|
-
flowCtx.state[EXEC_SPAN_KEY] = agentSpan;
|
|
1594
|
-
flowCtx.state[STAGE_TS_KEY] = Date.now();
|
|
1595
|
-
recordStageEvent(agentSpan, "execute.start", flowCtx.state);
|
|
1596
|
-
storeActiveSpan(flowCtx, agentSpan, agentOTelCtx);
|
|
1597
|
-
}
|
|
1598
|
-
function onAgentDidExecute(flowCtx) {
|
|
1599
|
-
const agentSpan = flowCtx.state?.[EXEC_SPAN_KEY];
|
|
1600
|
-
if (!agentSpan) return;
|
|
1601
|
-
recordStageEvent(agentSpan, "execute.done", flowCtx.state);
|
|
1602
|
-
endSpanOk(agentSpan);
|
|
1603
|
-
flowCtx.state[EXEC_SPAN_KEY] = void 0;
|
|
1604
|
-
clearActiveSpan(flowCtx);
|
|
1605
|
-
}
|
|
1606
|
-
function onAgentDidFinalize(flowCtx) {
|
|
1607
|
-
const rpcSpan = flowCtx.state?.[SPAN_KEY];
|
|
1608
|
-
const agentSpan = flowCtx.state?.[EXEC_SPAN_KEY];
|
|
1609
|
-
const error = flowCtx.state?.flowError;
|
|
1610
|
-
if (error) {
|
|
1611
|
-
if (agentSpan) endFailedSpan(agentSpan, error);
|
|
1612
|
-
if (rpcSpan) endFailedSpan(rpcSpan, error);
|
|
1613
|
-
} else if (rpcSpan) {
|
|
1614
|
-
recordStageEvent(rpcSpan, "finalize", flowCtx.state);
|
|
1615
|
-
endSpanOk(rpcSpan);
|
|
1616
|
-
}
|
|
1617
|
-
}
|
|
1618
|
-
function onGenericFlowWillStart(flowName, options, flowCtx) {
|
|
1619
|
-
if (options.executionSpans === false) return;
|
|
1620
|
-
const ctx = extractContext(flowCtx);
|
|
1621
|
-
if (!ctx) return;
|
|
1622
|
-
const tracer = getTracer();
|
|
1623
|
-
const parentOTelCtx = parentContextOf(ctx);
|
|
1624
|
-
const sessionHash = sessionTracingId(ctx.sessionId);
|
|
1625
|
-
const { span, context: spanCtx } = startSpan(tracer, {
|
|
1626
|
-
name: flowName,
|
|
1627
|
-
kind: SpanKind12.INTERNAL,
|
|
1628
|
-
attributes: {
|
|
1629
|
-
[FrontMcpAttributes.FLOW_NAME]: flowName,
|
|
1630
|
-
[McpAttributes.SESSION_ID]: sessionHash,
|
|
1631
|
-
[FrontMcpAttributes.SESSION_ID_HASH]: sessionHash,
|
|
1632
|
-
[FrontMcpAttributes.SCOPE_ID]: ctx.scopeId,
|
|
1633
|
-
[FrontMcpAttributes.REQUEST_ID]: ctx.requestId
|
|
1634
|
-
},
|
|
1635
|
-
parentContext: parentOTelCtx
|
|
1636
|
-
});
|
|
1637
|
-
beginFlowSpan(flowCtx, options, span, spanCtx);
|
|
1638
|
-
}
|
|
1639
|
-
function onGenericFlowStage(stageName, flowCtx) {
|
|
1640
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1641
|
-
if (span) recordStageEvent(span, stageName, flowCtx.state);
|
|
1642
|
-
}
|
|
1643
|
-
function onGenericFlowDidFinalize(flowCtx) {
|
|
1644
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1645
|
-
if (!span) return;
|
|
1646
|
-
const error = flowCtx.state?.flowError;
|
|
1647
|
-
if (error) {
|
|
1648
|
-
endFailedSpan(span, error);
|
|
1649
|
-
} else {
|
|
1650
|
-
endSpanOk(span);
|
|
1651
|
-
}
|
|
1652
|
-
}
|
|
1653
|
-
function onTransportWillStart(transportType, options, flowCtx) {
|
|
1654
|
-
if (options.transportSpans === false) return;
|
|
1655
|
-
const ctx = extractContext(flowCtx);
|
|
1656
|
-
if (!ctx) return;
|
|
1657
|
-
const tracer = getTracer();
|
|
1658
|
-
const parentOTelCtx = parentContextOf(ctx);
|
|
1659
|
-
const sessionHash = sessionTracingId(ctx.sessionId);
|
|
1660
|
-
const { span, context: spanCtx } = startTransportSpan(tracer, {
|
|
1661
|
-
type: transportType,
|
|
1662
|
-
sessionIdHash: sessionHash,
|
|
1663
|
-
parentContext: parentOTelCtx
|
|
1664
|
-
});
|
|
1665
|
-
beginFlowSpan(flowCtx, options, span, spanCtx);
|
|
1666
|
-
recordStageEvent(span, "parseInput", flowCtx.state);
|
|
1667
|
-
}
|
|
1668
|
-
function onTransportDidRoute(flowCtx) {
|
|
1669
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1670
|
-
if (!span) return;
|
|
1671
|
-
recordStageEvent(span, "router", flowCtx.state);
|
|
1672
|
-
const requestType = flowCtx.state?.requestType;
|
|
1673
|
-
if (requestType) setTransportRequestType(span, requestType);
|
|
1674
|
-
}
|
|
1675
|
-
function onTransportStage(stageName, flowCtx) {
|
|
1676
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1677
|
-
if (span) recordStageEvent(span, stageName, flowCtx.state);
|
|
1678
|
-
}
|
|
1679
|
-
function onTransportDidFinalize(flowCtx) {
|
|
1680
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1681
|
-
if (!span) return;
|
|
1682
|
-
recordStageEvent(span, "cleanup", flowCtx.state);
|
|
1683
|
-
const error = flowCtx.state?.flowError;
|
|
1684
|
-
if (error) {
|
|
1685
|
-
endFailedSpan(span, error);
|
|
1686
|
-
} else {
|
|
1687
|
-
endSpanOk(span);
|
|
1688
|
-
}
|
|
1689
|
-
}
|
|
1690
|
-
function onAuthWillStart(flowName, options, flowCtx) {
|
|
1691
|
-
if (options.authSpans === false) return;
|
|
1692
|
-
const ctx = extractContext(flowCtx);
|
|
1693
|
-
if (!ctx) return;
|
|
1694
|
-
const tracer = getTracer();
|
|
1695
|
-
const parentOTelCtx = parentContextOf(ctx);
|
|
1696
|
-
const { span, context: spanCtx } = startAuthSpan(tracer, {
|
|
1697
|
-
flowName,
|
|
1698
|
-
parentContext: parentOTelCtx
|
|
1699
|
-
});
|
|
1700
|
-
beginFlowSpan(flowCtx, options, span, spanCtx);
|
|
1701
|
-
recordStageEvent(span, "parseInput", flowCtx.state);
|
|
1702
|
-
}
|
|
1703
|
-
function onAuthDidDetermineMode(flowCtx) {
|
|
1704
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1705
|
-
if (!span) return;
|
|
1706
|
-
recordStageEvent(span, "determineAuthMode", flowCtx.state);
|
|
1707
|
-
const mode = flowCtx.state?.authMode;
|
|
1708
|
-
if (mode) setAuthMode(span, mode);
|
|
1709
|
-
}
|
|
1710
|
-
function onAuthStage(stageName, flowCtx) {
|
|
1711
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1712
|
-
if (span) recordStageEvent(span, stageName, flowCtx.state);
|
|
1713
|
-
}
|
|
1714
|
-
function onAuthDidFinalize(flowCtx) {
|
|
1715
|
-
const span = flowCtx.state?.[SPAN_KEY];
|
|
1716
|
-
if (!span) return;
|
|
1717
|
-
const error = flowCtx.state?.flowError;
|
|
1718
|
-
if (error) {
|
|
1719
|
-
setAuthResult(span, "unauthorized");
|
|
1720
|
-
endFailedSpan(span, error);
|
|
1721
|
-
} else {
|
|
1722
|
-
setAuthResult(span, "authorized");
|
|
1723
|
-
endSpanOk(span);
|
|
1724
|
-
}
|
|
1725
|
-
}
|
|
1726
|
-
function wrapContextFetch(options, flowCtx) {
|
|
1727
|
-
const toolCtx = flowCtx.state?.toolContext ?? flowCtx.state?.toolCallContext;
|
|
1728
|
-
if (!toolCtx || typeof toolCtx.fetch !== "function") return;
|
|
1729
|
-
const originalFetch = toolCtx.fetch.bind(toolCtx);
|
|
1730
|
-
const parentOTelCtx = flowCtx.state?.[SPAN_CTX_KEY];
|
|
1731
|
-
toolCtx.fetch = async (input, init) => {
|
|
1732
|
-
const fetchSpan = options.fetchSpans === false ? void 0 : startFetchSpan(getTracer(), {
|
|
1733
|
-
method: init?.method ?? (input instanceof Request ? input.method : "GET"),
|
|
1734
|
-
url: typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url,
|
|
1735
|
-
parentContext: parentOTelCtx
|
|
1736
|
-
}).span;
|
|
1737
|
-
const callingSpan = fetchSpan ?? flowCtx.state?.[EXEC_SPAN_KEY] ?? flowCtx.state?.[SPAN_KEY];
|
|
1738
|
-
const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
|
|
1739
|
-
if (callingSpan && !headers.has("traceparent")) headers.set("traceparent", traceparentOf(callingSpan));
|
|
1740
|
-
try {
|
|
1741
|
-
const response = await originalFetch(input, { ...init, headers });
|
|
1742
|
-
if (fetchSpan) {
|
|
1743
|
-
setFetchResponseStatus(fetchSpan, response.status);
|
|
1744
|
-
endSpanOk(fetchSpan);
|
|
1745
|
-
}
|
|
1746
|
-
return response;
|
|
1747
|
-
} catch (err) {
|
|
1748
|
-
if (fetchSpan) endSpanError(fetchSpan, err instanceof Error ? err : String(err));
|
|
1749
|
-
throw err;
|
|
1750
|
-
}
|
|
1751
|
-
};
|
|
1752
|
-
}
|
|
1753
|
-
function onAgentDidExecuteEnrich(flowCtx) {
|
|
1754
|
-
const agentSpan = flowCtx.state?.[EXEC_SPAN_KEY];
|
|
1755
|
-
if (!agentSpan) return;
|
|
1756
|
-
const meta = flowCtx.state?.executionMeta;
|
|
1757
|
-
if (meta) {
|
|
1758
|
-
if (typeof meta.iterations === "number") {
|
|
1759
|
-
agentSpan.setAttribute(FrontMcpAttributes.AGENT_ITERATIONS, meta.iterations);
|
|
1760
|
-
}
|
|
1761
|
-
if (typeof meta.durationMs === "number") {
|
|
1762
|
-
agentSpan.setAttribute(FrontMcpAttributes.AGENT_EXECUTION_DURATION_MS, meta.durationMs);
|
|
1763
|
-
}
|
|
1764
|
-
}
|
|
1765
|
-
}
|
|
1766
|
-
var HOOK_OBSERVER_KEY = /* @__PURE__ */ Symbol.for("frontmcp:hook-observer");
|
|
1767
|
-
function installHookObserver(flowCtx, observer) {
|
|
1768
|
-
const ctx = extractContext(flowCtx);
|
|
1769
|
-
if (ctx && !ctx.get?.(HOOK_OBSERVER_KEY)) ctx.set?.(HOOK_OBSERVER_KEY, observer);
|
|
1770
|
-
}
|
|
1771
|
-
async function runInHookSpan(flowCtx, hook, run) {
|
|
1772
|
-
const ctx = extractContext(flowCtx);
|
|
1773
|
-
const { span } = startHookSpan(getTracer(), {
|
|
1774
|
-
...hook,
|
|
1775
|
-
parentContext: flowCtx.state?.[SPAN_CTX_KEY] ?? (ctx && parentContextOf(ctx))
|
|
1776
|
-
});
|
|
1777
|
-
try {
|
|
1778
|
-
await run();
|
|
1779
|
-
endSpanOk(span);
|
|
1780
|
-
} catch (error) {
|
|
1781
|
-
if (error instanceof FlowControl && error.type !== "fail" && error.type !== "abort") endSpanOk(span);
|
|
1782
|
-
else endFailedSpan(span, error);
|
|
1783
|
-
throw error;
|
|
1784
|
-
}
|
|
1785
|
-
}
|
|
1786
|
-
function reportStartup(data) {
|
|
1787
|
-
const tracer = getTracer();
|
|
1788
|
-
emitStartupReport(tracer, data);
|
|
1789
|
-
}
|
|
1790
|
-
|
|
1791
|
-
// libs/observability/src/request-log/request-log.tokens.ts
|
|
1792
|
-
var REQUEST_LOG_COLLECTOR = /* @__PURE__ */ Symbol.for("frontmcp:observability:request-log-collector");
|
|
1793
|
-
|
|
1794
|
-
// libs/observability/src/request-log/request-log.hooks.ts
|
|
1795
|
-
var FRONTMCP_CONTEXT = /* @__PURE__ */ Symbol.for("frontmcp:CONTEXT");
|
|
1796
|
-
function resolve(flowCtx, token) {
|
|
1797
|
-
try {
|
|
1798
|
-
return flowCtx.get?.(token);
|
|
1799
|
-
} catch {
|
|
1800
|
-
return void 0;
|
|
1801
|
-
}
|
|
1802
|
-
}
|
|
1803
|
-
function currentRequestLog(flowCtx) {
|
|
1804
|
-
return resolve(flowCtx, FRONTMCP_CONTEXT)?.get(REQUEST_LOG_COLLECTOR);
|
|
1805
|
-
}
|
|
1806
|
-
function startRequestLog(flowCtx, options) {
|
|
1807
|
-
const context = resolve(flowCtx, FRONTMCP_CONTEXT);
|
|
1808
|
-
if (!context) return;
|
|
1809
|
-
const collector = new RequestLogCollector(
|
|
1810
|
-
{
|
|
1811
|
-
requestId: context.requestId,
|
|
1812
|
-
traceId: context.traceContext.traceId,
|
|
1813
|
-
sessionIdHash: sessionTracingId(context.sessionId).slice(0, 12),
|
|
1814
|
-
scopeId: context.scopeId
|
|
1815
|
-
},
|
|
1816
|
-
options
|
|
1817
|
-
);
|
|
1818
|
-
context.set(REQUEST_LOG_COLLECTOR, collector);
|
|
1819
|
-
const request = flowCtx.rawInput?.request;
|
|
1820
|
-
if (request?.method && request.path) collector.setHttpInfo(request.method, request.path);
|
|
1821
|
-
const rpcMethod = request?.body?.method;
|
|
1822
|
-
if (typeof rpcMethod === "string") collector.setRpcMethod(rpcMethod);
|
|
1823
|
-
}
|
|
1824
|
-
function recordRequestLogFailure(flowCtx) {
|
|
1825
|
-
const flowError = flowCtx.state?.["flowError"];
|
|
1826
|
-
if (!flowError) return;
|
|
1827
|
-
const { type, message, code, errorId } = flowFailureOf(flowError);
|
|
1828
|
-
currentRequestLog(flowCtx)?.setError({ type, message, code, error_id: errorId });
|
|
1829
|
-
}
|
|
1830
|
-
function recordRequestLogAuth(flowCtx) {
|
|
1831
|
-
const verifyResult = flowCtx.state?.["verifyResult"];
|
|
1832
|
-
const authorization = flowCtx.rawInput?.request?.headers?.["authorization"];
|
|
1833
|
-
const scheme = typeof authorization === "string" ? authorization.trim().split(/\s+/)[0].toLowerCase() : "";
|
|
1834
|
-
const sub = verifyResult?.authorization?.user?.sub;
|
|
1835
|
-
const anonymous = typeof sub !== "string" || isAnonymousSubject(sub);
|
|
1836
|
-
currentRequestLog(flowCtx)?.setAuthInfo(
|
|
1837
|
-
anonymous || !scheme ? "anonymous" : scheme,
|
|
1838
|
-
verifyResult?.kind === "authorized" && !anonymous
|
|
1839
|
-
);
|
|
1840
|
-
}
|
|
1841
|
-
async function completeRequestLog(flowCtx) {
|
|
1842
|
-
const collector = currentRequestLog(flowCtx);
|
|
1843
|
-
if (!collector || collector.isFinalized()) return;
|
|
1844
|
-
const statusCode = flowCtx.state?.["statusCode"] ?? flowCtx.rawInput?.response?.statusCode;
|
|
1845
|
-
if (typeof statusCode === "number") collector.setStatusCode(statusCode);
|
|
1846
|
-
await collector.finalize();
|
|
1847
|
-
}
|
|
1848
|
-
|
|
1849
|
-
// libs/observability/src/telemetry/telemetry.accessor.ts
|
|
1850
|
-
import {
|
|
1851
|
-
SpanKind as SpanKind13,
|
|
1852
|
-
SpanStatusCode as SpanStatusCode3,
|
|
1853
|
-
trace as trace4
|
|
1854
|
-
} from "@opentelemetry/api";
|
|
1855
|
-
|
|
1856
|
-
// libs/observability/src/telemetry/telemetry.counters.ts
|
|
1857
|
-
import { metrics } from "@opentelemetry/api";
|
|
1858
|
-
function snapshotKey(name, attributes) {
|
|
1859
|
-
const keys = Object.keys(attributes).sort();
|
|
1860
|
-
if (keys.length === 0) return name;
|
|
1861
|
-
const tail = keys.map((k) => `${k}=${attributes[k]}`).join(",");
|
|
1862
|
-
return `${name}{${tail}}`;
|
|
1863
|
-
}
|
|
1864
|
-
var snapshotStore = /* @__PURE__ */ new Map();
|
|
1865
|
-
var TelemetryCounterImpl = class {
|
|
1866
|
-
constructor(name, otelCounter) {
|
|
1867
|
-
this.name = name;
|
|
1868
|
-
this.otelCounter = otelCounter;
|
|
1869
|
-
}
|
|
1870
|
-
inc(by = 1, attributes = {}) {
|
|
1871
|
-
if (!Number.isFinite(by) || by < 0) {
|
|
1872
|
-
return;
|
|
1873
|
-
}
|
|
1874
|
-
try {
|
|
1875
|
-
this.otelCounter.add(by, attributes);
|
|
1876
|
-
} catch {
|
|
1877
|
-
}
|
|
1878
|
-
const key = snapshotKey(this.name, attributes);
|
|
1879
|
-
const existing = snapshotStore.get(key);
|
|
1880
|
-
if (existing) {
|
|
1881
|
-
existing.count += by;
|
|
1882
|
-
} else {
|
|
1883
|
-
snapshotStore.set(key, { name: this.name, count: by, attributes: { ...attributes } });
|
|
1884
|
-
}
|
|
1885
|
-
}
|
|
1886
|
-
};
|
|
1887
|
-
var METER_NAME = "@frontmcp/observability";
|
|
1888
|
-
var counterCache = /* @__PURE__ */ new Map();
|
|
1889
|
-
function createCounter(name, description) {
|
|
1890
|
-
const existing = counterCache.get(name);
|
|
1891
|
-
if (existing) return existing;
|
|
1892
|
-
const meter = metrics.getMeter(METER_NAME);
|
|
1893
|
-
const otelCounter = meter.createCounter(name, description ? { description } : void 0);
|
|
1894
|
-
const counter = new TelemetryCounterImpl(name, otelCounter);
|
|
1895
|
-
counterCache.set(name, counter);
|
|
1896
|
-
return counter;
|
|
1897
|
-
}
|
|
1898
|
-
function getMetricSnapshot() {
|
|
1899
|
-
return Array.from(snapshotStore.values()).map((entry) => ({
|
|
1900
|
-
name: entry.name,
|
|
1901
|
-
count: entry.count,
|
|
1902
|
-
attributes: { ...entry.attributes }
|
|
1903
|
-
}));
|
|
1904
|
-
}
|
|
1905
|
-
function getCounterTotal(name) {
|
|
1906
|
-
let sum = 0;
|
|
1907
|
-
for (const entry of snapshotStore.values()) {
|
|
1908
|
-
if (entry.name === name) sum += entry.count;
|
|
1909
|
-
}
|
|
1910
|
-
return sum;
|
|
1911
|
-
}
|
|
1912
|
-
function resetMetricSnapshot() {
|
|
1913
|
-
snapshotStore.clear();
|
|
1914
|
-
}
|
|
1915
|
-
function resetTelemetrySnapshotForTesting() {
|
|
1916
|
-
snapshotStore.clear();
|
|
1917
|
-
}
|
|
1918
|
-
function resetCounterCacheForTesting() {
|
|
1919
|
-
counterCache.clear();
|
|
1920
|
-
}
|
|
1921
|
-
var KNOWN_BUNDLE_SOURCES = ["static", "npm", "saas-pull", "webhook", "filesystem", "unknown"];
|
|
1922
|
-
function normalizeBundleSource(value) {
|
|
1923
|
-
if (typeof value !== "string") return "unknown";
|
|
1924
|
-
return KNOWN_BUNDLE_SOURCES.includes(value) ? value : "unknown";
|
|
1925
|
-
}
|
|
1926
|
-
var KNOWN_ERROR_REASONS = ["network", "timeout", "invalid_response", "parse_error", "unknown"];
|
|
1927
|
-
function normalizeErrorReason(err) {
|
|
1928
|
-
if (!err) return "unknown";
|
|
1929
|
-
const name = err instanceof Error ? err.name : "";
|
|
1930
|
-
const message = err instanceof Error ? err.message : typeof err === "string" ? err : "";
|
|
1931
|
-
const haystack = `${name} ${message}`.toLowerCase();
|
|
1932
|
-
if (name === "TimeoutError" || haystack.includes("timeout") || haystack.includes("timed out")) {
|
|
1933
|
-
return "timeout";
|
|
1934
|
-
}
|
|
1935
|
-
if (name === "NetworkError" || name === "FetchError" || haystack.includes("network") || haystack.includes("econnrefused") || haystack.includes("econnreset") || haystack.includes("enotfound") || haystack.includes("socket") || haystack.includes("dns")) {
|
|
1936
|
-
return "network";
|
|
1937
|
-
}
|
|
1938
|
-
if (name === "SyntaxError" || haystack.includes("parse") || haystack.includes("json")) {
|
|
1939
|
-
return "parse_error";
|
|
1940
|
-
}
|
|
1941
|
-
if (name === "TypeError" || name === "RangeError" || haystack.includes("invalid") || haystack.includes("malformed") || haystack.includes("schema")) {
|
|
1942
|
-
return "invalid_response";
|
|
1943
|
-
}
|
|
1944
|
-
return "unknown";
|
|
1945
|
-
}
|
|
1946
|
-
|
|
1947
|
-
// libs/observability/src/telemetry/telemetry.accessor.ts
|
|
1948
|
-
var TelemetrySpan = class {
|
|
1949
|
-
constructor(span) {
|
|
1950
|
-
this.span = span;
|
|
1951
|
-
this.hasError = false;
|
|
1952
|
-
}
|
|
1953
|
-
/** Set a string/number/boolean attribute */
|
|
1954
|
-
setAttribute(key, value) {
|
|
1955
|
-
this.span.setAttribute(key, value);
|
|
1956
|
-
return this;
|
|
1957
|
-
}
|
|
1958
|
-
/** Set multiple attributes at once */
|
|
1959
|
-
setAttributes(attrs) {
|
|
1960
|
-
this.span.setAttributes(attrs);
|
|
1961
|
-
return this;
|
|
1962
|
-
}
|
|
1963
|
-
/** Add a named event (with optional attributes) */
|
|
1964
|
-
addEvent(name, attributes) {
|
|
1965
|
-
this.span.addEvent(name, attributes);
|
|
1966
|
-
return this;
|
|
1967
|
-
}
|
|
1968
|
-
/** Record an error on this span */
|
|
1969
|
-
recordError(error) {
|
|
1970
|
-
this.span.recordException(error);
|
|
1971
|
-
this.span.setStatus({ code: SpanStatusCode3.ERROR, message: error.message });
|
|
1972
|
-
this.hasError = true;
|
|
1973
|
-
return this;
|
|
1974
|
-
}
|
|
1975
|
-
/** End the span (preserves ERROR status if already set) */
|
|
1976
|
-
end() {
|
|
1977
|
-
if (!this.hasError) {
|
|
1978
|
-
this.span.setStatus({ code: SpanStatusCode3.OK });
|
|
1979
|
-
}
|
|
1980
|
-
this.span.end();
|
|
1981
|
-
}
|
|
1982
|
-
/** End the span with error */
|
|
1983
|
-
endWithError(error) {
|
|
1984
|
-
const msg = typeof error === "string" ? error : error.message;
|
|
1985
|
-
if (error instanceof Error) this.span.recordException(error);
|
|
1986
|
-
this.span.setStatus({ code: SpanStatusCode3.ERROR, message: msg });
|
|
1987
|
-
this.span.end();
|
|
1988
|
-
}
|
|
1989
|
-
/** Get the underlying OTel span (escape hatch) */
|
|
1990
|
-
get raw() {
|
|
1991
|
-
return this.span;
|
|
1992
|
-
}
|
|
1993
|
-
};
|
|
1994
|
-
var TelemetryAccessor = class {
|
|
1995
|
-
constructor(ctx) {
|
|
1996
|
-
this.ctx = ctx;
|
|
1997
|
-
this.tracer = trace4.getTracer("@frontmcp/observability");
|
|
1998
|
-
this.fallbackContext = createOTelContextFromTrace(ctx.traceContext);
|
|
1999
|
-
this.sessionHash = sessionTracingId(ctx.sessionId);
|
|
2000
|
-
this.baseAttributes = {
|
|
2001
|
-
[FrontMcpAttributes.REQUEST_ID]: ctx.requestId,
|
|
2002
|
-
[FrontMcpAttributes.SCOPE_ID]: ctx.scopeId,
|
|
2003
|
-
[McpAttributes.SESSION_ID]: this.sessionHash
|
|
2004
|
-
};
|
|
2005
|
-
}
|
|
2006
|
-
/**
|
|
2007
|
-
* Get the active OTel context — prefers the execution span's context
|
|
2008
|
-
* (set by hooks during willExecute), falls back to the request-level trace.
|
|
2009
|
-
*/
|
|
2010
|
-
getActiveContext() {
|
|
2011
|
-
const otelCtx = this.ctx.get?.(ACTIVE_OTEL_CTX_KEY);
|
|
2012
|
-
return otelCtx ?? this.fallbackContext;
|
|
2013
|
-
}
|
|
2014
|
-
/**
|
|
2015
|
-
* Get the active execution span (set by auto-instrumentation hooks).
|
|
2016
|
-
* Returns undefined if not inside an instrumented execution stage.
|
|
2017
|
-
*/
|
|
2018
|
-
getActiveSpan() {
|
|
2019
|
-
return this.ctx.get?.(ACTIVE_SPAN_KEY);
|
|
2020
|
-
}
|
|
2021
|
-
/**
|
|
2022
|
-
* Start a new child span under the current execution span.
|
|
2023
|
-
*
|
|
2024
|
-
* If called inside a tool's execute(), the span is a child of
|
|
2025
|
-
* the tool execution span. Otherwise falls back to the request trace.
|
|
2026
|
-
*
|
|
2027
|
-
* You MUST call `span.end()` or `span.endWithError()` when done.
|
|
2028
|
-
*/
|
|
2029
|
-
startSpan(name, attributes) {
|
|
2030
|
-
const span = this.tracer.startSpan(
|
|
2031
|
-
name,
|
|
2032
|
-
{
|
|
2033
|
-
kind: SpanKind13.INTERNAL,
|
|
2034
|
-
attributes: { ...this.baseAttributes, ...attributes }
|
|
2035
|
-
},
|
|
2036
|
-
this.getActiveContext()
|
|
2037
|
-
);
|
|
2038
|
-
return new TelemetrySpan(span);
|
|
2039
|
-
}
|
|
2040
|
-
/**
|
|
2041
|
-
* Run a function within a child span. Automatically ended on
|
|
2042
|
-
* success (OK) or error (ERROR + exception recorded).
|
|
2043
|
-
*
|
|
2044
|
-
* @example
|
|
2045
|
-
* ```typescript
|
|
2046
|
-
* const data = await this.telemetry.withSpan('fetch-api', async (span) => {
|
|
2047
|
-
* span.addEvent('request-sent');
|
|
2048
|
-
* const res = await this.fetch(url);
|
|
2049
|
-
* span.setAttribute('status', res.status);
|
|
2050
|
-
* return res.json();
|
|
2051
|
-
* });
|
|
2052
|
-
* ```
|
|
2053
|
-
*/
|
|
2054
|
-
async withSpan(name, fn, attributes) {
|
|
2055
|
-
const telemetrySpan = this.startSpan(name, attributes);
|
|
2056
|
-
try {
|
|
2057
|
-
const result = await fn(telemetrySpan);
|
|
2058
|
-
telemetrySpan.end();
|
|
2059
|
-
return result;
|
|
2060
|
-
} catch (err) {
|
|
2061
|
-
telemetrySpan.endWithError(err instanceof Error ? err : String(err));
|
|
2062
|
-
throw err;
|
|
2063
|
-
}
|
|
2064
|
-
}
|
|
2065
|
-
/**
|
|
2066
|
-
* Add an event to the **active flow execution span**.
|
|
2067
|
-
*
|
|
2068
|
-
* If called inside a tool's execute(), the event appears on the
|
|
2069
|
-
* tool execution span. If no active span exists, creates a
|
|
2070
|
-
* lightweight child span carrying the event.
|
|
2071
|
-
*
|
|
2072
|
-
* @param name — event name (e.g., 'validation-complete', 'cache-hit')
|
|
2073
|
-
* @param attributes — optional event attributes
|
|
2074
|
-
*/
|
|
2075
|
-
addEvent(name, attributes) {
|
|
2076
|
-
const activeSpan = this.getActiveSpan();
|
|
2077
|
-
if (activeSpan) {
|
|
2078
|
-
activeSpan.addEvent(name, attributes);
|
|
2079
|
-
} else {
|
|
2080
|
-
const span = this.tracer.startSpan(
|
|
2081
|
-
name,
|
|
2082
|
-
{ kind: SpanKind13.INTERNAL, attributes: this.baseAttributes },
|
|
2083
|
-
this.fallbackContext
|
|
2084
|
-
);
|
|
2085
|
-
if (attributes) span.addEvent(name, attributes);
|
|
2086
|
-
span.setStatus({ code: SpanStatusCode3.OK });
|
|
2087
|
-
span.end();
|
|
2088
|
-
}
|
|
2089
|
-
}
|
|
2090
|
-
/**
|
|
2091
|
-
* Set attributes on the **active flow execution span**.
|
|
2092
|
-
*
|
|
2093
|
-
* If called inside a tool's execute(), attributes are set on the
|
|
2094
|
-
* tool execution span. If no active span exists, this is a no-op.
|
|
2095
|
-
*
|
|
2096
|
-
* @param attrs — key-value attributes
|
|
2097
|
-
*/
|
|
2098
|
-
setAttributes(attrs) {
|
|
2099
|
-
const activeSpan = this.getActiveSpan();
|
|
2100
|
-
if (activeSpan) {
|
|
2101
|
-
activeSpan.setAttributes(attrs);
|
|
2102
|
-
}
|
|
2103
|
-
}
|
|
2104
|
-
/**
|
|
2105
|
-
* Create (or retrieve cached) a named counter.
|
|
2106
|
-
*
|
|
2107
|
-
* Counter increments are exported through the global OTel MeterProvider
|
|
2108
|
-
* when one is configured, and are always recorded in an in-memory snapshot
|
|
2109
|
-
* store (`getMetricSnapshot()` from `@frontmcp/observability`) so tests can
|
|
2110
|
-
* assert behavior without standing up a full OTel pipeline.
|
|
2111
|
-
*
|
|
2112
|
-
* @param name - OTel-style snake_case name, e.g. `frontmcp_skills_bundle_pulls_total`
|
|
2113
|
-
* @param description - human-readable description
|
|
2114
|
-
*/
|
|
2115
|
-
createCounter(name, description) {
|
|
2116
|
-
return createCounter(name, description);
|
|
2117
|
-
}
|
|
2118
|
-
/**
|
|
2119
|
-
* Get the trace ID of the current request.
|
|
2120
|
-
* Useful for including in external API calls or logs.
|
|
2121
|
-
*/
|
|
2122
|
-
get traceId() {
|
|
2123
|
-
return trace4.getSpan(this.fallbackContext)?.spanContext().traceId ?? "";
|
|
2124
|
-
}
|
|
2125
|
-
/**
|
|
2126
|
-
* Get the session tracing ID (privacy-safe hash).
|
|
2127
|
-
*/
|
|
2128
|
-
get sessionId() {
|
|
2129
|
-
return this.sessionHash;
|
|
2130
|
-
}
|
|
2131
|
-
};
|
|
2132
|
-
|
|
2133
|
-
// libs/observability/src/telemetry/telemetry.factory.ts
|
|
2134
|
-
import { SpanStatusCode as SpanStatusCode4, trace as trace5 } from "@opentelemetry/api";
|
|
2135
|
-
var TelemetryFactory = class {
|
|
2136
|
-
constructor(tracerName = "@frontmcp/observability") {
|
|
2137
|
-
this.tracer = trace5.getTracer(tracerName);
|
|
2138
|
-
}
|
|
2139
|
-
/**
|
|
2140
|
-
* Create (or retrieve cached) a named counter. Increments propagate to
|
|
2141
|
-
* the OTel meter (when configured) and to the in-memory snapshot store.
|
|
2142
|
-
*
|
|
2143
|
-
* @param name - OTel-style snake_case name with `_total` suffix.
|
|
2144
|
-
* @param description - human-readable description (deduped: subsequent
|
|
2145
|
-
* calls with a different description return the
|
|
2146
|
-
* cached counter unchanged).
|
|
2147
|
-
*/
|
|
2148
|
-
createCounter(name, description) {
|
|
2149
|
-
return createCounter(name, description);
|
|
2150
|
-
}
|
|
2151
|
-
/**
|
|
2152
|
-
* Start a span. Caller is responsible for calling `end()` /
|
|
2153
|
-
* `endWithError()`. The span parents to the currently-active OTel
|
|
2154
|
-
* context; if none is active it becomes a root span.
|
|
2155
|
-
*/
|
|
2156
|
-
startSpan(name, attributes, parent) {
|
|
2157
|
-
const opts = attributes ? { attributes } : void 0;
|
|
2158
|
-
const span = parent ? this.tracer.startSpan(name, opts, parent) : this.tracer.startSpan(name, opts);
|
|
2159
|
-
return new TelemetrySpan(span);
|
|
2160
|
-
}
|
|
2161
|
-
/**
|
|
2162
|
-
* Convenience wrapper — start a span, run `fn` with it, end on success
|
|
2163
|
-
* or error. Same lifecycle as `TelemetryAccessor.withSpan` but without
|
|
2164
|
-
* the per-request base attributes.
|
|
2165
|
-
*/
|
|
2166
|
-
async withSpan(name, fn, attributes) {
|
|
2167
|
-
const span = this.startSpan(name, attributes);
|
|
2168
|
-
try {
|
|
2169
|
-
const result = await fn(span);
|
|
2170
|
-
span.end();
|
|
2171
|
-
return result;
|
|
2172
|
-
} catch (err) {
|
|
2173
|
-
span.endWithError(err instanceof Error ? err : String(err));
|
|
2174
|
-
throw err;
|
|
2175
|
-
}
|
|
2176
|
-
}
|
|
2177
|
-
};
|
|
2178
|
-
|
|
2179
|
-
// libs/observability/src/telemetry/telemetry.tokens.ts
|
|
2180
|
-
var TELEMETRY_ACCESSOR = /* @__PURE__ */ Symbol.for("frontmcp:observability:telemetry-accessor");
|
|
2181
|
-
var TELEMETRY_FACTORY = /* @__PURE__ */ Symbol.for("frontmcp:observability:telemetry-factory");
|
|
2182
|
-
|
|
2183
|
-
// libs/observability/src/plugin/observability.plugin.ts
|
|
2184
|
-
var PromptHook = FlowHooksOf("prompts:get-prompt");
|
|
2185
|
-
var ListPromptsHook = FlowHooksOf("prompts:list-prompts");
|
|
2186
|
-
var SkillSearchHook = FlowHooksOf("skills:search");
|
|
2187
|
-
var SkillLoadHook = FlowHooksOf("skills:load");
|
|
2188
|
-
var CompletionHook = FlowHooksOf("completion:complete");
|
|
2189
|
-
var LegacySseHook = FlowHooksOf("handle:legacy-sse");
|
|
2190
|
-
var StreamableHttpHook = FlowHooksOf("handle:streamable-http");
|
|
2191
|
-
var StatelessHttpHook = FlowHooksOf("handle:stateless-http");
|
|
2192
|
-
var AuthVerifyHook = FlowHooksOf("auth:verify");
|
|
2193
|
-
var SessionVerifyHook = FlowHooksOf("session:verify");
|
|
2194
|
-
var OAuthTokenHook = FlowHooksOf("oauth:token");
|
|
2195
|
-
var OAuthAuthorizeHook = FlowHooksOf("oauth:authorize");
|
|
2196
|
-
var OAuthCallbackHook = FlowHooksOf("oauth:callback");
|
|
2197
|
-
var OAuthProviderCallbackHook = FlowHooksOf("oauth:provider-callback");
|
|
2198
|
-
var OAuthRegisterHook = FlowHooksOf("oauth:register");
|
|
2199
|
-
var ElicitRequestHook = FlowHooksOf("elicitation:request");
|
|
2200
|
-
var ElicitResultHook = FlowHooksOf("elicitation:result");
|
|
2201
|
-
var SubscribeResourceHook = FlowHooksOf("resources:subscribe");
|
|
2202
|
-
var UnsubscribeResourceHook = FlowHooksOf("resources:unsubscribe");
|
|
2203
|
-
var SkillsHttpLlmTxtHook = FlowHooksOf("skills-http:llm-txt");
|
|
2204
|
-
var SkillsHttpLlmFullTxtHook = FlowHooksOf("skills-http:llm-full-txt");
|
|
2205
|
-
var SkillsHttpApiHook = FlowHooksOf("skills-http:api");
|
|
2206
|
-
var WellKnownJwksHook = FlowHooksOf("well-known.jwks");
|
|
2207
|
-
var WellKnownOAuthServerHook = FlowHooksOf("well-known.oauth-authorization-server");
|
|
2208
|
-
var WellKnownPrmHook = FlowHooksOf("well-known.prm");
|
|
2209
|
-
var LoggingSetLevelHook = FlowHooksOf("logging:set-level");
|
|
2210
|
-
var DEFAULT_TRACING = {
|
|
2211
|
-
httpSpans: true,
|
|
2212
|
-
executionSpans: true,
|
|
2213
|
-
hookSpans: false,
|
|
2214
|
-
fetchSpans: true,
|
|
2215
|
-
flowStageEvents: true,
|
|
2216
|
-
transportSpans: true,
|
|
2217
|
-
authSpans: true,
|
|
2218
|
-
oauthSpans: true,
|
|
2219
|
-
elicitationSpans: true,
|
|
2220
|
-
startupReport: true
|
|
2221
|
-
};
|
|
2222
|
-
var ObservabilityPlugin = class extends DynamicPlugin {
|
|
2223
|
-
constructor(options = {}) {
|
|
2224
|
-
super();
|
|
2225
|
-
/** Wraps each other hook the request runs: names it on the request's log, and gives it a span with `hookSpans`. */
|
|
2226
|
-
this.observeHook = async ({ flowName, stage, target, flowContext }, run) => {
|
|
2227
|
-
if (target === this) return run();
|
|
2228
|
-
if (this.requestLogsEnabled) currentRequestLog(flowContext)?.addHook(`${flowName}:${stage}`);
|
|
2229
|
-
if (!this.traces("hookSpans")) return run();
|
|
2230
|
-
const owner = target?.constructor?.name;
|
|
2231
|
-
return runInHookSpan(flowContext, { flowName, stage, owner }, run);
|
|
2232
|
-
};
|
|
2233
|
-
this.options = resolveOptions(options);
|
|
2234
|
-
this.tracingOpts = this.options.tracing !== false ? this.options.tracing : DEFAULT_TRACING;
|
|
2235
|
-
}
|
|
2236
|
-
get tracingEnabled() {
|
|
2237
|
-
return this.options.tracing !== false;
|
|
2238
|
-
}
|
|
2239
|
-
get requestLogsEnabled() {
|
|
2240
|
-
return this.options.requestLogs !== false;
|
|
2241
|
-
}
|
|
2242
|
-
/** Whether tracing is on and its `kind` option isn't off. */
|
|
2243
|
-
traces(kind) {
|
|
2244
|
-
return this.tracingEnabled && this.tracingOpts[kind] !== false;
|
|
2245
|
-
}
|
|
2246
|
-
/** Watches the hooks of the request `ctx` serves, from the first flow of it that this plugin sees. */
|
|
2247
|
-
watchHooks(ctx) {
|
|
2248
|
-
if (this.requestLogsEnabled || this.traces("hookSpans"))
|
|
2249
|
-
installHookObserver(ctx, this.observeHook);
|
|
2250
|
-
}
|
|
2251
|
-
/** Names the entry a request serves on its request log, and records the entry flow's failure. */
|
|
2252
|
-
annotateRequestLog(ctx, set) {
|
|
2253
|
-
if (!this.requestLogsEnabled) return;
|
|
2254
|
-
const flowCtx = ctx;
|
|
2255
|
-
const log = currentRequestLog(ctx);
|
|
2256
|
-
if (log && flowCtx.state?.input) set(log, flowCtx.state.input);
|
|
2257
|
-
}
|
|
2258
|
-
_httpWillTrace(ctx) {
|
|
2259
|
-
if (this.tracingEnabled) onHttpWillTrace(this.tracingOpts, ctx);
|
|
2260
|
-
if (this.options.requestLogs !== false) startRequestLog(ctx, this.options.requestLogs);
|
|
2261
|
-
this.watchHooks(ctx);
|
|
2262
|
-
}
|
|
2263
|
-
_httpWillQuota(ctx) {
|
|
2264
|
-
if (this.tracingEnabled) onHttpWillAcquireQuota(ctx);
|
|
2265
|
-
}
|
|
2266
|
-
_httpDidSemaphore(ctx) {
|
|
2267
|
-
if (this.tracingEnabled) onHttpDidAcquireQuota(ctx);
|
|
2268
|
-
}
|
|
2269
|
-
_httpWillAuth(ctx) {
|
|
2270
|
-
if (this.tracingEnabled) onHttpWillCheckAuth(ctx);
|
|
2271
|
-
}
|
|
2272
|
-
_httpDidAuth(ctx) {
|
|
2273
|
-
if (this.tracingEnabled) onHttpDidCheckAuth(ctx);
|
|
2274
|
-
if (this.requestLogsEnabled) recordRequestLogAuth(ctx);
|
|
2275
|
-
}
|
|
2276
|
-
_httpWillRoute(ctx) {
|
|
2277
|
-
if (this.tracingEnabled) onHttpWillRoute(ctx);
|
|
2278
|
-
}
|
|
2279
|
-
_httpDidRoute(ctx) {
|
|
2280
|
-
if (this.tracingEnabled) onHttpDidRoute(ctx);
|
|
2281
|
-
}
|
|
2282
|
-
_httpDidFinalize(ctx) {
|
|
2283
|
-
if (this.tracingEnabled) onHttpDidFinalize(ctx);
|
|
2284
|
-
if (this.requestLogsEnabled) void completeRequestLog(ctx);
|
|
2285
|
-
}
|
|
2286
|
-
_toolWillParse(ctx) {
|
|
2287
|
-
this.watchHooks(ctx);
|
|
2288
|
-
if (this.tracingEnabled) onToolWillParse(this.tracingOpts, ctx);
|
|
2289
|
-
}
|
|
2290
|
-
_toolWillFind(ctx) {
|
|
2291
|
-
if (this.tracingEnabled) onToolWillFindTool(ctx);
|
|
2292
|
-
this.annotateRequestLog(ctx, (log, input) => log.setToolName(String(input["name"])));
|
|
2293
|
-
}
|
|
2294
|
-
_toolWillCheckAuth(ctx) {
|
|
2295
|
-
if (this.tracingEnabled) onToolWillCheckAuth(ctx);
|
|
2296
|
-
}
|
|
2297
|
-
_toolWillCheckAuthorities(ctx) {
|
|
2298
|
-
if (this.tracingEnabled) onEntryWillCheckAuthorities(ctx);
|
|
2299
|
-
}
|
|
2300
|
-
_toolDidCheckAuthorities(ctx) {
|
|
2301
|
-
if (this.tracingEnabled) onEntryDidCheckAuthorities(ctx);
|
|
2302
|
-
}
|
|
2303
|
-
_toolWillCreateCtx(ctx) {
|
|
2304
|
-
if (this.tracingEnabled) onToolWillCreateContext(ctx);
|
|
2305
|
-
}
|
|
2306
|
-
_toolWillValidate(ctx) {
|
|
2307
|
-
if (this.tracingEnabled) onToolWillValidateInput(ctx);
|
|
2308
|
-
}
|
|
2309
|
-
_toolWillExecute(ctx) {
|
|
2310
|
-
if (this.tracingEnabled) onToolWillExecute(this.tracingOpts, ctx);
|
|
2311
|
-
}
|
|
2312
|
-
_toolDidExecute(ctx) {
|
|
2313
|
-
if (this.tracingEnabled) onToolDidExecute(this.tracingOpts, ctx);
|
|
2314
|
-
}
|
|
2315
|
-
_toolWillValidateOut(ctx) {
|
|
2316
|
-
if (this.tracingEnabled) onToolWillValidateOutput(ctx);
|
|
2317
|
-
}
|
|
2318
|
-
_toolWillApplyUI(ctx) {
|
|
2319
|
-
if (this.tracingEnabled) onToolWillApplyUI(ctx);
|
|
2320
|
-
}
|
|
2321
|
-
_toolDidFinalize(ctx) {
|
|
2322
|
-
if (this.tracingEnabled) onToolDidFinalize(ctx);
|
|
2323
|
-
if (this.requestLogsEnabled) recordRequestLogFailure(ctx);
|
|
2324
|
-
}
|
|
2325
|
-
_resourceWillParse(ctx) {
|
|
2326
|
-
this.watchHooks(ctx);
|
|
2327
|
-
if (this.tracingEnabled) onResourceWillParse(this.tracingOpts, ctx);
|
|
2328
|
-
}
|
|
2329
|
-
_resourceWillFind(ctx) {
|
|
2330
|
-
if (this.tracingEnabled) onResourceWillFind(ctx);
|
|
2331
|
-
this.annotateRequestLog(ctx, (log, input) => log.setResourceUri(String(input["uri"])));
|
|
2332
|
-
}
|
|
2333
|
-
_resourceWillCheckAuthorities(ctx) {
|
|
2334
|
-
if (this.tracingEnabled) onEntryWillCheckAuthorities(ctx);
|
|
2335
|
-
}
|
|
2336
|
-
_resourceDidCheckAuthorities(ctx) {
|
|
2337
|
-
if (this.tracingEnabled) onEntryDidCheckAuthorities(ctx);
|
|
2338
|
-
}
|
|
2339
|
-
_resourceWillExecute(ctx) {
|
|
2340
|
-
if (this.tracingEnabled) onResourceWillExecute(this.tracingOpts, ctx);
|
|
2341
|
-
}
|
|
2342
|
-
_resourceDidExecute(ctx) {
|
|
2343
|
-
if (this.tracingEnabled) onResourceDidExecute(ctx);
|
|
2344
|
-
}
|
|
2345
|
-
_resourceDidFinalize(ctx) {
|
|
2346
|
-
if (this.tracingEnabled) onResourceDidFinalize(ctx);
|
|
2347
|
-
if (this.requestLogsEnabled) recordRequestLogFailure(ctx);
|
|
2348
|
-
}
|
|
2349
|
-
_promptWillParse(ctx) {
|
|
2350
|
-
this.watchHooks(ctx);
|
|
2351
|
-
if (this.tracingEnabled) onPromptWillParse(this.tracingOpts, ctx);
|
|
2352
|
-
}
|
|
2353
|
-
_promptWillFind(ctx) {
|
|
2354
|
-
if (this.tracingEnabled) onPromptWillFind(ctx);
|
|
2355
|
-
this.annotateRequestLog(ctx, (log, input) => log.setPromptName(String(input["name"])));
|
|
2356
|
-
}
|
|
2357
|
-
_promptWillCheckAuthorities(ctx) {
|
|
2358
|
-
if (this.tracingEnabled) onEntryWillCheckAuthorities(ctx);
|
|
2359
|
-
}
|
|
2360
|
-
_promptDidCheckAuthorities(ctx) {
|
|
2361
|
-
if (this.tracingEnabled) onEntryDidCheckAuthorities(ctx);
|
|
2362
|
-
}
|
|
2363
|
-
_promptWillExecute(ctx) {
|
|
2364
|
-
if (this.tracingEnabled) onPromptWillExecute(this.tracingOpts, ctx);
|
|
2365
|
-
}
|
|
2366
|
-
_promptDidExecute(ctx) {
|
|
2367
|
-
if (this.tracingEnabled) onPromptDidExecute(ctx);
|
|
2368
|
-
}
|
|
2369
|
-
_promptDidFinalize(ctx) {
|
|
2370
|
-
if (this.tracingEnabled) onPromptDidFinalize(ctx);
|
|
2371
|
-
if (this.requestLogsEnabled) recordRequestLogFailure(ctx);
|
|
2372
|
-
}
|
|
2373
|
-
_agentWillParse(ctx) {
|
|
2374
|
-
this.watchHooks(ctx);
|
|
2375
|
-
if (this.tracingEnabled) onAgentWillParse(this.tracingOpts, ctx);
|
|
2376
|
-
}
|
|
2377
|
-
_agentWillFind(ctx) {
|
|
2378
|
-
if (this.tracingEnabled) onAgentWillFind(ctx);
|
|
2379
|
-
}
|
|
2380
|
-
_agentWillCheckAuthorities(ctx) {
|
|
2381
|
-
if (this.tracingEnabled) onEntryWillCheckAuthorities(ctx);
|
|
2382
|
-
}
|
|
2383
|
-
_agentDidCheckAuthorities(ctx) {
|
|
2384
|
-
if (this.tracingEnabled) onEntryDidCheckAuthorities(ctx);
|
|
2385
|
-
}
|
|
2386
|
-
_agentWillExecute(ctx) {
|
|
2387
|
-
if (this.tracingEnabled) onAgentWillExecute(this.tracingOpts, ctx);
|
|
2388
|
-
}
|
|
2389
|
-
_agentDidExecute(ctx) {
|
|
2390
|
-
if (this.tracingEnabled) onAgentDidExecute(ctx);
|
|
2391
|
-
}
|
|
2392
|
-
_agentDidFinalize(ctx) {
|
|
2393
|
-
if (this.tracingEnabled) onAgentDidFinalize(ctx);
|
|
2394
|
-
}
|
|
2395
|
-
_listToolsWill(ctx) {
|
|
2396
|
-
if (this.tracingEnabled) onGenericFlowWillStart("tools/list", this.tracingOpts, ctx);
|
|
2397
|
-
}
|
|
2398
|
-
_listToolsDidFind(ctx) {
|
|
2399
|
-
if (this.tracingEnabled) onGenericFlowStage("findTools", ctx);
|
|
2400
|
-
}
|
|
2401
|
-
_listToolsDidFilter(ctx) {
|
|
2402
|
-
if (this.tracingEnabled) onGenericFlowStage("filterByAuthorities", ctx);
|
|
2403
|
-
}
|
|
2404
|
-
_listToolsDone(ctx) {
|
|
2405
|
-
if (this.tracingEnabled) onGenericFlowDidFinalize(ctx);
|
|
2406
|
-
}
|
|
2407
|
-
_listResourcesWill(ctx) {
|
|
2408
|
-
if (this.tracingEnabled) onGenericFlowWillStart("resources/list", this.tracingOpts, ctx);
|
|
2409
|
-
}
|
|
2410
|
-
_listResourcesDidFilter(ctx) {
|
|
2411
|
-
if (this.tracingEnabled) onGenericFlowStage("filterByAuthorities", ctx);
|
|
2412
|
-
}
|
|
2413
|
-
_listResourcesDone(ctx) {
|
|
2414
|
-
if (this.tracingEnabled) onGenericFlowDidFinalize(ctx);
|
|
2415
|
-
}
|
|
2416
|
-
_listTemplatesWill(ctx) {
|
|
2417
|
-
if (this.tracingEnabled) onGenericFlowWillStart("resources/listTemplates", this.tracingOpts, ctx);
|
|
2418
|
-
}
|
|
2419
|
-
_listTemplatesDidFilter(ctx) {
|
|
2420
|
-
if (this.tracingEnabled) onGenericFlowStage("filterByAuthorities", ctx);
|
|
2421
|
-
}
|
|
2422
|
-
_listTemplatesDone(ctx) {
|
|
2423
|
-
if (this.tracingEnabled) onGenericFlowDidFinalize(ctx);
|
|
2424
|
-
}
|
|
2425
|
-
_listPromptsWill(ctx) {
|
|
2426
|
-
if (this.tracingEnabled) onGenericFlowWillStart("prompts/list", this.tracingOpts, ctx);
|
|
2427
|
-
}
|
|
2428
|
-
_listPromptsDidFilter(ctx) {
|
|
2429
|
-
if (this.tracingEnabled) onGenericFlowStage("filterByAuthorities", ctx);
|
|
2430
|
-
}
|
|
2431
|
-
_listPromptsDone(ctx) {
|
|
2432
|
-
if (this.tracingEnabled) onGenericFlowDidFinalize(ctx);
|
|
2433
|
-
}
|
|
2434
|
-
_skillSearchWill(ctx) {
|
|
2435
|
-
if (this.tracingEnabled) onGenericFlowWillStart("skills/search", this.tracingOpts, ctx);
|
|
2436
|
-
}
|
|
2437
|
-
_skillSearchDone(ctx) {
|
|
2438
|
-
if (this.tracingEnabled) onGenericFlowDidFinalize(ctx);
|
|
2439
|
-
}
|
|
2440
|
-
_skillLoadWill(ctx) {
|
|
2441
|
-
if (this.tracingEnabled) onGenericFlowWillStart("skills/load", this.tracingOpts, ctx);
|
|
2442
|
-
}
|
|
2443
|
-
_skillLoadStage(ctx) {
|
|
2444
|
-
if (this.tracingEnabled) onGenericFlowStage("loadSkills", ctx);
|
|
2445
|
-
}
|
|
2446
|
-
_skillLoadDone(ctx) {
|
|
2447
|
-
if (this.tracingEnabled) onGenericFlowDidFinalize(ctx);
|
|
2448
|
-
}
|
|
2449
|
-
_completionWill(ctx) {
|
|
2450
|
-
if (this.tracingEnabled) onGenericFlowWillStart("completion/complete", this.tracingOpts, ctx);
|
|
2451
|
-
}
|
|
2452
|
-
_completionDone(ctx) {
|
|
2453
|
-
if (this.tracingEnabled) onGenericFlowDidFinalize(ctx);
|
|
2454
|
-
}
|
|
2455
|
-
_sseWillParse(ctx) {
|
|
2456
|
-
if (this.tracingEnabled) onTransportWillStart("legacy-sse", this.tracingOpts, ctx);
|
|
2457
|
-
}
|
|
2458
|
-
_sseDidRoute(ctx) {
|
|
2459
|
-
if (this.tracingEnabled) onTransportDidRoute(ctx);
|
|
2460
|
-
}
|
|
2461
|
-
_sseDidInit(ctx) {
|
|
2462
|
-
if (this.tracingEnabled) onTransportStage("onInitialize", ctx);
|
|
2463
|
-
}
|
|
2464
|
-
_sseDidMsg(ctx) {
|
|
2465
|
-
if (this.tracingEnabled) onTransportStage("onMessage", ctx);
|
|
2466
|
-
}
|
|
2467
|
-
_sseDidElicit(ctx) {
|
|
2468
|
-
if (this.tracingEnabled) onTransportStage("onElicitResult", ctx);
|
|
2469
|
-
}
|
|
2470
|
-
_sseDidCleanup(ctx) {
|
|
2471
|
-
if (this.tracingEnabled) onTransportDidFinalize(ctx);
|
|
2472
|
-
}
|
|
2473
|
-
_shttpWillParse(ctx) {
|
|
2474
|
-
if (this.tracingEnabled) onTransportWillStart("streamable-http", this.tracingOpts, ctx);
|
|
2475
|
-
}
|
|
2476
|
-
_shttpDidRoute(ctx) {
|
|
2477
|
-
if (this.tracingEnabled) onTransportDidRoute(ctx);
|
|
2478
|
-
}
|
|
2479
|
-
_shttpDidInit(ctx) {
|
|
2480
|
-
if (this.tracingEnabled) onTransportStage("onInitialize", ctx);
|
|
2481
|
-
}
|
|
2482
|
-
_shttpDidMsg(ctx) {
|
|
2483
|
-
if (this.tracingEnabled) onTransportStage("onMessage", ctx);
|
|
2484
|
-
}
|
|
2485
|
-
_shttpDidElicit(ctx) {
|
|
2486
|
-
if (this.tracingEnabled) onTransportStage("onElicitResult", ctx);
|
|
2487
|
-
}
|
|
2488
|
-
_shttpDidSse(ctx) {
|
|
2489
|
-
if (this.tracingEnabled) onTransportStage("onSseListener", ctx);
|
|
2490
|
-
}
|
|
2491
|
-
_shttpDidExtApps(ctx) {
|
|
2492
|
-
if (this.tracingEnabled) onTransportStage("onExtApps", ctx);
|
|
2493
|
-
}
|
|
2494
|
-
_shttpDidCleanup(ctx) {
|
|
2495
|
-
if (this.tracingEnabled) onTransportDidFinalize(ctx);
|
|
2496
|
-
}
|
|
2497
|
-
_slhttpWillParse(ctx) {
|
|
2498
|
-
if (this.tracingEnabled) onTransportWillStart("stateless-http", this.tracingOpts, ctx);
|
|
2499
|
-
}
|
|
2500
|
-
_slhttpDidHandle(ctx) {
|
|
2501
|
-
if (this.tracingEnabled) onTransportStage("handleRequest", ctx);
|
|
2502
|
-
}
|
|
2503
|
-
_slhttpDidCleanup(ctx) {
|
|
2504
|
-
if (this.tracingEnabled) onTransportDidFinalize(ctx);
|
|
2505
|
-
}
|
|
2506
|
-
_authVerifyWill(ctx) {
|
|
2507
|
-
if (this.tracingEnabled) onAuthWillStart("auth:verify", this.tracingOpts, ctx);
|
|
2508
|
-
}
|
|
2509
|
-
_authVerifyDidMode(ctx) {
|
|
2510
|
-
if (this.tracingEnabled) onAuthDidDetermineMode(ctx);
|
|
2511
|
-
}
|
|
2512
|
-
_authVerifyDidToken(ctx) {
|
|
2513
|
-
if (this.tracingEnabled) onAuthStage("verifyToken", ctx);
|
|
2514
|
-
}
|
|
2515
|
-
_authVerifyDidBuild(ctx) {
|
|
2516
|
-
if (this.tracingEnabled) onAuthDidFinalize(ctx);
|
|
2517
|
-
}
|
|
2518
|
-
_sessionVerifyWill(ctx) {
|
|
2519
|
-
if (this.tracingEnabled) onAuthWillStart("session:verify", this.tracingOpts, ctx);
|
|
2520
|
-
}
|
|
2521
|
-
_sessionVerifyDidJwt(ctx) {
|
|
2522
|
-
if (this.tracingEnabled) onAuthStage("verifyIfJwt", ctx);
|
|
2523
|
-
}
|
|
2524
|
-
_sessionVerifyDidBuild(ctx) {
|
|
2525
|
-
if (this.tracingEnabled) onAuthDidFinalize(ctx);
|
|
2526
|
-
}
|
|
2527
|
-
_oauthTokenWill(ctx) {
|
|
2528
|
-
if (this.traces("oauthSpans")) onGenericFlowWillStart("oauth/token", this.tracingOpts, ctx);
|
|
2529
|
-
}
|
|
2530
|
-
_oauthTokenDone(ctx) {
|
|
2531
|
-
if (this.traces("oauthSpans")) onGenericFlowDidFinalize(ctx);
|
|
2532
|
-
}
|
|
2533
|
-
_oauthAuthzWill(ctx) {
|
|
2534
|
-
if (this.traces("oauthSpans")) onGenericFlowWillStart("oauth/authorize", this.tracingOpts, ctx);
|
|
2535
|
-
}
|
|
2536
|
-
_oauthAuthzDone(ctx) {
|
|
2537
|
-
if (this.traces("oauthSpans")) onGenericFlowDidFinalize(ctx);
|
|
2538
|
-
}
|
|
2539
|
-
_oauthCallbackWill(ctx) {
|
|
2540
|
-
if (this.traces("oauthSpans")) onGenericFlowWillStart("oauth/callback", this.tracingOpts, ctx);
|
|
2541
|
-
}
|
|
2542
|
-
_oauthCallbackDone(ctx) {
|
|
2543
|
-
if (this.traces("oauthSpans")) onGenericFlowDidFinalize(ctx);
|
|
2544
|
-
}
|
|
2545
|
-
_oauthProviderWill(ctx) {
|
|
2546
|
-
if (this.traces("oauthSpans")) onGenericFlowWillStart("oauth/provider-callback", this.tracingOpts, ctx);
|
|
2547
|
-
}
|
|
2548
|
-
_oauthProviderDone(ctx) {
|
|
2549
|
-
if (this.traces("oauthSpans")) onGenericFlowDidFinalize(ctx);
|
|
2550
|
-
}
|
|
2551
|
-
_oauthRegisterWill(ctx) {
|
|
2552
|
-
if (this.traces("oauthSpans")) onGenericFlowWillStart("oauth/register", this.tracingOpts, ctx);
|
|
2553
|
-
}
|
|
2554
|
-
_oauthRegisterDone(ctx) {
|
|
2555
|
-
if (this.traces("oauthSpans")) onGenericFlowDidFinalize(ctx);
|
|
2556
|
-
}
|
|
2557
|
-
_elicitReqWill(ctx) {
|
|
2558
|
-
if (this.traces("elicitationSpans")) onGenericFlowWillStart("elicitation/request", this.tracingOpts, ctx);
|
|
2559
|
-
}
|
|
2560
|
-
_elicitReqDone(ctx) {
|
|
2561
|
-
if (this.traces("elicitationSpans")) onGenericFlowDidFinalize(ctx);
|
|
2562
|
-
}
|
|
2563
|
-
_elicitResWill(ctx) {
|
|
2564
|
-
if (this.traces("elicitationSpans")) onGenericFlowWillStart("elicitation/result", this.tracingOpts, ctx);
|
|
2565
|
-
}
|
|
2566
|
-
_elicitResDone(ctx) {
|
|
2567
|
-
if (this.traces("elicitationSpans")) onGenericFlowDidFinalize(ctx);
|
|
2568
|
-
}
|
|
2569
|
-
_subscribeWill(ctx) {
|
|
2570
|
-
if (this.tracingEnabled) onGenericFlowWillStart("resources/subscribe", this.tracingOpts, ctx);
|
|
2571
|
-
}
|
|
2572
|
-
_subscribeDone(ctx) {
|
|
2573
|
-
if (this.tracingEnabled) onGenericFlowDidFinalize(ctx);
|
|
2574
|
-
}
|
|
2575
|
-
_unsubscribeWill(ctx) {
|
|
2576
|
-
if (this.tracingEnabled) onGenericFlowWillStart("resources/unsubscribe", this.tracingOpts, ctx);
|
|
2577
|
-
}
|
|
2578
|
-
_unsubscribeDone(ctx) {
|
|
2579
|
-
if (this.tracingEnabled) onGenericFlowDidFinalize(ctx);
|
|
2580
|
-
}
|
|
2581
|
-
_skillsLlmTxtWill(ctx) {
|
|
2582
|
-
if (this.tracingEnabled) onGenericFlowWillStart("skills-http/llm-txt", this.tracingOpts, ctx);
|
|
2583
|
-
}
|
|
2584
|
-
_skillsLlmTxtDone(ctx) {
|
|
2585
|
-
if (this.tracingEnabled) onGenericFlowDidFinalize(ctx);
|
|
2586
|
-
}
|
|
2587
|
-
_skillsLlmFullTxtWill(ctx) {
|
|
2588
|
-
if (this.tracingEnabled) onGenericFlowWillStart("skills-http/llm-full-txt", this.tracingOpts, ctx);
|
|
2589
|
-
}
|
|
2590
|
-
_skillsLlmFullTxtDone(ctx) {
|
|
2591
|
-
if (this.tracingEnabled) onGenericFlowDidFinalize(ctx);
|
|
2592
|
-
}
|
|
2593
|
-
_skillsApiWill(ctx) {
|
|
2594
|
-
if (this.tracingEnabled) onGenericFlowWillStart("skills-http/api", this.tracingOpts, ctx);
|
|
2595
|
-
}
|
|
2596
|
-
_skillsApiDone(ctx) {
|
|
2597
|
-
if (this.tracingEnabled) onGenericFlowDidFinalize(ctx);
|
|
2598
|
-
}
|
|
2599
|
-
_jwksWill(ctx) {
|
|
2600
|
-
if (this.tracingEnabled) onGenericFlowWillStart("well-known/jwks", this.tracingOpts, ctx);
|
|
2601
|
-
}
|
|
2602
|
-
_jwksDone(ctx) {
|
|
2603
|
-
if (this.tracingEnabled) onGenericFlowDidFinalize(ctx);
|
|
2604
|
-
}
|
|
2605
|
-
_oauthServerWill(ctx) {
|
|
2606
|
-
if (this.tracingEnabled) onGenericFlowWillStart("well-known/oauth-server", this.tracingOpts, ctx);
|
|
2607
|
-
}
|
|
2608
|
-
_oauthServerDone(ctx) {
|
|
2609
|
-
if (this.tracingEnabled) onGenericFlowDidFinalize(ctx);
|
|
2610
|
-
}
|
|
2611
|
-
_prmWill(ctx) {
|
|
2612
|
-
if (this.tracingEnabled) onGenericFlowWillStart("well-known/prm", this.tracingOpts, ctx);
|
|
2613
|
-
}
|
|
2614
|
-
_prmDone(ctx) {
|
|
2615
|
-
if (this.tracingEnabled) onGenericFlowDidFinalize(ctx);
|
|
2616
|
-
}
|
|
2617
|
-
_setLevelWill(ctx) {
|
|
2618
|
-
if (this.tracingEnabled) onGenericFlowWillStart("logging/set-level", this.tracingOpts, ctx);
|
|
2619
|
-
}
|
|
2620
|
-
_setLevelDone(ctx) {
|
|
2621
|
-
if (this.tracingEnabled) onGenericFlowDidFinalize(ctx);
|
|
2622
|
-
}
|
|
2623
|
-
_toolDidCreateCtxFetch(ctx) {
|
|
2624
|
-
if (this.tracingEnabled) wrapContextFetch(this.tracingOpts, ctx);
|
|
2625
|
-
}
|
|
2626
|
-
_agentDidExecuteMeta(ctx) {
|
|
2627
|
-
if (this.tracingEnabled) onAgentDidExecuteEnrich(ctx);
|
|
2628
|
-
}
|
|
2629
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
2630
|
-
// Startup Report (public method)
|
|
2631
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
2632
|
-
/**
|
|
2633
|
-
* Emit the `frontmcp.startup` span (`tracing.startupReport`). The scope calls it once it is ready.
|
|
2634
|
-
*/
|
|
2635
|
-
reportStartupTelemetry(data) {
|
|
2636
|
-
if (this.traces("startupReport")) reportStartup(data);
|
|
2637
|
-
}
|
|
2638
|
-
};
|
|
2639
|
-
ObservabilityPlugin.defaultOptions = {
|
|
2640
|
-
tracing: DEFAULT_TRACING,
|
|
2641
|
-
logging: false,
|
|
2642
|
-
requestLogs: false
|
|
2643
|
-
};
|
|
2644
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
2645
|
-
// Dynamic Providers
|
|
2646
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
2647
|
-
ObservabilityPlugin.dynamicProviders = (input) => {
|
|
2648
|
-
const options = resolveOptions(input);
|
|
2649
|
-
const providers = [];
|
|
2650
|
-
if (options.tracing !== false) {
|
|
2651
|
-
providers.push({
|
|
2652
|
-
name: "observability:tracer",
|
|
2653
|
-
provide: OTEL_TRACER,
|
|
2654
|
-
useValue: trace6.getTracer("@frontmcp/observability")
|
|
2655
|
-
});
|
|
2656
|
-
providers.push({
|
|
2657
|
-
name: "observability:config",
|
|
2658
|
-
provide: OTEL_CONFIG,
|
|
2659
|
-
useValue: options.tracing
|
|
2660
|
-
});
|
|
2661
|
-
providers.push({
|
|
2662
|
-
name: "observability:telemetry-accessor",
|
|
2663
|
-
provide: TELEMETRY_ACCESSOR,
|
|
2664
|
-
scope: ProviderScope.CONTEXT,
|
|
2665
|
-
inject: () => [FRONTMCP_CONTEXT2],
|
|
2666
|
-
useFactory: (ctx) => new TelemetryAccessor(ctx)
|
|
2667
|
-
});
|
|
2668
|
-
providers.push({
|
|
2669
|
-
name: "observability:telemetry-factory",
|
|
2670
|
-
provide: TELEMETRY_FACTORY,
|
|
2671
|
-
useValue: new TelemetryFactory()
|
|
2672
|
-
});
|
|
2673
|
-
}
|
|
2674
|
-
if (options.logging !== false) {
|
|
2675
|
-
const loggingOpts = options.logging;
|
|
2676
|
-
const sinks = createSinks(loggingOpts.sinks);
|
|
2677
|
-
const transport = new StructuredLogTransport(
|
|
2678
|
-
sinks,
|
|
2679
|
-
{
|
|
2680
|
-
redactFields: loggingOpts.redactFields,
|
|
2681
|
-
includeStacks: loggingOpts.includeStacks,
|
|
2682
|
-
staticFields: loggingOpts.staticFields
|
|
2683
|
-
},
|
|
2684
|
-
void 0
|
|
2685
|
-
);
|
|
2686
|
-
providers.push({
|
|
2687
|
-
name: "observability:structured-log-transport",
|
|
2688
|
-
provide: StructuredLogTransport,
|
|
2689
|
-
useValue: transport
|
|
2690
|
-
});
|
|
2691
|
-
}
|
|
2692
|
-
if (options.requestLogs !== false) {
|
|
2693
|
-
const requestLogOpts = options.requestLogs;
|
|
2694
|
-
providers.push({
|
|
2695
|
-
name: "observability:request-log-collector",
|
|
2696
|
-
provide: REQUEST_LOG_COLLECTOR,
|
|
2697
|
-
scope: ProviderScope.CONTEXT,
|
|
2698
|
-
inject: () => [FRONTMCP_CONTEXT2],
|
|
2699
|
-
useFactory: (ctx) => {
|
|
2700
|
-
return new RequestLogCollector(
|
|
2701
|
-
{
|
|
2702
|
-
requestId: ctx.requestId,
|
|
2703
|
-
traceId: ctx.traceContext.traceId,
|
|
2704
|
-
sessionIdHash: sessionTracingId(ctx.sessionId).slice(0, 12),
|
|
2705
|
-
scopeId: ctx.scopeId
|
|
2706
|
-
},
|
|
2707
|
-
requestLogOpts
|
|
2708
|
-
);
|
|
2709
|
-
}
|
|
2710
|
-
});
|
|
2711
|
-
}
|
|
2712
|
-
return providers;
|
|
2713
|
-
};
|
|
2714
|
-
__decorateClass([
|
|
2715
|
-
HttpHook.Will("traceRequest", { priority: -1e3 })
|
|
2716
|
-
], ObservabilityPlugin.prototype, "_httpWillTrace", 1);
|
|
2717
|
-
__decorateClass([
|
|
2718
|
-
HttpHook.Will("acquireQuota", { priority: -1e3 })
|
|
2719
|
-
], ObservabilityPlugin.prototype, "_httpWillQuota", 1);
|
|
2720
|
-
__decorateClass([
|
|
2721
|
-
HttpHook.Did("acquireSemaphore", { priority: 1e3 })
|
|
2722
|
-
], ObservabilityPlugin.prototype, "_httpDidSemaphore", 1);
|
|
2723
|
-
__decorateClass([
|
|
2724
|
-
HttpHook.Will("checkAuthorization", { priority: -1e3 })
|
|
2725
|
-
], ObservabilityPlugin.prototype, "_httpWillAuth", 1);
|
|
2726
|
-
__decorateClass([
|
|
2727
|
-
HttpHook.Did("checkAuthorization", { priority: 1e3 })
|
|
2728
|
-
], ObservabilityPlugin.prototype, "_httpDidAuth", 1);
|
|
2729
|
-
__decorateClass([
|
|
2730
|
-
HttpHook.Will("router", { priority: -1e3 })
|
|
2731
|
-
], ObservabilityPlugin.prototype, "_httpWillRoute", 1);
|
|
2732
|
-
__decorateClass([
|
|
2733
|
-
HttpHook.Did("router", { priority: 1e3 })
|
|
2734
|
-
], ObservabilityPlugin.prototype, "_httpDidRoute", 1);
|
|
2735
|
-
__decorateClass([
|
|
2736
|
-
HttpHook.Did("finalize", { priority: 1e3 })
|
|
2737
|
-
], ObservabilityPlugin.prototype, "_httpDidFinalize", 1);
|
|
2738
|
-
__decorateClass([
|
|
2739
|
-
ToolHook.Will("parseInput", { priority: -1e3 })
|
|
2740
|
-
], ObservabilityPlugin.prototype, "_toolWillParse", 1);
|
|
2741
|
-
__decorateClass([
|
|
2742
|
-
ToolHook.Will("findTool", { priority: -1e3 })
|
|
2743
|
-
], ObservabilityPlugin.prototype, "_toolWillFind", 1);
|
|
2744
|
-
__decorateClass([
|
|
2745
|
-
ToolHook.Will("checkToolAuthorization", { priority: -1e3 })
|
|
2746
|
-
], ObservabilityPlugin.prototype, "_toolWillCheckAuth", 1);
|
|
2747
|
-
__decorateClass([
|
|
2748
|
-
ToolHook.Will("checkEntryAuthorities", { priority: -1e3 })
|
|
2749
|
-
], ObservabilityPlugin.prototype, "_toolWillCheckAuthorities", 1);
|
|
2750
|
-
__decorateClass([
|
|
2751
|
-
ToolHook.Did("checkEntryAuthorities", { priority: 1e3 })
|
|
2752
|
-
], ObservabilityPlugin.prototype, "_toolDidCheckAuthorities", 1);
|
|
2753
|
-
__decorateClass([
|
|
2754
|
-
ToolHook.Will("createToolCallContext", { priority: -1e3 })
|
|
2755
|
-
], ObservabilityPlugin.prototype, "_toolWillCreateCtx", 1);
|
|
2756
|
-
__decorateClass([
|
|
2757
|
-
ToolHook.Will("validateInput", { priority: -1e3 })
|
|
2758
|
-
], ObservabilityPlugin.prototype, "_toolWillValidate", 1);
|
|
2759
|
-
__decorateClass([
|
|
2760
|
-
ToolHook.Will("execute", { priority: -1e3 })
|
|
2761
|
-
], ObservabilityPlugin.prototype, "_toolWillExecute", 1);
|
|
2762
|
-
__decorateClass([
|
|
2763
|
-
ToolHook.Did("execute", { priority: 1e3 })
|
|
2764
|
-
], ObservabilityPlugin.prototype, "_toolDidExecute", 1);
|
|
2765
|
-
__decorateClass([
|
|
2766
|
-
ToolHook.Will("validateOutput", { priority: -1e3 })
|
|
2767
|
-
], ObservabilityPlugin.prototype, "_toolWillValidateOut", 1);
|
|
2768
|
-
__decorateClass([
|
|
2769
|
-
ToolHook.Will("applyUI", { priority: -1e3 })
|
|
2770
|
-
], ObservabilityPlugin.prototype, "_toolWillApplyUI", 1);
|
|
2771
|
-
__decorateClass([
|
|
2772
|
-
ToolHook.Did("finalize", { priority: 1e3 })
|
|
2773
|
-
], ObservabilityPlugin.prototype, "_toolDidFinalize", 1);
|
|
2774
|
-
__decorateClass([
|
|
2775
|
-
ResourceHook.Will("parseInput", { priority: -1e3 })
|
|
2776
|
-
], ObservabilityPlugin.prototype, "_resourceWillParse", 1);
|
|
2777
|
-
__decorateClass([
|
|
2778
|
-
ResourceHook.Will("findResource", { priority: -1e3 })
|
|
2779
|
-
], ObservabilityPlugin.prototype, "_resourceWillFind", 1);
|
|
2780
|
-
__decorateClass([
|
|
2781
|
-
ResourceHook.Will("checkEntryAuthorities", { priority: -1e3 })
|
|
2782
|
-
], ObservabilityPlugin.prototype, "_resourceWillCheckAuthorities", 1);
|
|
2783
|
-
__decorateClass([
|
|
2784
|
-
ResourceHook.Did("checkEntryAuthorities", { priority: 1e3 })
|
|
2785
|
-
], ObservabilityPlugin.prototype, "_resourceDidCheckAuthorities", 1);
|
|
2786
|
-
__decorateClass([
|
|
2787
|
-
ResourceHook.Will("execute", { priority: -1e3 })
|
|
2788
|
-
], ObservabilityPlugin.prototype, "_resourceWillExecute", 1);
|
|
2789
|
-
__decorateClass([
|
|
2790
|
-
ResourceHook.Did("execute", { priority: 1e3 })
|
|
2791
|
-
], ObservabilityPlugin.prototype, "_resourceDidExecute", 1);
|
|
2792
|
-
__decorateClass([
|
|
2793
|
-
ResourceHook.Did("finalize", { priority: 1e3 })
|
|
2794
|
-
], ObservabilityPlugin.prototype, "_resourceDidFinalize", 1);
|
|
2795
|
-
__decorateClass([
|
|
2796
|
-
PromptHook.Will("parseInput", { priority: -1e3 })
|
|
2797
|
-
], ObservabilityPlugin.prototype, "_promptWillParse", 1);
|
|
2798
|
-
__decorateClass([
|
|
2799
|
-
PromptHook.Will("findPrompt", { priority: -1e3 })
|
|
2800
|
-
], ObservabilityPlugin.prototype, "_promptWillFind", 1);
|
|
2801
|
-
__decorateClass([
|
|
2802
|
-
PromptHook.Will("checkEntryAuthorities", { priority: -1e3 })
|
|
2803
|
-
], ObservabilityPlugin.prototype, "_promptWillCheckAuthorities", 1);
|
|
2804
|
-
__decorateClass([
|
|
2805
|
-
PromptHook.Did("checkEntryAuthorities", { priority: 1e3 })
|
|
2806
|
-
], ObservabilityPlugin.prototype, "_promptDidCheckAuthorities", 1);
|
|
2807
|
-
__decorateClass([
|
|
2808
|
-
PromptHook.Will("execute", { priority: -1e3 })
|
|
2809
|
-
], ObservabilityPlugin.prototype, "_promptWillExecute", 1);
|
|
2810
|
-
__decorateClass([
|
|
2811
|
-
PromptHook.Did("execute", { priority: 1e3 })
|
|
2812
|
-
], ObservabilityPlugin.prototype, "_promptDidExecute", 1);
|
|
2813
|
-
__decorateClass([
|
|
2814
|
-
PromptHook.Did("finalize", { priority: 1e3 })
|
|
2815
|
-
], ObservabilityPlugin.prototype, "_promptDidFinalize", 1);
|
|
2816
|
-
__decorateClass([
|
|
2817
|
-
AgentCallHook.Will("parseInput", { priority: -1e3 })
|
|
2818
|
-
], ObservabilityPlugin.prototype, "_agentWillParse", 1);
|
|
2819
|
-
__decorateClass([
|
|
2820
|
-
AgentCallHook.Will("findAgent", { priority: -1e3 })
|
|
2821
|
-
], ObservabilityPlugin.prototype, "_agentWillFind", 1);
|
|
2822
|
-
__decorateClass([
|
|
2823
|
-
AgentCallHook.Will("checkEntryAuthorities", { priority: -1e3 })
|
|
2824
|
-
], ObservabilityPlugin.prototype, "_agentWillCheckAuthorities", 1);
|
|
2825
|
-
__decorateClass([
|
|
2826
|
-
AgentCallHook.Did("checkEntryAuthorities", { priority: 1e3 })
|
|
2827
|
-
], ObservabilityPlugin.prototype, "_agentDidCheckAuthorities", 1);
|
|
2828
|
-
__decorateClass([
|
|
2829
|
-
AgentCallHook.Will("execute", { priority: -1e3 })
|
|
2830
|
-
], ObservabilityPlugin.prototype, "_agentWillExecute", 1);
|
|
2831
|
-
__decorateClass([
|
|
2832
|
-
AgentCallHook.Did("execute", { priority: 1e3 })
|
|
2833
|
-
], ObservabilityPlugin.prototype, "_agentDidExecute", 1);
|
|
2834
|
-
__decorateClass([
|
|
2835
|
-
AgentCallHook.Did("finalize", { priority: 1e3 })
|
|
2836
|
-
], ObservabilityPlugin.prototype, "_agentDidFinalize", 1);
|
|
2837
|
-
__decorateClass([
|
|
2838
|
-
ListToolsHook.Will("parseInput", { priority: -1e3 })
|
|
2839
|
-
], ObservabilityPlugin.prototype, "_listToolsWill", 1);
|
|
2840
|
-
__decorateClass([
|
|
2841
|
-
ListToolsHook.Did("findTools", { priority: 1e3 })
|
|
2842
|
-
], ObservabilityPlugin.prototype, "_listToolsDidFind", 1);
|
|
2843
|
-
__decorateClass([
|
|
2844
|
-
ListToolsHook.Did("filterByAuthorities", { priority: 1e3 })
|
|
2845
|
-
], ObservabilityPlugin.prototype, "_listToolsDidFilter", 1);
|
|
2846
|
-
__decorateClass([
|
|
2847
|
-
ListToolsHook.Did("parseTools", { priority: 1e3 })
|
|
2848
|
-
], ObservabilityPlugin.prototype, "_listToolsDone", 1);
|
|
2849
|
-
__decorateClass([
|
|
2850
|
-
ListResourcesHook.Will("parseInput", { priority: -1e3 })
|
|
2851
|
-
], ObservabilityPlugin.prototype, "_listResourcesWill", 1);
|
|
2852
|
-
__decorateClass([
|
|
2853
|
-
ListResourcesHook.Did("filterByAuthorities", { priority: 1e3 })
|
|
2854
|
-
], ObservabilityPlugin.prototype, "_listResourcesDidFilter", 1);
|
|
2855
|
-
__decorateClass([
|
|
2856
|
-
ListResourcesHook.Did("parseResources", { priority: 1e3 })
|
|
2857
|
-
], ObservabilityPlugin.prototype, "_listResourcesDone", 1);
|
|
2858
|
-
__decorateClass([
|
|
2859
|
-
ListResourceTemplatesHook.Will("parseInput", { priority: -1e3 })
|
|
2860
|
-
], ObservabilityPlugin.prototype, "_listTemplatesWill", 1);
|
|
2861
|
-
__decorateClass([
|
|
2862
|
-
ListResourceTemplatesHook.Did("filterByAuthorities", { priority: 1e3 })
|
|
2863
|
-
], ObservabilityPlugin.prototype, "_listTemplatesDidFilter", 1);
|
|
2864
|
-
__decorateClass([
|
|
2865
|
-
ListResourceTemplatesHook.Did("parseTemplates", { priority: 1e3 })
|
|
2866
|
-
], ObservabilityPlugin.prototype, "_listTemplatesDone", 1);
|
|
2867
|
-
__decorateClass([
|
|
2868
|
-
ListPromptsHook.Will("parseInput", { priority: -1e3 })
|
|
2869
|
-
], ObservabilityPlugin.prototype, "_listPromptsWill", 1);
|
|
2870
|
-
__decorateClass([
|
|
2871
|
-
ListPromptsHook.Did("filterByAuthorities", { priority: 1e3 })
|
|
2872
|
-
], ObservabilityPlugin.prototype, "_listPromptsDidFilter", 1);
|
|
2873
|
-
__decorateClass([
|
|
2874
|
-
ListPromptsHook.Did("parsePrompts", { priority: 1e3 })
|
|
2875
|
-
], ObservabilityPlugin.prototype, "_listPromptsDone", 1);
|
|
2876
|
-
__decorateClass([
|
|
2877
|
-
SkillSearchHook.Will("parseInput", { priority: -1e3 })
|
|
2878
|
-
], ObservabilityPlugin.prototype, "_skillSearchWill", 1);
|
|
2879
|
-
__decorateClass([
|
|
2880
|
-
SkillSearchHook.Did("finalize", { priority: 1e3 })
|
|
2881
|
-
], ObservabilityPlugin.prototype, "_skillSearchDone", 1);
|
|
2882
|
-
__decorateClass([
|
|
2883
|
-
SkillLoadHook.Will("parseInput", { priority: -1e3 })
|
|
2884
|
-
], ObservabilityPlugin.prototype, "_skillLoadWill", 1);
|
|
2885
|
-
__decorateClass([
|
|
2886
|
-
SkillLoadHook.Will("loadSkills", { priority: -1e3 })
|
|
2887
|
-
], ObservabilityPlugin.prototype, "_skillLoadStage", 1);
|
|
2888
|
-
__decorateClass([
|
|
2889
|
-
SkillLoadHook.Did("finalize", { priority: 1e3 })
|
|
2890
|
-
], ObservabilityPlugin.prototype, "_skillLoadDone", 1);
|
|
2891
|
-
__decorateClass([
|
|
2892
|
-
CompletionHook.Will("parseInput", { priority: -1e3 })
|
|
2893
|
-
], ObservabilityPlugin.prototype, "_completionWill", 1);
|
|
2894
|
-
__decorateClass([
|
|
2895
|
-
CompletionHook.Did("finalize", { priority: 1e3 })
|
|
2896
|
-
], ObservabilityPlugin.prototype, "_completionDone", 1);
|
|
2897
|
-
__decorateClass([
|
|
2898
|
-
LegacySseHook.Will("parseInput", { priority: -1e3 })
|
|
2899
|
-
], ObservabilityPlugin.prototype, "_sseWillParse", 1);
|
|
2900
|
-
__decorateClass([
|
|
2901
|
-
LegacySseHook.Did("router", { priority: 1e3 })
|
|
2902
|
-
], ObservabilityPlugin.prototype, "_sseDidRoute", 1);
|
|
2903
|
-
__decorateClass([
|
|
2904
|
-
LegacySseHook.Did("onInitialize", { priority: 1e3 })
|
|
2905
|
-
], ObservabilityPlugin.prototype, "_sseDidInit", 1);
|
|
2906
|
-
__decorateClass([
|
|
2907
|
-
LegacySseHook.Did("onMessage", { priority: 1e3 })
|
|
2908
|
-
], ObservabilityPlugin.prototype, "_sseDidMsg", 1);
|
|
2909
|
-
__decorateClass([
|
|
2910
|
-
LegacySseHook.Did("onElicitResult", { priority: 1e3 })
|
|
2911
|
-
], ObservabilityPlugin.prototype, "_sseDidElicit", 1);
|
|
2912
|
-
__decorateClass([
|
|
2913
|
-
LegacySseHook.Did("cleanup", { priority: 1e3 })
|
|
2914
|
-
], ObservabilityPlugin.prototype, "_sseDidCleanup", 1);
|
|
2915
|
-
__decorateClass([
|
|
2916
|
-
StreamableHttpHook.Will("parseInput", { priority: -1e3 })
|
|
2917
|
-
], ObservabilityPlugin.prototype, "_shttpWillParse", 1);
|
|
2918
|
-
__decorateClass([
|
|
2919
|
-
StreamableHttpHook.Did("router", { priority: 1e3 })
|
|
2920
|
-
], ObservabilityPlugin.prototype, "_shttpDidRoute", 1);
|
|
2921
|
-
__decorateClass([
|
|
2922
|
-
StreamableHttpHook.Did("onInitialize", { priority: 1e3 })
|
|
2923
|
-
], ObservabilityPlugin.prototype, "_shttpDidInit", 1);
|
|
2924
|
-
__decorateClass([
|
|
2925
|
-
StreamableHttpHook.Did("onMessage", { priority: 1e3 })
|
|
2926
|
-
], ObservabilityPlugin.prototype, "_shttpDidMsg", 1);
|
|
2927
|
-
__decorateClass([
|
|
2928
|
-
StreamableHttpHook.Did("onElicitResult", { priority: 1e3 })
|
|
2929
|
-
], ObservabilityPlugin.prototype, "_shttpDidElicit", 1);
|
|
2930
|
-
__decorateClass([
|
|
2931
|
-
StreamableHttpHook.Did("onSseListener", { priority: 1e3 })
|
|
2932
|
-
], ObservabilityPlugin.prototype, "_shttpDidSse", 1);
|
|
2933
|
-
__decorateClass([
|
|
2934
|
-
StreamableHttpHook.Did("onExtApps", { priority: 1e3 })
|
|
2935
|
-
], ObservabilityPlugin.prototype, "_shttpDidExtApps", 1);
|
|
2936
|
-
__decorateClass([
|
|
2937
|
-
StreamableHttpHook.Did("cleanup", { priority: 1e3 })
|
|
2938
|
-
], ObservabilityPlugin.prototype, "_shttpDidCleanup", 1);
|
|
2939
|
-
__decorateClass([
|
|
2940
|
-
StatelessHttpHook.Will("parseInput", { priority: -1e3 })
|
|
2941
|
-
], ObservabilityPlugin.prototype, "_slhttpWillParse", 1);
|
|
2942
|
-
__decorateClass([
|
|
2943
|
-
StatelessHttpHook.Did("handleRequest", { priority: 1e3 })
|
|
2944
|
-
], ObservabilityPlugin.prototype, "_slhttpDidHandle", 1);
|
|
2945
|
-
__decorateClass([
|
|
2946
|
-
StatelessHttpHook.Did("cleanup", { priority: 1e3 })
|
|
2947
|
-
], ObservabilityPlugin.prototype, "_slhttpDidCleanup", 1);
|
|
2948
|
-
__decorateClass([
|
|
2949
|
-
AuthVerifyHook.Will("parseInput", { priority: -1e3 })
|
|
2950
|
-
], ObservabilityPlugin.prototype, "_authVerifyWill", 1);
|
|
2951
|
-
__decorateClass([
|
|
2952
|
-
AuthVerifyHook.Did("determineAuthMode", { priority: 1e3 })
|
|
2953
|
-
], ObservabilityPlugin.prototype, "_authVerifyDidMode", 1);
|
|
2954
|
-
__decorateClass([
|
|
2955
|
-
AuthVerifyHook.Did("verifyToken", { priority: 1e3 })
|
|
2956
|
-
], ObservabilityPlugin.prototype, "_authVerifyDidToken", 1);
|
|
2957
|
-
__decorateClass([
|
|
2958
|
-
AuthVerifyHook.Did("buildAuthorization", { priority: 1e3 })
|
|
2959
|
-
], ObservabilityPlugin.prototype, "_authVerifyDidBuild", 1);
|
|
2960
|
-
__decorateClass([
|
|
2961
|
-
SessionVerifyHook.Will("parseInput", { priority: -1e3 })
|
|
2962
|
-
], ObservabilityPlugin.prototype, "_sessionVerifyWill", 1);
|
|
2963
|
-
__decorateClass([
|
|
2964
|
-
SessionVerifyHook.Did("verifyIfJwt", { priority: 1e3 })
|
|
2965
|
-
], ObservabilityPlugin.prototype, "_sessionVerifyDidJwt", 1);
|
|
2966
|
-
__decorateClass([
|
|
2967
|
-
SessionVerifyHook.Did("buildAuthorizedOutput", { priority: 1e3 })
|
|
2968
|
-
], ObservabilityPlugin.prototype, "_sessionVerifyDidBuild", 1);
|
|
2969
|
-
__decorateClass([
|
|
2970
|
-
OAuthTokenHook.Will("parseInput", { priority: -1e3 })
|
|
2971
|
-
], ObservabilityPlugin.prototype, "_oauthTokenWill", 1);
|
|
2972
|
-
__decorateClass([
|
|
2973
|
-
OAuthTokenHook.Did("buildTokenResponse", { priority: 1e3 })
|
|
2974
|
-
], ObservabilityPlugin.prototype, "_oauthTokenDone", 1);
|
|
2975
|
-
__decorateClass([
|
|
2976
|
-
OAuthAuthorizeHook.Will("parseInput", { priority: -1e3 })
|
|
2977
|
-
], ObservabilityPlugin.prototype, "_oauthAuthzWill", 1);
|
|
2978
|
-
__decorateClass([
|
|
2979
|
-
OAuthAuthorizeHook.Did("buildAuthorizeOutput", { priority: 1e3 })
|
|
2980
|
-
], ObservabilityPlugin.prototype, "_oauthAuthzDone", 1);
|
|
2981
|
-
__decorateClass([
|
|
2982
|
-
OAuthCallbackHook.Will("parseInput", { priority: -1e3 })
|
|
2983
|
-
], ObservabilityPlugin.prototype, "_oauthCallbackWill", 1);
|
|
2984
|
-
__decorateClass([
|
|
2985
|
-
OAuthCallbackHook.Did("redirectToClient", { priority: 1e3 })
|
|
2986
|
-
], ObservabilityPlugin.prototype, "_oauthCallbackDone", 1);
|
|
2987
|
-
__decorateClass([
|
|
2988
|
-
OAuthProviderCallbackHook.Will("parseInput", { priority: -1e3 })
|
|
2989
|
-
], ObservabilityPlugin.prototype, "_oauthProviderWill", 1);
|
|
2990
|
-
__decorateClass([
|
|
2991
|
-
OAuthProviderCallbackHook.Did("handleNextProviderOrComplete", { priority: 1e3 })
|
|
2992
|
-
], ObservabilityPlugin.prototype, "_oauthProviderDone", 1);
|
|
2993
|
-
__decorateClass([
|
|
2994
|
-
OAuthRegisterHook.Will("parseInput", { priority: -1e3 })
|
|
2995
|
-
], ObservabilityPlugin.prototype, "_oauthRegisterWill", 1);
|
|
2996
|
-
__decorateClass([
|
|
2997
|
-
OAuthRegisterHook.Did("respondRegistration", { priority: 1e3 })
|
|
2998
|
-
], ObservabilityPlugin.prototype, "_oauthRegisterDone", 1);
|
|
2999
|
-
__decorateClass([
|
|
3000
|
-
ElicitRequestHook.Will("parseInput", { priority: -1e3 })
|
|
3001
|
-
], ObservabilityPlugin.prototype, "_elicitReqWill", 1);
|
|
3002
|
-
__decorateClass([
|
|
3003
|
-
ElicitRequestHook.Did("finalize", { priority: 1e3 })
|
|
3004
|
-
], ObservabilityPlugin.prototype, "_elicitReqDone", 1);
|
|
3005
|
-
__decorateClass([
|
|
3006
|
-
ElicitResultHook.Will("parseInput", { priority: -1e3 })
|
|
3007
|
-
], ObservabilityPlugin.prototype, "_elicitResWill", 1);
|
|
3008
|
-
__decorateClass([
|
|
3009
|
-
ElicitResultHook.Did("finalize", { priority: 1e3 })
|
|
3010
|
-
], ObservabilityPlugin.prototype, "_elicitResDone", 1);
|
|
3011
|
-
__decorateClass([
|
|
3012
|
-
SubscribeResourceHook.Will("parseInput", { priority: -1e3 })
|
|
3013
|
-
], ObservabilityPlugin.prototype, "_subscribeWill", 1);
|
|
3014
|
-
__decorateClass([
|
|
3015
|
-
SubscribeResourceHook.Did("finalize", { priority: 1e3 })
|
|
3016
|
-
], ObservabilityPlugin.prototype, "_subscribeDone", 1);
|
|
3017
|
-
__decorateClass([
|
|
3018
|
-
UnsubscribeResourceHook.Will("parseInput", { priority: -1e3 })
|
|
3019
|
-
], ObservabilityPlugin.prototype, "_unsubscribeWill", 1);
|
|
3020
|
-
__decorateClass([
|
|
3021
|
-
UnsubscribeResourceHook.Did("finalize", { priority: 1e3 })
|
|
3022
|
-
], ObservabilityPlugin.prototype, "_unsubscribeDone", 1);
|
|
3023
|
-
__decorateClass([
|
|
3024
|
-
SkillsHttpLlmTxtHook.Will("checkEnabled", { priority: -1e3 })
|
|
3025
|
-
], ObservabilityPlugin.prototype, "_skillsLlmTxtWill", 1);
|
|
3026
|
-
__decorateClass([
|
|
3027
|
-
SkillsHttpLlmTxtHook.Did("generateContent", { priority: 1e3 })
|
|
3028
|
-
], ObservabilityPlugin.prototype, "_skillsLlmTxtDone", 1);
|
|
3029
|
-
__decorateClass([
|
|
3030
|
-
SkillsHttpLlmFullTxtHook.Will("checkEnabled", { priority: -1e3 })
|
|
3031
|
-
], ObservabilityPlugin.prototype, "_skillsLlmFullTxtWill", 1);
|
|
3032
|
-
__decorateClass([
|
|
3033
|
-
SkillsHttpLlmFullTxtHook.Did("generateContent", { priority: 1e3 })
|
|
3034
|
-
], ObservabilityPlugin.prototype, "_skillsLlmFullTxtDone", 1);
|
|
3035
|
-
__decorateClass([
|
|
3036
|
-
SkillsHttpApiHook.Will("checkEnabled", { priority: -1e3 })
|
|
3037
|
-
], ObservabilityPlugin.prototype, "_skillsApiWill", 1);
|
|
3038
|
-
__decorateClass([
|
|
3039
|
-
SkillsHttpApiHook.Did("handleRequest", { priority: 1e3 })
|
|
3040
|
-
], ObservabilityPlugin.prototype, "_skillsApiDone", 1);
|
|
3041
|
-
__decorateClass([
|
|
3042
|
-
WellKnownJwksHook.Will("parseInput", { priority: -1e3 })
|
|
3043
|
-
], ObservabilityPlugin.prototype, "_jwksWill", 1);
|
|
3044
|
-
__decorateClass([
|
|
3045
|
-
WellKnownJwksHook.Did("collectData", { priority: 1e3 })
|
|
3046
|
-
], ObservabilityPlugin.prototype, "_jwksDone", 1);
|
|
3047
|
-
__decorateClass([
|
|
3048
|
-
WellKnownOAuthServerHook.Will("parseInput", { priority: -1e3 })
|
|
3049
|
-
], ObservabilityPlugin.prototype, "_oauthServerWill", 1);
|
|
3050
|
-
__decorateClass([
|
|
3051
|
-
WellKnownOAuthServerHook.Did("collectData", { priority: 1e3 })
|
|
3052
|
-
], ObservabilityPlugin.prototype, "_oauthServerDone", 1);
|
|
3053
|
-
__decorateClass([
|
|
3054
|
-
WellKnownPrmHook.Will("parseInput", { priority: -1e3 })
|
|
3055
|
-
], ObservabilityPlugin.prototype, "_prmWill", 1);
|
|
3056
|
-
__decorateClass([
|
|
3057
|
-
WellKnownPrmHook.Did("collectData", { priority: 1e3 })
|
|
3058
|
-
], ObservabilityPlugin.prototype, "_prmDone", 1);
|
|
3059
|
-
__decorateClass([
|
|
3060
|
-
LoggingSetLevelHook.Will("parseInput", { priority: -1e3 })
|
|
3061
|
-
], ObservabilityPlugin.prototype, "_setLevelWill", 1);
|
|
3062
|
-
__decorateClass([
|
|
3063
|
-
LoggingSetLevelHook.Did("finalize", { priority: 1e3 })
|
|
3064
|
-
], ObservabilityPlugin.prototype, "_setLevelDone", 1);
|
|
3065
|
-
__decorateClass([
|
|
3066
|
-
ToolHook.Did("createToolCallContext", { priority: 999 })
|
|
3067
|
-
], ObservabilityPlugin.prototype, "_toolDidCreateCtxFetch", 1);
|
|
3068
|
-
__decorateClass([
|
|
3069
|
-
AgentCallHook.Did("execute", { priority: 999 })
|
|
3070
|
-
], ObservabilityPlugin.prototype, "_agentDidExecuteMeta", 1);
|
|
3071
|
-
ObservabilityPlugin = __decorateClass([
|
|
3072
|
-
Plugin({
|
|
3073
|
-
name: "observability",
|
|
3074
|
-
description: "Full-system OpenTelemetry instrumentation, structured logging, and request logs",
|
|
3075
|
-
providers: [],
|
|
3076
|
-
contextExtensions: [
|
|
3077
|
-
{
|
|
3078
|
-
property: "telemetry",
|
|
3079
|
-
token: TELEMETRY_ACCESSOR,
|
|
3080
|
-
errorMessage: "ObservabilityPlugin is not installed or tracing is disabled. Add ObservabilityPlugin.init() to your plugins array."
|
|
3081
|
-
}
|
|
3082
|
-
]
|
|
3083
|
-
})
|
|
3084
|
-
], ObservabilityPlugin);
|
|
3085
|
-
function resolveOptions(input) {
|
|
3086
|
-
return {
|
|
3087
|
-
tracing: resolveTracingOptions(input.tracing),
|
|
3088
|
-
logging: resolveLoggingOptions(input.logging),
|
|
3089
|
-
requestLogs: resolveRequestLogOptions(input.requestLogs)
|
|
3090
|
-
};
|
|
3091
|
-
}
|
|
3092
|
-
function resolveTracingOptions(input) {
|
|
3093
|
-
if (input === false) return false;
|
|
3094
|
-
if (input === true || input === void 0) return DEFAULT_TRACING;
|
|
3095
|
-
return { ...DEFAULT_TRACING, ...input };
|
|
3096
|
-
}
|
|
3097
|
-
function resolveLoggingOptions(input) {
|
|
3098
|
-
if (input === false || input === void 0) return false;
|
|
3099
|
-
if (input === true) return {};
|
|
3100
|
-
return input;
|
|
3101
|
-
}
|
|
3102
|
-
function resolveRequestLogOptions(input) {
|
|
3103
|
-
if (input === false || input === void 0) return false;
|
|
3104
|
-
if (input === true) return {};
|
|
3105
|
-
return input;
|
|
3106
|
-
}
|
|
3107
|
-
|
|
3108
|
-
// libs/observability/src/otel/context-propagator.ts
|
|
3109
|
-
import {
|
|
3110
|
-
trace as trace7
|
|
3111
|
-
} from "@opentelemetry/api";
|
|
3112
|
-
var TRACEPARENT_HEADER = "traceparent";
|
|
3113
|
-
var FrontMcpPropagator = class {
|
|
3114
|
-
inject(context, carrier, setter) {
|
|
3115
|
-
const span = trace7.getSpan(context);
|
|
3116
|
-
if (!span) return;
|
|
3117
|
-
const sc = span.spanContext();
|
|
3118
|
-
if (!sc || !isValidSpanContext(sc)) return;
|
|
3119
|
-
const flags = sc.traceFlags.toString(16).padStart(2, "0");
|
|
3120
|
-
const traceparent = `00-${sc.traceId}-${sc.spanId}-${flags}`;
|
|
3121
|
-
setter.set(carrier, TRACEPARENT_HEADER, traceparent);
|
|
3122
|
-
}
|
|
3123
|
-
extract(context, carrier, getter) {
|
|
3124
|
-
const traceparent = getter.get(carrier, TRACEPARENT_HEADER);
|
|
3125
|
-
const value = Array.isArray(traceparent) ? traceparent[0] : traceparent;
|
|
3126
|
-
if (!value) return context;
|
|
3127
|
-
const parsed = parseTraceparent(value);
|
|
3128
|
-
if (!parsed) return context;
|
|
3129
|
-
const spanContext = {
|
|
3130
|
-
traceId: parsed.traceId,
|
|
3131
|
-
spanId: parsed.parentId,
|
|
3132
|
-
traceFlags: parsed.traceFlags,
|
|
3133
|
-
isRemote: true
|
|
3134
|
-
};
|
|
3135
|
-
const span = trace7.wrapSpanContext(spanContext);
|
|
3136
|
-
return trace7.setSpan(context, span);
|
|
3137
|
-
}
|
|
3138
|
-
fields() {
|
|
3139
|
-
return [TRACEPARENT_HEADER];
|
|
3140
|
-
}
|
|
3141
|
-
};
|
|
3142
|
-
function parseTraceparent(value) {
|
|
3143
|
-
const parts = value.split("-");
|
|
3144
|
-
if (parts.length !== 4) return null;
|
|
3145
|
-
const [version, traceId, parentId, flags] = parts;
|
|
3146
|
-
if (version !== "00") return null;
|
|
3147
|
-
if (!/^[a-f0-9]{32}$/i.test(traceId) || traceId === "00000000000000000000000000000000") return null;
|
|
3148
|
-
if (!/^[a-f0-9]{16}$/i.test(parentId) || parentId === "0000000000000000") return null;
|
|
3149
|
-
if (!/^[0-9a-fA-F]{2}$/.test(flags)) return null;
|
|
3150
|
-
const traceFlags = parseInt(flags, 16);
|
|
3151
|
-
return {
|
|
3152
|
-
traceId: traceId.toLowerCase(),
|
|
3153
|
-
parentId: parentId.toLowerCase(),
|
|
3154
|
-
traceFlags
|
|
3155
|
-
};
|
|
3156
|
-
}
|
|
3157
|
-
function isValidSpanContext(sc) {
|
|
3158
|
-
return sc.traceId !== "00000000000000000000000000000000" && sc.spanId !== "0000000000000000" && sc.traceId.length === 32 && sc.spanId.length === 16;
|
|
3159
|
-
}
|
|
3160
|
-
|
|
3161
|
-
// libs/observability/src/otel/otel.setup.ts
|
|
3162
|
-
function setupOTel(options) {
|
|
3163
|
-
const serviceName = options?.serviceName ?? process.env["OTEL_SERVICE_NAME"] ?? "frontmcp-server";
|
|
3164
|
-
const exporterType = options?.exporter ?? "console";
|
|
3165
|
-
const endpoint = options?.endpoint ?? process.env["OTEL_EXPORTER_OTLP_ENDPOINT"] ?? "http://localhost:4318";
|
|
3166
|
-
let traceExporter;
|
|
3167
|
-
if (exporterType === "otlp") {
|
|
3168
|
-
try {
|
|
3169
|
-
const { OTLPTraceExporter } = __require("@opentelemetry/exporter-trace-otlp-http");
|
|
3170
|
-
traceExporter = new OTLPTraceExporter({ url: `${endpoint}/v1/traces` });
|
|
3171
|
-
} catch {
|
|
3172
|
-
throw new Error(
|
|
3173
|
-
"setupOTel: @opentelemetry/exporter-trace-otlp-http is required for OTLP export. Install it with: npm install @opentelemetry/exporter-trace-otlp-http"
|
|
3174
|
-
);
|
|
3175
|
-
}
|
|
3176
|
-
} else if (exporterType === "console") {
|
|
3177
|
-
const { ConsoleSpanExporter } = __require("@opentelemetry/sdk-trace-base");
|
|
3178
|
-
traceExporter = new ConsoleSpanExporter();
|
|
3179
|
-
}
|
|
3180
|
-
try {
|
|
3181
|
-
const { NodeSDK } = __require("@opentelemetry/sdk-node");
|
|
3182
|
-
const { resourceFromAttributes } = __require("@opentelemetry/resources");
|
|
3183
|
-
const { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } = __require("@opentelemetry/semantic-conventions");
|
|
3184
|
-
const resource = resourceFromAttributes({
|
|
3185
|
-
[ATTR_SERVICE_NAME]: serviceName,
|
|
3186
|
-
...options?.serviceVersion ? { [ATTR_SERVICE_VERSION]: options.serviceVersion } : {}
|
|
3187
|
-
});
|
|
3188
|
-
const sdk = new NodeSDK({
|
|
3189
|
-
resource,
|
|
3190
|
-
traceExporter
|
|
3191
|
-
});
|
|
3192
|
-
sdk.start();
|
|
3193
|
-
return async () => {
|
|
3194
|
-
await sdk.shutdown();
|
|
3195
|
-
};
|
|
3196
|
-
} catch {
|
|
3197
|
-
throw new Error(
|
|
3198
|
-
"setupOTel: @opentelemetry/sdk-node is required. Install it with: npm install @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/semantic-conventions"
|
|
3199
|
-
);
|
|
3200
|
-
}
|
|
3201
|
-
}
|
|
3202
|
-
|
|
3203
|
-
// libs/observability/src/otel/spans/pretty-span-exporter.ts
|
|
3204
|
-
import { SpanKind as SpanKind14, SpanStatusCode as SpanStatusCode5 } from "@opentelemetry/api";
|
|
3205
|
-
var RESET = "\x1B[0m";
|
|
3206
|
-
var DIM = "\x1B[2m";
|
|
3207
|
-
var BOLD = "\x1B[1m";
|
|
3208
|
-
var CYAN = "\x1B[36m";
|
|
3209
|
-
var GREEN = "\x1B[32m";
|
|
3210
|
-
var RED = "\x1B[31m";
|
|
3211
|
-
var YELLOW = "\x1B[33m";
|
|
3212
|
-
var KIND_LABELS = {
|
|
3213
|
-
[SpanKind14.INTERNAL]: "INTERNAL",
|
|
3214
|
-
[SpanKind14.SERVER]: "SERVER",
|
|
3215
|
-
[SpanKind14.CLIENT]: "CLIENT",
|
|
3216
|
-
[SpanKind14.PRODUCER]: "PRODUCER",
|
|
3217
|
-
[SpanKind14.CONSUMER]: "CONSUMER"
|
|
3218
|
-
};
|
|
3219
|
-
var SHOW_ATTRS = /* @__PURE__ */ new Set([
|
|
3220
|
-
"rpc.system",
|
|
3221
|
-
"rpc.method",
|
|
3222
|
-
"rpc.service",
|
|
3223
|
-
"mcp.method.name",
|
|
3224
|
-
"mcp.session.id",
|
|
3225
|
-
"mcp.component.type",
|
|
3226
|
-
"mcp.component.key",
|
|
3227
|
-
"http.request.method",
|
|
3228
|
-
"http.response.status_code",
|
|
3229
|
-
"url.path",
|
|
3230
|
-
"frontmcp.tool.name",
|
|
3231
|
-
"frontmcp.tool.owner",
|
|
3232
|
-
"frontmcp.transport.type",
|
|
3233
|
-
"frontmcp.transport.request_type",
|
|
3234
|
-
"frontmcp.auth.mode",
|
|
3235
|
-
"frontmcp.auth.result",
|
|
3236
|
-
"frontmcp.flow.name",
|
|
3237
|
-
"enduser.id"
|
|
3238
|
-
]);
|
|
3239
|
-
var PrettySpanExporter = class {
|
|
3240
|
-
constructor() {
|
|
3241
|
-
this.useAnsi = typeof process !== "undefined" && !!process.stdout?.isTTY;
|
|
3242
|
-
}
|
|
3243
|
-
export(spans, resultCallback) {
|
|
3244
|
-
for (const span of spans) {
|
|
3245
|
-
console.log(this.format(span));
|
|
3246
|
-
}
|
|
3247
|
-
resultCallback({ code: 0 });
|
|
3248
|
-
}
|
|
3249
|
-
shutdown() {
|
|
3250
|
-
return Promise.resolve();
|
|
3251
|
-
}
|
|
3252
|
-
format(span) {
|
|
3253
|
-
const traceShort = span.spanContext().traceId.slice(0, 8);
|
|
3254
|
-
const durationMs = (span.duration[0] * 1e3 + span.duration[1] / 1e6).toFixed(1);
|
|
3255
|
-
const kind = KIND_LABELS[span.kind] ?? "UNKNOWN";
|
|
3256
|
-
const statusOk = span.status.code !== SpanStatusCode5.ERROR;
|
|
3257
|
-
const attrs = Object.entries(span.attributes).filter(([k]) => SHOW_ATTRS.has(k)).map(([k, v]) => {
|
|
3258
|
-
const short = k.replace("frontmcp.", "").replace("mcp.", "");
|
|
3259
|
-
return `${short}=${v}`;
|
|
3260
|
-
}).join(" ");
|
|
3261
|
-
const eventCount = span.events.length;
|
|
3262
|
-
const eventSummary = eventCount > 0 ? ` (${eventCount} events)` : "";
|
|
3263
|
-
if (this.useAnsi) {
|
|
3264
|
-
const statusColor = statusOk ? GREEN : RED;
|
|
3265
|
-
const kindColor = span.kind === SpanKind14.SERVER ? CYAN : DIM;
|
|
3266
|
-
return [
|
|
3267
|
-
`${DIM}\u21B3${RESET}`,
|
|
3268
|
-
`${BOLD}${statusColor}SPAN${RESET}`,
|
|
3269
|
-
`${BOLD}${span.name}${RESET}`,
|
|
3270
|
-
`${DIM}[${traceShort}]${RESET}`,
|
|
3271
|
-
`${YELLOW}${durationMs}ms${RESET}`,
|
|
3272
|
-
`${kindColor}${kind}${RESET}`,
|
|
3273
|
-
attrs ? `${DIM}${attrs}${RESET}` : "",
|
|
3274
|
-
eventSummary ? `${DIM}${eventSummary}${RESET}` : ""
|
|
3275
|
-
].filter(Boolean).join(" ");
|
|
3276
|
-
}
|
|
3277
|
-
return ["\u21B3 SPAN", span.name, `[${traceShort}]`, `${durationMs}ms`, kind, attrs, eventSummary].filter(Boolean).join(" ");
|
|
3278
|
-
}
|
|
3279
|
-
};
|
|
3280
|
-
|
|
3281
|
-
// libs/observability/src/logging/sinks/index.ts
|
|
3282
|
-
init_winston_sink();
|
|
3283
|
-
init_pino_sink();
|
|
3284
|
-
init_otlp_sink();
|
|
3285
|
-
|
|
3286
|
-
// libs/observability/src/prometheus/render.ts
|
|
3287
|
-
var METRIC_NAME_REGEX = /^[a-zA-Z_:][a-zA-Z0-9_:]*$/;
|
|
3288
|
-
var LABEL_NAME_REGEX = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
|
|
3289
|
-
var PROMETHEUS_CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8";
|
|
3290
|
-
function escapeLabelValue(value) {
|
|
3291
|
-
return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
|
|
3292
|
-
}
|
|
3293
|
-
function sortedLabelString(attributes) {
|
|
3294
|
-
const keys = Object.keys(attributes).filter((k) => LABEL_NAME_REGEX.test(k)).sort();
|
|
3295
|
-
if (keys.length === 0) return "";
|
|
3296
|
-
const pairs = keys.map((k) => `${k}="${escapeLabelValue(attributes[k] ?? "")}"`);
|
|
3297
|
-
return `{${pairs.join(",")}}`;
|
|
3298
|
-
}
|
|
3299
|
-
function formatFloat(value) {
|
|
3300
|
-
if (!Number.isFinite(value)) return "";
|
|
3301
|
-
if (Number.isInteger(value)) return String(value);
|
|
3302
|
-
return String(value);
|
|
3303
|
-
}
|
|
3304
|
-
function renderPrometheusExposition(counters, gauges = [], options = {}) {
|
|
3305
|
-
const byName = /* @__PURE__ */ new Map();
|
|
3306
|
-
for (const entry of counters) {
|
|
3307
|
-
if (!METRIC_NAME_REGEX.test(entry.name)) continue;
|
|
3308
|
-
const valueStr = formatFloat(entry.count);
|
|
3309
|
-
if (valueStr === "") continue;
|
|
3310
|
-
const labels = sortedLabelString(entry.attributes ?? {});
|
|
3311
|
-
const line = `${entry.name}${labels} ${valueStr}`;
|
|
3312
|
-
let group = byName.get(entry.name);
|
|
3313
|
-
if (!group) {
|
|
3314
|
-
group = {
|
|
3315
|
-
type: "counter",
|
|
3316
|
-
help: options.counterHelp?.[entry.name],
|
|
3317
|
-
lines: []
|
|
3318
|
-
};
|
|
3319
|
-
byName.set(entry.name, group);
|
|
3320
|
-
}
|
|
3321
|
-
group.lines.push(line);
|
|
3322
|
-
}
|
|
3323
|
-
for (const entry of gauges) {
|
|
3324
|
-
if (!METRIC_NAME_REGEX.test(entry.name)) continue;
|
|
3325
|
-
const valueStr = formatFloat(entry.value);
|
|
3326
|
-
if (valueStr === "") continue;
|
|
3327
|
-
const labels = sortedLabelString(entry.attributes ?? {});
|
|
3328
|
-
const line = `${entry.name}${labels} ${valueStr}`;
|
|
3329
|
-
let group = byName.get(entry.name);
|
|
3330
|
-
if (!group) {
|
|
3331
|
-
group = { type: "gauge", help: entry.help, lines: [] };
|
|
3332
|
-
byName.set(entry.name, group);
|
|
3333
|
-
} else if (entry.help && !group.help) {
|
|
3334
|
-
group.help = entry.help;
|
|
3335
|
-
}
|
|
3336
|
-
group.lines.push(line);
|
|
3337
|
-
}
|
|
3338
|
-
if (byName.size === 0) return "";
|
|
3339
|
-
const sortedNames = Array.from(byName.keys()).sort();
|
|
3340
|
-
const blocks = [];
|
|
3341
|
-
for (const name of sortedNames) {
|
|
3342
|
-
const group = byName.get(name);
|
|
3343
|
-
if (!group) continue;
|
|
3344
|
-
const block = [];
|
|
3345
|
-
if (group.help) {
|
|
3346
|
-
block.push(`# HELP ${name} ${group.help.replace(/\n/g, " ")}`);
|
|
3347
|
-
}
|
|
3348
|
-
block.push(`# TYPE ${name} ${group.type}`);
|
|
3349
|
-
block.push(...group.lines.slice().sort());
|
|
3350
|
-
blocks.push(block.join("\n"));
|
|
3351
|
-
}
|
|
3352
|
-
return blocks.join("\n") + "\n";
|
|
3353
|
-
}
|
|
3354
|
-
function renderJsonExposition(counters, gauges = []) {
|
|
3355
|
-
return {
|
|
3356
|
-
counters: counters.filter((c) => METRIC_NAME_REGEX.test(c.name) && Number.isFinite(c.count)).map((c) => ({ name: c.name, count: c.count, attributes: { ...c.attributes ?? {} } })),
|
|
3357
|
-
gauges: gauges.filter((g) => METRIC_NAME_REGEX.test(g.name) && Number.isFinite(g.value)).map((g) => ({
|
|
3358
|
-
name: g.name,
|
|
3359
|
-
value: g.value,
|
|
3360
|
-
attributes: { ...g.attributes ?? {} },
|
|
3361
|
-
...g.help ? { help: g.help } : {}
|
|
3362
|
-
}))
|
|
3363
|
-
};
|
|
3364
|
-
}
|
|
3365
|
-
|
|
3366
|
-
// libs/observability/src/process-stats/process-stats.collector.ts
|
|
3367
|
-
import { readdirSync } from "@frontmcp/utils";
|
|
3368
|
-
var NS_PER_SECOND = 1e9;
|
|
3369
|
-
var MICROS_PER_SECOND = 1e6;
|
|
3370
|
-
function probeSafely(probe) {
|
|
3371
|
-
try {
|
|
3372
|
-
return probe();
|
|
3373
|
-
} catch {
|
|
3374
|
-
return void 0;
|
|
3375
|
-
}
|
|
3376
|
-
}
|
|
3377
|
-
function defaultMonitorEventLoopDelay() {
|
|
3378
|
-
try {
|
|
3379
|
-
const { monitorEventLoopDelay } = __require("node:perf_hooks");
|
|
3380
|
-
const histogram = monitorEventLoopDelay({ resolution: 10 });
|
|
3381
|
-
histogram.enable();
|
|
3382
|
-
return histogram;
|
|
3383
|
-
} catch {
|
|
3384
|
-
return void 0;
|
|
3385
|
-
}
|
|
3386
|
-
}
|
|
3387
|
-
function defaultGetActiveHandles() {
|
|
3388
|
-
const proc = process;
|
|
3389
|
-
if (typeof proc._getActiveHandles !== "function") return void 0;
|
|
3390
|
-
try {
|
|
3391
|
-
return proc._getActiveHandles();
|
|
3392
|
-
} catch {
|
|
3393
|
-
return void 0;
|
|
3394
|
-
}
|
|
3395
|
-
}
|
|
3396
|
-
function defaultGetActiveRequests() {
|
|
3397
|
-
const proc = process;
|
|
3398
|
-
if (typeof proc._getActiveRequests !== "function") return void 0;
|
|
3399
|
-
try {
|
|
3400
|
-
return proc._getActiveRequests();
|
|
3401
|
-
} catch {
|
|
3402
|
-
return void 0;
|
|
3403
|
-
}
|
|
3404
|
-
}
|
|
3405
|
-
function defaultReadFdCount() {
|
|
3406
|
-
if (process.platform !== "linux") return void 0;
|
|
3407
|
-
try {
|
|
3408
|
-
return readdirSync("/proc/self/fd").length;
|
|
3409
|
-
} catch {
|
|
3410
|
-
return void 0;
|
|
3411
|
-
}
|
|
3412
|
-
}
|
|
3413
|
-
var ProcessStatsCollector = class {
|
|
3414
|
-
constructor(init = {}) {
|
|
3415
|
-
this.options = init.options ?? {};
|
|
3416
|
-
this.cpuUsage = init.cpuUsage ?? ((prev) => process.cpuUsage(prev));
|
|
3417
|
-
this.memoryUsage = init.memoryUsage ?? (() => process.memoryUsage());
|
|
3418
|
-
this.uptime = init.uptime ?? (() => process.uptime());
|
|
3419
|
-
this.getActiveHandles = init.getActiveHandles ?? defaultGetActiveHandles;
|
|
3420
|
-
this.getActiveRequests = init.getActiveRequests ?? defaultGetActiveRequests;
|
|
3421
|
-
this.readFdCount = init.readFdCount ?? defaultReadFdCount;
|
|
3422
|
-
this.cpuStart = probeSafely(() => this.cpuUsage());
|
|
3423
|
-
if (this.options.eventLoopLag !== false) {
|
|
3424
|
-
this.histogram = init.monitorEventLoopDelay ? init.monitorEventLoopDelay() : defaultMonitorEventLoopDelay();
|
|
3425
|
-
}
|
|
3426
|
-
}
|
|
3427
|
-
collect() {
|
|
3428
|
-
const entries = [];
|
|
3429
|
-
this.cpuStart ??= probeSafely(() => this.cpuUsage());
|
|
3430
|
-
const cpu = this.cpuStart && probeSafely(() => this.cpuUsage(this.cpuStart));
|
|
3431
|
-
if (cpu) {
|
|
3432
|
-
entries.push({
|
|
3433
|
-
name: "frontmcp_process_cpu_seconds_total",
|
|
3434
|
-
value: cpu.user / MICROS_PER_SECOND,
|
|
3435
|
-
attributes: { mode: "user" },
|
|
3436
|
-
help: "CPU time consumed since collector start, by mode (seconds)"
|
|
3437
|
-
});
|
|
3438
|
-
entries.push({
|
|
3439
|
-
name: "frontmcp_process_cpu_seconds_total",
|
|
3440
|
-
value: cpu.system / MICROS_PER_SECOND,
|
|
3441
|
-
attributes: { mode: "system" }
|
|
3442
|
-
});
|
|
3443
|
-
}
|
|
3444
|
-
const mem = probeSafely(() => this.memoryUsage());
|
|
3445
|
-
if (mem && mem.rss > 0) {
|
|
3446
|
-
entries.push({
|
|
3447
|
-
name: "frontmcp_process_resident_memory_bytes",
|
|
3448
|
-
value: mem.rss,
|
|
3449
|
-
help: "Resident memory size in bytes"
|
|
3450
|
-
});
|
|
3451
|
-
entries.push({
|
|
3452
|
-
name: "frontmcp_process_heap_bytes",
|
|
3453
|
-
value: mem.heapTotal,
|
|
3454
|
-
help: "Total V8 heap size in bytes"
|
|
3455
|
-
});
|
|
3456
|
-
entries.push({
|
|
3457
|
-
name: "frontmcp_process_heap_used_bytes",
|
|
3458
|
-
value: mem.heapUsed,
|
|
3459
|
-
help: "Used V8 heap size in bytes"
|
|
3460
|
-
});
|
|
3461
|
-
entries.push({
|
|
3462
|
-
name: "frontmcp_process_external_bytes",
|
|
3463
|
-
value: mem.external,
|
|
3464
|
-
help: "Memory used by C++ objects bound to JS in bytes"
|
|
3465
|
-
});
|
|
3466
|
-
}
|
|
3467
|
-
const uptime = probeSafely(() => this.uptime());
|
|
3468
|
-
if (uptime !== void 0 && uptime > 0) {
|
|
3469
|
-
entries.push({
|
|
3470
|
-
name: "frontmcp_process_uptime_seconds",
|
|
3471
|
-
value: uptime,
|
|
3472
|
-
help: "Time since process start in seconds"
|
|
3473
|
-
});
|
|
3474
|
-
}
|
|
3475
|
-
const histogram = this.options.eventLoopLag !== false ? this.histogram : void 0;
|
|
3476
|
-
const lag = histogram && probeSafely(() => {
|
|
3477
|
-
const sample = {
|
|
3478
|
-
meanSeconds: histogram.mean / NS_PER_SECOND,
|
|
3479
|
-
p99Seconds: histogram.percentile(99) / NS_PER_SECOND
|
|
3480
|
-
};
|
|
3481
|
-
histogram.reset();
|
|
3482
|
-
return sample;
|
|
3483
|
-
});
|
|
3484
|
-
if (lag) {
|
|
3485
|
-
const { meanSeconds, p99Seconds } = lag;
|
|
3486
|
-
if (Number.isFinite(meanSeconds)) {
|
|
3487
|
-
entries.push({
|
|
3488
|
-
name: "frontmcp_nodejs_eventloop_lag_seconds",
|
|
3489
|
-
value: meanSeconds,
|
|
3490
|
-
attributes: { quantile: "mean" },
|
|
3491
|
-
help: "Event-loop lag in seconds, sampled at 10ms resolution since the last scrape"
|
|
3492
|
-
});
|
|
3493
|
-
}
|
|
3494
|
-
if (Number.isFinite(p99Seconds)) {
|
|
3495
|
-
entries.push({
|
|
3496
|
-
name: "frontmcp_nodejs_eventloop_lag_seconds",
|
|
3497
|
-
value: p99Seconds,
|
|
3498
|
-
attributes: { quantile: "p99" }
|
|
3499
|
-
});
|
|
3500
|
-
}
|
|
3501
|
-
}
|
|
3502
|
-
if (this.options.activeHandles !== false) {
|
|
3503
|
-
const handles = this.getActiveHandles?.();
|
|
3504
|
-
if (handles !== void 0) {
|
|
3505
|
-
entries.push({
|
|
3506
|
-
name: "frontmcp_nodejs_active_handles",
|
|
3507
|
-
value: handles.length,
|
|
3508
|
-
help: "Currently active libuv handles (sockets, timers, etc.)"
|
|
3509
|
-
});
|
|
3510
|
-
}
|
|
3511
|
-
const requests = this.getActiveRequests?.();
|
|
3512
|
-
if (requests !== void 0) {
|
|
3513
|
-
entries.push({
|
|
3514
|
-
name: "frontmcp_nodejs_active_requests",
|
|
3515
|
-
value: requests.length,
|
|
3516
|
-
help: "Currently active libuv requests (file I/O, DNS, etc.)"
|
|
3517
|
-
});
|
|
3518
|
-
}
|
|
3519
|
-
}
|
|
3520
|
-
if (this.options.fdCount !== false) {
|
|
3521
|
-
const fdCount = this.readFdCount();
|
|
3522
|
-
if (typeof fdCount === "number") {
|
|
3523
|
-
entries.push({
|
|
3524
|
-
name: "frontmcp_nodejs_open_fds",
|
|
3525
|
-
value: fdCount,
|
|
3526
|
-
help: "Number of open file descriptors (Linux only)"
|
|
3527
|
-
});
|
|
3528
|
-
}
|
|
3529
|
-
}
|
|
3530
|
-
return entries;
|
|
3531
|
-
}
|
|
3532
|
-
/**
|
|
3533
|
-
* Release the perf_hooks histogram listener. Call when the collector is
|
|
3534
|
-
* no longer used (e.g., when reconfiguring the server).
|
|
3535
|
-
*/
|
|
3536
|
-
close() {
|
|
3537
|
-
this.histogram?.disable?.();
|
|
3538
|
-
}
|
|
3539
|
-
};
|
|
3540
|
-
|
|
3541
|
-
// libs/observability/src/testing/index.ts
|
|
3542
|
-
function createTestTracer(name = "test") {
|
|
3543
|
-
const sdkTraceBase = __require("@opentelemetry/sdk-trace-base");
|
|
3544
|
-
const exporter = new sdkTraceBase.InMemorySpanExporter();
|
|
3545
|
-
const provider = new sdkTraceBase.BasicTracerProvider({
|
|
3546
|
-
spanProcessors: [new sdkTraceBase.SimpleSpanProcessor(exporter)]
|
|
3547
|
-
});
|
|
3548
|
-
const tracer = provider.getTracer(name);
|
|
3549
|
-
return {
|
|
3550
|
-
tracer,
|
|
3551
|
-
exporter,
|
|
3552
|
-
provider,
|
|
3553
|
-
cleanup: async () => {
|
|
3554
|
-
exporter.reset();
|
|
3555
|
-
await provider.forceFlush();
|
|
3556
|
-
await provider.shutdown();
|
|
3557
|
-
}
|
|
3558
|
-
};
|
|
3559
|
-
}
|
|
3560
|
-
function getFinishedSpans(exporter) {
|
|
3561
|
-
return exporter.getFinishedSpans();
|
|
3562
|
-
}
|
|
3563
|
-
function assertSpanExists(spans, name) {
|
|
3564
|
-
const match = spans.find((s) => s.name === name);
|
|
3565
|
-
if (!match) {
|
|
3566
|
-
const names = spans.map((s) => s.name).join(", ");
|
|
3567
|
-
throw new Error(`Expected span "${name}" but found: [${names}]`);
|
|
3568
|
-
}
|
|
3569
|
-
return match;
|
|
3570
|
-
}
|
|
3571
|
-
function assertSpanAttribute(span, key, value) {
|
|
3572
|
-
const actual = span.attributes[key];
|
|
3573
|
-
if (actual !== value) {
|
|
3574
|
-
throw new Error(
|
|
3575
|
-
`Expected span "${span.name}" attribute "${key}" to be ${JSON.stringify(value)} but got ${JSON.stringify(actual)}`
|
|
3576
|
-
);
|
|
3577
|
-
}
|
|
3578
|
-
}
|
|
3579
|
-
function findSpan(spans, name) {
|
|
3580
|
-
return spans.find((s) => s.name === name);
|
|
3581
|
-
}
|
|
3582
|
-
function findSpansByAttribute(spans, key, value) {
|
|
3583
|
-
return spans.filter((s) => s.attributes[key] === value);
|
|
3584
|
-
}
|
|
3585
|
-
export {
|
|
3586
|
-
CallbackSink,
|
|
3587
|
-
ConsoleSink,
|
|
3588
|
-
EnduserAttributes,
|
|
3589
|
-
FrontMcpAttributes,
|
|
3590
|
-
FrontMcpPropagator,
|
|
3591
|
-
HttpAttributes,
|
|
3592
|
-
KNOWN_BUNDLE_SOURCES,
|
|
3593
|
-
KNOWN_ERROR_REASONS,
|
|
3594
|
-
LOG_LEVEL_TO_OTEL_SEVERITY,
|
|
3595
|
-
McpAttributes,
|
|
3596
|
-
OTEL_CONFIG,
|
|
3597
|
-
OTEL_TRACER,
|
|
3598
|
-
ObservabilityPlugin,
|
|
3599
|
-
OtlpSink,
|
|
3600
|
-
PROMETHEUS_CONTENT_TYPE,
|
|
3601
|
-
PinoSink,
|
|
3602
|
-
PrettySpanExporter,
|
|
3603
|
-
ProcessStatsCollector,
|
|
3604
|
-
REQUEST_LOG_COLLECTOR,
|
|
3605
|
-
RequestLogCollector,
|
|
3606
|
-
RpcAttributes,
|
|
3607
|
-
StdoutSink,
|
|
3608
|
-
StructuredLogTransport,
|
|
3609
|
-
TELEMETRY_ACCESSOR,
|
|
3610
|
-
TELEMETRY_FACTORY,
|
|
3611
|
-
TelemetryAccessor,
|
|
3612
|
-
TelemetryFactory,
|
|
3613
|
-
TelemetrySpan,
|
|
3614
|
-
WinstonSink,
|
|
3615
|
-
assertSpanAttribute,
|
|
3616
|
-
assertSpanExists,
|
|
3617
|
-
createCounter,
|
|
3618
|
-
createOTelContextFromTrace,
|
|
3619
|
-
createSink,
|
|
3620
|
-
createSinks,
|
|
3621
|
-
createTestTracer,
|
|
3622
|
-
emitStartupReport,
|
|
3623
|
-
endSpanError,
|
|
3624
|
-
endSpanOk,
|
|
3625
|
-
findSpan,
|
|
3626
|
-
findSpansByAttribute,
|
|
3627
|
-
frontmcpToOTelSpanContext,
|
|
3628
|
-
getCounterTotal,
|
|
3629
|
-
getFinishedSpans,
|
|
3630
|
-
getMetricSnapshot,
|
|
3631
|
-
normalizeBundleSource,
|
|
3632
|
-
normalizeErrorReason,
|
|
3633
|
-
otelToFrontmcpContext,
|
|
3634
|
-
recordHookEvent,
|
|
3635
|
-
redactFields,
|
|
3636
|
-
renderJsonExposition,
|
|
3637
|
-
renderPrometheusExposition,
|
|
3638
|
-
reportStartup,
|
|
3639
|
-
resetCounterCacheForTesting,
|
|
3640
|
-
resetMetricSnapshot,
|
|
3641
|
-
resetTelemetrySnapshotForTesting,
|
|
3642
|
-
sessionTracingId,
|
|
3643
|
-
setAuthMode,
|
|
3644
|
-
setAuthResult,
|
|
3645
|
-
setFetchResponseStatus,
|
|
3646
|
-
setHttpResponseStatus,
|
|
3647
|
-
setTransportRequestType,
|
|
3648
|
-
setupOTel,
|
|
3649
|
-
startAuthSpan,
|
|
3650
|
-
startFetchSpan,
|
|
3651
|
-
startHookSpan,
|
|
3652
|
-
startHttpServerSpan,
|
|
3653
|
-
startPromptSpan,
|
|
3654
|
-
startResourceSpan,
|
|
3655
|
-
startRpcSpan,
|
|
3656
|
-
startSpan,
|
|
3657
|
-
startToolSpan,
|
|
3658
|
-
startTransportSpan,
|
|
3659
|
-
withSpan
|
|
3660
|
-
};
|
|
4
|
+
var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __esm=(fn,res,err)=>function __init(){if(err)throw err[0];try{return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res}catch(e){throw err=[e],e}};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var __decorateClass=(decorators,target,key,kind)=>{var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target;for(var i=decorators.length-1,decorator;i>=0;i--)if(decorator=decorators[i])result=(kind?decorator(target,key,result):decorator(result))||result;if(kind&&result)__defProp(target,key,result);return result};var winston_sink_exports={};__export(winston_sink_exports,{WinstonSink:()=>WinstonSink});function mapToWinstonLevel(level){switch(level){case"debug":case"verbose":return"debug";case"info":return"info";case"warn":return"warn";case"error":return"error";default:return"info"}}var WinstonSink;var init_winston_sink=__esm({"libs/observability/src/logging/sinks/winston.sink.ts"(){"use strict";WinstonSink=class{constructor(logger){this.logger=logger}write(entry){const{message,level,...meta}=entry;const winstonLevel=mapToWinstonLevel(level);switch(winstonLevel){case"debug":this.logger.debug(message,meta);break;case"info":this.logger.info(message,meta);break;case"warn":this.logger.warn(message,meta);break;case"error":this.logger.error(message,meta);break}}}}});var pino_sink_exports={};__export(pino_sink_exports,{PinoSink:()=>PinoSink});function mapToPinoLevel(level){switch(level){case"debug":case"verbose":return"debug";case"info":return"info";case"warn":return"warn";case"error":return"error";default:return"info"}}var PinoSink;var init_pino_sink=__esm({"libs/observability/src/logging/sinks/pino.sink.ts"(){"use strict";PinoSink=class{constructor(logger){this.logger=logger}write(entry){const{message,level,...obj}=entry;const pinoLevel=mapToPinoLevel(level);switch(pinoLevel){case"debug":this.logger.debug(obj,message);break;case"info":this.logger.info(obj,message);break;case"warn":this.logger.warn(obj,message);break;case"error":this.logger.error(obj,message);break}}}}});var otlp_sink_exports={};__export(otlp_sink_exports,{OtlpSink:()=>OtlpSink});var OtlpSink;var init_otlp_sink=__esm({"libs/observability/src/logging/sinks/otlp.sink.ts"(){"use strict";OtlpSink=class{constructor(options){this.batch=[];let base=options.endpoint;while(base.endsWith("/")){base=base.slice(0,-1)}this.endpoint=`${base}/v1/logs`;this.headers={"Content-Type":"application/json",...options.headers??{}};this.batchSize=options.batchSize??100;this.maxQueueSize=options.maxQueueSize??5e3;this.serviceName=options.serviceName??(typeof process!=="undefined"?process.env?.["OTEL_SERVICE_NAME"]:void 0)??"frontmcp-server";const flushMs=options.flushIntervalMs??5e3;if(flushMs>0){this.flushTimer=setInterval(()=>{void this.flush()},flushMs);if(this.flushTimer&&typeof this.flushTimer==="object"&&"unref"in this.flushTimer){this.flushTimer.unref()}}}write(entry){this.batch.push(entry);this.enforceCapacity();if(this.batch.length>=this.batchSize){void this.flush()}}async flush(){if(this.batch.length===0)return;const entries=this.batch.splice(0);const payload=this.buildOtlpPayload(entries);try{const controller=new AbortController;const timeout=setTimeout(()=>controller.abort(),1e4);try{const response=await fetch(this.endpoint,{method:"POST",headers:this.headers,body:JSON.stringify(payload),signal:controller.signal});clearTimeout(timeout);if(!response.ok){const body=await response.text().catch(()=>"");console.error(`[OtlpSink] Export failed: HTTP ${response.status} \u2014 ${body.slice(0,200)}`);this.requeue(entries)}}catch(err){clearTimeout(timeout);console.debug(`[OtlpSink] Export error (${entries.length} entries): ${err instanceof Error?err.message:err}`);this.requeue(entries)}}catch{}}requeue(entries){this.batch.unshift(...entries);this.enforceCapacity()}enforceCapacity(){if(this.batch.length>this.maxQueueSize){this.batch.splice(0,this.batch.length-this.maxQueueSize)}}async close(){if(this.flushTimer){clearInterval(this.flushTimer);this.flushTimer=void 0}await this.flush()}buildOtlpPayload(entries){return{resourceLogs:[{resource:{attributes:[{key:"service.name",value:{stringValue:this.serviceName}}]},scopeLogs:[{scope:{name:"@frontmcp/observability"},logRecords:entries.map(entry=>this.entryToLogRecord(entry))}]}]}}entryToLogRecord(entry){const attrs=[];const record={timeUnixNano:String(new Date(entry.timestamp).getTime()*1e6),severityNumber:entry.severity_number,severityText:entry.level.toUpperCase(),body:{stringValue:entry.message},attributes:attrs};if(entry.trace_id){record.traceId=entry.trace_id}if(entry.span_id){record.spanId=entry.span_id}if(entry.trace_flags!==void 0){record.flags=entry.trace_flags}if(entry.request_id){attrs.push({key:"frontmcp.request.id",value:{stringValue:entry.request_id}})}if(entry.session_id_hash){attrs.push({key:"mcp.session.id",value:{stringValue:entry.session_id_hash}})}if(entry.scope_id){attrs.push({key:"frontmcp.scope.id",value:{stringValue:entry.scope_id}})}if(entry.flow_name){attrs.push({key:"frontmcp.flow.name",value:{stringValue:entry.flow_name}})}if(entry.prefix){attrs.push({key:"log.prefix",value:{stringValue:entry.prefix}})}if(entry.elapsed_ms!==void 0){attrs.push({key:"elapsed_ms",value:Number.isInteger(entry.elapsed_ms)?{intValue:String(entry.elapsed_ms)}:{doubleValue:entry.elapsed_ms}})}if(entry.error){attrs.push({key:"error.type",value:{stringValue:entry.error.type}});attrs.push({key:"error.message",value:{stringValue:entry.error.message}});if(entry.error.code){attrs.push({key:"error.code",value:{stringValue:entry.error.code}})}if(entry.error.error_id){attrs.push({key:"error.id",value:{stringValue:entry.error.error_id}})}if(entry.error.stack){attrs.push({key:"error.stack",value:{stringValue:entry.error.stack}})}}if(entry.attributes){for(const[key,value]of Object.entries(entry.attributes)){if(value==null)continue;if(typeof value==="string"){attrs.push({key,value:{stringValue:value}})}else if(typeof value==="number"){attrs.push({key,value:Number.isInteger(value)?{intValue:String(value)}:{doubleValue:value}})}else if(typeof value==="boolean"){attrs.push({key,value:{boolValue:value}})}else{attrs.push({key,value:{stringValue:JSON.stringify(value)}})}}}return record}}}});import{trace as trace6}from"@opentelemetry/api";import{AgentCallHook,DynamicPlugin,FlowHooksOf,FRONTMCP_CONTEXT as FRONTMCP_CONTEXT2,HttpHook,ListResourcesHook,ListResourceTemplatesHook,ListToolsHook,Plugin,ProviderScope,ResourceHook,ToolHook}from"@frontmcp/sdk";function defaultStream(){const flag=typeof process!=="undefined"?process.env?.["FRONTMCP_STDIO"]:void 0;return flag==="1"||flag==="true"?process.stderr:process.stdout}var StdoutSink=class{constructor(options){this.stream=options?.stream??defaultStream();this.pretty=options?.pretty??false}write(entry){const line=this.pretty?JSON.stringify(entry,null,2):JSON.stringify(entry);this.stream.write(line+"\n")}};var ConsoleSink=class{write(entry){const method=levelToConsoleMethod(entry.level);const formatted=formatEntry(entry);method(formatted)}};function formatEntry(entry){const useAnsi=typeof process!=="undefined"&&!!process.stdout?.isTTY;const ts=entry.timestamp.slice(11,23);const level=entry.level.toUpperCase().padEnd(7);const traceShort=entry.trace_id?entry.trace_id.slice(0,8):"";const reqShort=entry.request_id?entry.request_id.slice(0,8):"";const parts=[];const DIM2=useAnsi?"\x1B[2m":"";const BOLD2=useAnsi?"\x1B[1m":"";const RESET2=useAnsi?"\x1B[0m":"";const levelColor=useAnsi?LEVEL_COLORS[entry.level]??"":"";parts.push(`${DIM2}[${ts}]${RESET2}`);parts.push(`${BOLD2}${levelColor}${level}${RESET2}`);if(traceShort||reqShort){parts.push(`${DIM2}[${traceShort}${reqShort?":"+reqShort:""}]${RESET2}`)}if(entry.prefix)parts.push(`${DIM2}[${entry.prefix}]${RESET2}`);parts.push(entry.message);if(entry.attributes&&Object.keys(entry.attributes).length>0){const attrs=Object.entries(entry.attributes).map(([k,v])=>`${k}=${typeof v==="string"?v:JSON.stringify(v)}`).join(" ");parts.push(`${DIM2}{ ${attrs} }${RESET2}`)}if(entry.error){parts.push(`[${entry.error.type}: ${entry.error.message}]`)}if(entry.elapsed_ms!==void 0){parts.push(`${DIM2}(${entry.elapsed_ms}ms)${RESET2}`)}return parts.join(" ")}var LEVEL_COLORS={debug:"\x1B[34m",verbose:"\x1B[90m",info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"};function levelToConsoleMethod(level){switch(level){case"debug":case"verbose":return console.debug;case"info":return console.info;case"warn":return console.warn;case"error":return console.error;default:return console.log}}var CallbackSink=class{constructor(fn){this.fn=fn}write(entry){this.fn(entry)}};function createSink(config){switch(config.type){case"stdout":return new StdoutSink({stream:config.stream,pretty:config.pretty});case"console":return new ConsoleSink;case"winston":{const{WinstonSink:WinstonSink2}=(init_winston_sink(),__toCommonJS(winston_sink_exports));return new WinstonSink2(config.logger)}case"pino":{const{PinoSink:PinoSink2}=(init_pino_sink(),__toCommonJS(pino_sink_exports));return new PinoSink2(config.logger)}case"callback":return new CallbackSink(config.fn);case"otlp":{const{OtlpSink:OtlpSink2}=(init_otlp_sink(),__toCommonJS(otlp_sink_exports));return new OtlpSink2({endpoint:config.endpoint??(typeof process!=="undefined"?process.env?.["OTEL_EXPORTER_OTLP_ENDPOINT"]:void 0)??"http://localhost:4318",headers:config.headers,batchSize:config.batchSize,flushIntervalMs:config.flushIntervalMs,serviceName:config.serviceName})}default:throw new Error(`Unknown sink type: ${config.type}`)}}function createSinks(configs){if(configs&&configs.length>0){return configs.map(createSink)}return[]}import{LogTransportInterface,LogLevelName,LogTransport}from"@frontmcp/sdk";var LOG_LEVEL_TO_OTEL_SEVERITY={debug:5,verbose:6,info:9,warn:13,error:17};var REDACTED="[REDACTED]";function redactFields(obj,fields,maxDepth=5){if(fields.length===0)return obj;const lowerFields=new Set(fields.map(f=>f.toLowerCase()));return redactRecursive(obj,lowerFields,0,maxDepth)}function redactRecursive(obj,fields,depth,maxDepth){if(depth>=maxDepth)return obj;const result={};for(const[key,value]of Object.entries(obj)){if(fields.has(key.toLowerCase())){result[key]=REDACTED}else if(isPlainObject(value)){result[key]=redactRecursive(value,fields,depth+1,maxDepth)}else if(Array.isArray(value)){result[key]=value.map(item=>isPlainObject(item)?redactRecursive(item,fields,depth+1,maxDepth):item)}else{result[key]=value}}return result}function isPlainObject(value){if(typeof value!=="object"||value===null)return false;const proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null}var StructuredLogTransport=class extends LogTransportInterface{constructor(sinks,options,contextAccessor){super();this.sinks=sinks;this.redactFieldNames=options?.redactFields??[];this.includeStacks=options?.includeStacks??true;this.staticFields=options?.staticFields??{};this.getContext=contextAccessor}log(rec){const entry=this.buildEntry(rec);if(this.onEntry){try{this.onEntry(entry)}catch{}}for(const sink of this.sinks){try{sink.write(entry)}catch{}}}buildEntry(rec){const levelName=LogLevelName[rec.level]??"info";const entry={...this.staticFields,timestamp:rec.timestamp.toISOString(),level:levelName,severity_number:LOG_LEVEL_TO_OTEL_SEVERITY[levelName]??9,message:String(rec.message)};if(rec.prefix){entry.prefix=rec.prefix}const ctx=this.getContext?.();if(ctx){entry.trace_id=ctx.traceContext.traceId;entry.span_id=ctx.traceContext.parentId;entry.trace_flags=ctx.traceContext.traceFlags;entry.request_id=ctx.requestId;entry.session_id_hash=ctx.sessionIdHash;entry.scope_id=ctx.scopeId;if(ctx.flowName){entry.flow_name=ctx.flowName}entry.elapsed_ms=ctx.elapsed}this.processArgs(rec.args,entry);return entry}processArgs(args,entry){const attributes={};let hasAttributes=false;for(const arg of args){if(arg instanceof Error){entry.error=this.buildError(arg)}else if(typeof arg==="object"&&arg!==null&&!Array.isArray(arg)){const obj=arg;const redacted=this.redactFieldNames.length>0?redactFields(obj,this.redactFieldNames):obj;Object.assign(attributes,redacted);hasAttributes=true}}if(hasAttributes){entry.attributes=attributes}}buildError(err){const result={type:err.constructor.name,message:err.message};if("code"in err&&typeof err.code==="number"){result.code=String(err.code)}if("errorId"in err&&typeof err.errorId==="string"){result.error_id=err.errorId}if(this.includeStacks&&err.stack){result.stack=err.stack}return result}};StructuredLogTransport=__decorateClass([LogTransport({name:"StructuredLogTransport",description:"Produces structured log objects and forwards to configurable sinks"})],StructuredLogTransport);var OTEL_TRACER=Symbol.for("frontmcp:observability:otel-tracer");var OTEL_CONFIG=Symbol.for("frontmcp:observability:otel-config");var RequestLogCollector=class{constructor(context,options){this.entries=[];this.hooksTriggered=new Set;this.authenticated=false;this.status="ok";this.finalized=false;this.requestId=context.requestId;this.traceId=context.traceId;this.sessionIdHash=context.sessionIdHash;this.scopeId=context.scopeId;this.startTime=new Date;this.maxEntries=options?.maxEntries??500;this.onComplete=options?.onRequestComplete}addEntry(entry){if(this.finalized||this.entries.length>=this.maxEntries)return;const logEntry={timestamp:entry.timestamp,level:entry.level,message:entry.message};if(entry.flow_name){logEntry.stage=entry.flow_name}if(entry.elapsed_ms!==void 0){logEntry.elapsed_ms=entry.elapsed_ms}if(entry.attributes&&Object.keys(entry.attributes).length>0){logEntry.attributes=entry.attributes}this.entries.push(logEntry)}addHook(stage){this.hooksTriggered.add(stage)}setHttpInfo(method,path){this.httpMethod=method;this.httpPath=path}setRpcMethod(method){this.rpcMethod=method}setToolName(name){this.toolName=name}setResourceUri(uri){this.resourceUri=uri}setPromptName(name){this.promptName=name}setAuthInfo(type,authenticated){this.authType=type;this.authenticated=authenticated}setStatus(status,statusCode){this.status=status;this.statusCode=statusCode}setStatusCode(statusCode){this.statusCode=statusCode;if(statusCode>=400)this.status="error"}setError(error){this.error=error;this.status="error"}async finalize(){if(this.finalized){return this.finalizedLog}this.finalized=true;const log=this.toRequestLog();this.finalizedLog=log;if(this.onComplete){try{await this.onComplete(log)}catch{}}return log}toRequestLog(){const endTime=new Date;return{request_id:this.requestId,trace_id:this.traceId,session_id_hash:this.sessionIdHash,scope_id:this.scopeId,start_time:this.startTime.toISOString(),end_time:endTime.toISOString(),duration_ms:endTime.getTime()-this.startTime.getTime(),http_method:this.httpMethod,http_path:this.httpPath,rpc_method:this.rpcMethod,tool_name:this.toolName,resource_uri:this.resourceUri,prompt_name:this.promptName,auth_type:this.authType,authenticated:this.authenticated,status:this.status,status_code:this.statusCode,error:this.error,hooks_triggered:Array.from(this.hooksTriggered),entries:[...this.entries]}}isFinalized(){return this.finalized}getEntryCount(){return this.entries.length}};import{isAnonymousSubject}from"@frontmcp/sdk";import{context as otelContext3,SpanKind as SpanKind12,SpanStatusCode as SpanStatusCode2,trace as trace3}from"@opentelemetry/api";import{FlowControl,InternalMcpError,toMcpError}from"@frontmcp/sdk";import{sha256Hex}from"@frontmcp/utils";var McpAttributes={METHOD_NAME:"mcp.method.name",SESSION_ID:"mcp.session.id",RESOURCE_URI:"mcp.resource.uri",COMPONENT_TYPE:"mcp.component.type",COMPONENT_KEY:"mcp.component.key"};var FrontMcpAttributes={SCOPE_ID:"frontmcp.scope.id",SERVER_NAME:"frontmcp.server.name",TOOL_NAME:"frontmcp.tool.name",TOOL_OWNER:"frontmcp.tool.owner",RESOURCE_URI:"frontmcp.resource.uri",RESOURCE_NAME:"frontmcp.resource.name",PROMPT_NAME:"frontmcp.prompt.name",FLOW_NAME:"frontmcp.flow.name",FLOW_STAGE:"frontmcp.flow.stage",HOOK_STAGE:"frontmcp.hook.stage",HOOK_OWNER:"frontmcp.hook.owner",SESSION_ID_HASH:"frontmcp.session.id_hash",AUTH_TYPE:"frontmcp.auth.type",REQUEST_ID:"frontmcp.request.id",PROVIDER_TYPE:"frontmcp.provider.type",DELEGATE_ORIGINAL_NAME:"frontmcp.delegate.original_name",TRANSPORT_TYPE:"frontmcp.transport.type",TRANSPORT_REQUEST_TYPE:"frontmcp.transport.request_type",SESSION_PROTOCOL:"frontmcp.session.protocol",SESSION_CREATED:"frontmcp.session.created",AUTH_MODE:"frontmcp.auth.mode",AUTH_RESULT:"frontmcp.auth.result",OAUTH_GRANT_TYPE:"frontmcp.oauth.grant_type",ELICITATION_ID:"frontmcp.elicitation.id",AGENT_NAME:"frontmcp.agent.name",AGENT_ITERATIONS:"frontmcp.agent.iterations",AGENT_EXECUTION_DURATION_MS:"frontmcp.agent.execution_duration_ms",STARTUP_TOOLS_COUNT:"frontmcp.startup.tools_count",STARTUP_RESOURCES_COUNT:"frontmcp.startup.resources_count",STARTUP_PROMPTS_COUNT:"frontmcp.startup.prompts_count",STARTUP_PLUGINS_COUNT:"frontmcp.startup.plugins_count",STARTUP_DURATION_MS:"frontmcp.startup.duration_ms"};var HttpAttributes={METHOD:"http.request.method",STATUS_CODE:"http.response.status_code",URL_PATH:"url.path",URL_FULL:"url.full",URL_SCHEME:"url.scheme",SERVER_ADDRESS:"server.address",SERVER_PORT:"server.port"};var RpcAttributes={SYSTEM:"rpc.system",SERVICE:"rpc.service",METHOD:"rpc.method",JSONRPC_VERSION:"rpc.jsonrpc.version",JSONRPC_REQUEST_ID:"rpc.jsonrpc.request_id"};var EnduserAttributes={ID:"enduser.id",SCOPE:"enduser.scope"};import{SpanKind as SpanKind2}from"@opentelemetry/api";import{SpanKind,SpanStatusCode,context as otelContext,trace}from"@opentelemetry/api";function startSpan(tracer,options){const parentCtx=options.parentContext??otelContext.active();const span=tracer.startSpan(options.name,{kind:options.kind??SpanKind.INTERNAL,attributes:options.attributes},parentCtx);const spanContext=trace.setSpan(parentCtx,span);return{span,context:spanContext}}function endSpanOk(span){span.setStatus({code:SpanStatusCode.OK});span.end()}function endSpanError(span,error){const message=typeof error==="string"?error:error.message;span.setStatus({code:SpanStatusCode.ERROR,message});if(error instanceof Error){span.recordException(error)}span.end()}async function withSpan(tracer,options,fn){const{span,context:spanContext}=startSpan(tracer,options);return otelContext.with(spanContext,async()=>{try{const result=await fn(span);endSpanOk(span);return result}catch(err){endSpanError(span,err instanceof Error?err:String(err));throw err}})}function startAuthSpan(tracer,options){return startSpan(tracer,{name:`auth ${options.flowName}`,kind:SpanKind2.INTERNAL,attributes:{[FrontMcpAttributes.FLOW_NAME]:options.flowName},parentContext:options.parentContext})}function setAuthMode(span,mode){span.setAttribute(FrontMcpAttributes.AUTH_MODE,mode)}function setAuthResult(span,result){span.setAttribute(FrontMcpAttributes.AUTH_RESULT,result)}import{SpanKind as SpanKind3}from"@opentelemetry/api";function startFetchSpan(tracer,options){return startSpan(tracer,{name:options.method.toUpperCase(),kind:SpanKind3.CLIENT,attributes:{[HttpAttributes.METHOD]:options.method.toUpperCase(),[HttpAttributes.URL_FULL]:options.url},parentContext:options.parentContext})}function setFetchResponseStatus(span,statusCode){span.setAttribute(HttpAttributes.STATUS_CODE,statusCode)}import{SpanKind as SpanKind4}from"@opentelemetry/api";function recordHookEvent(parentSpan,stage,owner){const attributes={};if(owner){attributes[FrontMcpAttributes.HOOK_OWNER]=owner}parentSpan.addEvent(`hook.${stage}`,attributes)}function startHookSpan(tracer,options){const attributes={[FrontMcpAttributes.HOOK_STAGE]:options.stage};if(options.owner){attributes[FrontMcpAttributes.HOOK_OWNER]=options.owner}if(options.flowName){attributes[FrontMcpAttributes.FLOW_NAME]=options.flowName}return startSpan(tracer,{name:`hook ${options.stage}`,kind:SpanKind4.INTERNAL,attributes,parentContext:options.parentContext})}import{SpanKind as SpanKind5}from"@opentelemetry/api";function startHttpServerSpan(tracer,options){const attributes={[HttpAttributes.METHOD]:options.method.toUpperCase(),[HttpAttributes.URL_PATH]:options.path};if(options.scheme){attributes[HttpAttributes.URL_SCHEME]=options.scheme}if(options.serverAddress){attributes[HttpAttributes.SERVER_ADDRESS]=options.serverAddress}if(options.serverPort){attributes[HttpAttributes.SERVER_PORT]=options.serverPort}if(options.scopeId){attributes[FrontMcpAttributes.SCOPE_ID]=options.scopeId}if(options.requestId){attributes[FrontMcpAttributes.REQUEST_ID]=options.requestId}return startSpan(tracer,{name:`${options.method.toUpperCase()} ${options.path}`,kind:SpanKind5.SERVER,attributes,parentContext:options.parentContext})}function setHttpResponseStatus(span,statusCode){span.setAttribute(HttpAttributes.STATUS_CODE,statusCode)}import{SpanKind as SpanKind6}from"@opentelemetry/api";function startPromptSpan(tracer,options){return startSpan(tracer,{name:`prompt ${options.name}`,kind:SpanKind6.INTERNAL,attributes:{[FrontMcpAttributes.PROMPT_NAME]:options.name,[McpAttributes.COMPONENT_TYPE]:"prompt",[McpAttributes.COMPONENT_KEY]:`prompt:${options.name}`},parentContext:options.parentContext})}import{SpanKind as SpanKind7}from"@opentelemetry/api";function startResourceSpan(tracer,options){const attributes={[FrontMcpAttributes.RESOURCE_URI]:options.uri,[McpAttributes.RESOURCE_URI]:options.uri,[McpAttributes.COMPONENT_TYPE]:"resource",[McpAttributes.COMPONENT_KEY]:`resource:${options.uri}`};if(options.name){attributes[FrontMcpAttributes.RESOURCE_NAME]=options.name}return startSpan(tracer,{name:`resource ${options.uri}`,kind:SpanKind7.INTERNAL,attributes,parentContext:options.parentContext})}import{SpanKind as SpanKind8}from"@opentelemetry/api";function startRpcSpan(tracer,options){const attributes={[RpcAttributes.SYSTEM]:"mcp",[RpcAttributes.METHOD]:options.method,[RpcAttributes.JSONRPC_VERSION]:"2.0",[McpAttributes.METHOD_NAME]:options.method};if(options.requestId!==void 0){attributes[RpcAttributes.JSONRPC_REQUEST_ID]=String(options.requestId)}if(options.scopeId){attributes[FrontMcpAttributes.SCOPE_ID]=options.scopeId}if(options.serviceName){attributes[RpcAttributes.SERVICE]=options.serviceName;attributes[FrontMcpAttributes.SERVER_NAME]=options.serviceName}if(options.sessionIdHash){attributes[McpAttributes.SESSION_ID]=options.sessionIdHash;attributes[FrontMcpAttributes.SESSION_ID_HASH]=options.sessionIdHash}return startSpan(tracer,{name:options.method,kind:SpanKind8.SERVER,attributes,parentContext:options.parentContext})}import{SpanKind as SpanKind9}from"@opentelemetry/api";function emitStartupReport(tracer,data){const attributes={[FrontMcpAttributes.STARTUP_TOOLS_COUNT]:data.toolsCount,[FrontMcpAttributes.STARTUP_RESOURCES_COUNT]:data.resourcesCount,[FrontMcpAttributes.STARTUP_PROMPTS_COUNT]:data.promptsCount,[FrontMcpAttributes.STARTUP_PLUGINS_COUNT]:data.pluginsCount,[FrontMcpAttributes.STARTUP_DURATION_MS]:data.durationMs};if(data.scopeId){attributes[FrontMcpAttributes.SCOPE_ID]=data.scopeId}const{span}=startSpan(tracer,{name:"frontmcp.startup",kind:SpanKind9.INTERNAL,attributes});endSpanOk(span)}import{SpanKind as SpanKind10}from"@opentelemetry/api";function startToolSpan(tracer,options){const attributes={[FrontMcpAttributes.TOOL_NAME]:options.name,[McpAttributes.COMPONENT_TYPE]:"tool",[McpAttributes.COMPONENT_KEY]:`tool:${options.name}`};if(options.owner){attributes[FrontMcpAttributes.TOOL_OWNER]=options.owner}if(options.enduserId){attributes[EnduserAttributes.ID]=options.enduserId}if(options.enduserScope){attributes[EnduserAttributes.SCOPE]=options.enduserScope}return startSpan(tracer,{name:`tool ${options.name}`,kind:SpanKind10.INTERNAL,attributes,parentContext:options.parentContext})}import{SpanKind as SpanKind11}from"@opentelemetry/api";function startTransportSpan(tracer,options){const attributes={[FrontMcpAttributes.TRANSPORT_TYPE]:options.type};if(options.sessionIdHash){attributes[FrontMcpAttributes.SESSION_ID_HASH]=options.sessionIdHash}if(options.sessionCreated!==void 0){attributes[FrontMcpAttributes.SESSION_CREATED]=options.sessionCreated}return startSpan(tracer,{name:`transport ${options.type}`,kind:SpanKind11.INTERNAL,attributes,parentContext:options.parentContext})}function setTransportRequestType(span,requestType){span.setAttribute(FrontMcpAttributes.TRANSPORT_REQUEST_TYPE,requestType)}import{TraceFlags,trace as trace2,context as otelContext2}from"@opentelemetry/api";function frontmcpToOTelSpanContext(tc){return{traceId:tc.traceId,spanId:tc.parentId,traceFlags:tc.traceFlags&TraceFlags.SAMPLED?TraceFlags.SAMPLED:TraceFlags.NONE,isRemote:true}}function otelToFrontmcpContext(sc){const flags=sc.traceFlags.toString(16).padStart(2,"0");return{traceId:sc.traceId,parentId:sc.spanId,traceFlags:sc.traceFlags,raw:`00-${sc.traceId}-${sc.spanId}-${flags}`}}function createOTelContextFromTrace(tc){const spanContext=frontmcpToOTelSpanContext(tc);const span=trace2.wrapSpanContext(spanContext);return trace2.setSpan(otelContext2.active(),span)}var SPAN_KEY=Symbol.for("frontmcp:otel:span");var SPAN_CTX_KEY=Symbol.for("frontmcp:otel:span-ctx");var EXEC_SPAN_KEY=Symbol.for("frontmcp:otel:exec-span");var ACTIVE_SPAN_KEY=Symbol.for("frontmcp:otel:active-span");var ACTIVE_OTEL_CTX_KEY=Symbol.for("frontmcp:otel:active-otel-ctx");var STAGE_TS_KEY=Symbol.for("frontmcp:otel:stage-ts");var STAGE_EVENTS_KEY=Symbol.for("frontmcp:otel:stage-events");var HTTP_SPAN_CTX_KEY=Symbol.for("frontmcp:otel:http-span-ctx");function sessionTracingId(sessionId){return sha256Hex(sessionId).slice(0,16)}function getTracer(){return trace3.getTracer("@frontmcp/observability")}function extractContext(flowCtx){try{const ctx=flowCtx.get?.(Symbol.for("frontmcp:CONTEXT"));if(ctx)return ctx}catch{}return flowCtx.state?.ctx??flowCtx.state?.frontmcpContext}function storeActiveSpan(flowCtx,span,otelCtx){try{const ctx=flowCtx.get?.(Symbol.for("frontmcp:CONTEXT"));if(ctx&&typeof ctx.set==="function"){ctx.set(ACTIVE_SPAN_KEY,span);ctx.set(ACTIVE_OTEL_CTX_KEY,otelCtx)}}catch{}}function clearActiveSpan(flowCtx){try{const ctx=flowCtx.get?.(Symbol.for("frontmcp:CONTEXT"));if(ctx&&typeof ctx.delete==="function"){ctx.delete(ACTIVE_SPAN_KEY);ctx.delete(ACTIVE_OTEL_CTX_KEY)}}catch{}}function beginFlowSpan(flowCtx,options,span,spanCtx){flowCtx.state[SPAN_KEY]=span;flowCtx.state[SPAN_CTX_KEY]=spanCtx;flowCtx.state[STAGE_TS_KEY]=Date.now();flowCtx.state[STAGE_EVENTS_KEY]=options.flowStageEvents!==false}function parentContextOf(ctx){return ctx.get?.(HTTP_SPAN_CTX_KEY)??createOTelContextFromTrace(ctx.traceContext)}function flowFailureOf(flowError){const failed=flowError?.originalError;const error=flowError instanceof FlowControl?failed instanceof Error?failed:new InternalMcpError(`Flow ended with: ${flowError.type}`):flowError instanceof Error?flowError:new Error(String(flowError));const reported=toMcpError(error);return{error,type:reported.name,message:reported.getPublicMessage(),code:reported.code,errorId:reported.errorId}}function endFailedSpan(span,flowError){const failure=flowFailureOf(flowError);span.setStatus({code:SpanStatusCode2.ERROR,message:failure.message});span.recordException({name:failure.type,message:failure.message,code:failure.code,stack:failure.error.stack});span.end()}function traceparentOf(span){const{traceId,spanId,traceFlags}=span.spanContext();return`00-${traceId}-${spanId}-${traceFlags.toString(16).padStart(2,"0")}`}function recordStageEvent(span,stageName,state){if(state[STAGE_EVENTS_KEY]===false)return;const now=Date.now();const prev=state[STAGE_TS_KEY];const attributes={};if(prev){attributes["duration_ms"]=now-prev}state[STAGE_TS_KEY]=now;span.addEvent(`stage.${stageName}`,attributes)}function onHttpWillTrace(options,flowCtx){if(options.httpSpans===false)return;const ctx=extractContext(flowCtx);if(!ctx)return;const tracer=getTracer();const parentOTelCtx=createOTelContextFromTrace(ctx.traceContext);const sessionHash=sessionTracingId(ctx.sessionId);const{span,context:spanCtx}=startHttpServerSpan(tracer,{method:ctx.metadata?.customHeaders?.["x-http-method"]??"POST",path:ctx.metadata?.customHeaders?.["x-url-path"]??"/",scopeId:ctx.scopeId,requestId:ctx.requestId,parentContext:parentOTelCtx});span.setAttribute(McpAttributes.SESSION_ID,sessionHash);span.setAttribute(FrontMcpAttributes.SESSION_ID_HASH,sessionHash);ctx.set?.(HTTP_SPAN_CTX_KEY,spanCtx);beginFlowSpan(flowCtx,options,span,spanCtx);recordStageEvent(span,"traceRequest",flowCtx.state)}function onHttpWillAcquireQuota(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,"acquireQuota",flowCtx.state)}function onHttpDidAcquireQuota(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,"acquireQuota.done",flowCtx.state)}function onHttpWillCheckAuth(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,"checkAuthorization",flowCtx.state)}function onHttpDidCheckAuth(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,"checkAuthorization.done",flowCtx.state)}function onHttpWillRoute(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,"router",flowCtx.state)}function onHttpDidRoute(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,"router.done",flowCtx.state)}function onHttpDidFinalize(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(!span)return;recordStageEvent(span,"finalize",flowCtx.state);const statusCode=flowCtx.state?.statusCode??200;setHttpResponseStatus(span,statusCode);if(statusCode>=400){endSpanError(span,`HTTP ${statusCode}`)}else{endSpanOk(span)}}function onToolWillParse(options,flowCtx){if(options.executionSpans===false)return;const ctx=extractContext(flowCtx);if(!ctx)return;const tracer=getTracer();const parentOTelCtx=parentContextOf(ctx);const sessionHash=sessionTracingId(ctx.sessionId);const{span,context:spanCtx}=startRpcSpan(tracer,{method:"tools/call",scopeId:ctx.scopeId,sessionIdHash:sessionHash,parentContext:parentOTelCtx});beginFlowSpan(flowCtx,options,span,spanCtx);recordStageEvent(span,"parseInput",flowCtx.state)}function onToolWillFindTool(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,"findTool",flowCtx.state)}function onToolWillCheckAuth(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,"checkToolAuthorization",flowCtx.state)}function onEntryWillCheckAuthorities(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,"checkEntryAuthorities",flowCtx.state)}function onEntryDidCheckAuthorities(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(!span)return;recordStageEvent(span,"checkEntryAuthorities.done",flowCtx.state);span.setAttribute("auth.authorities.result","granted")}function onToolWillCreateContext(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,"createToolCallContext",flowCtx.state)}function onToolWillValidateInput(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,"validateInput",flowCtx.state)}function onToolWillExecute(options,flowCtx){if(options.executionSpans===false)return;const ctx=extractContext(flowCtx);const rpcCtx=flowCtx.state?.[SPAN_CTX_KEY];const tracer=getTracer();const toolName=flowCtx.state?.input?.name??"unknown";const toolOwner=flowCtx.state?._toolOwnerId;const enduser=ctx?.authInfo;const{span:toolSpan,context:toolOTelCtx}=startToolSpan(tracer,{name:toolName,owner:toolOwner,enduserId:enduser?.clientId??enduser?.extra?.sub,enduserScope:Array.isArray(enduser?.scopes)?enduser.scopes.join(" "):void 0,parentContext:rpcCtx});flowCtx.state[EXEC_SPAN_KEY]=toolSpan;flowCtx.state[STAGE_TS_KEY]=Date.now();recordStageEvent(toolSpan,"execute.start",flowCtx.state);storeActiveSpan(flowCtx,toolSpan,toolOTelCtx)}function onToolDidExecute(options,flowCtx){const toolSpan=flowCtx.state?.[EXEC_SPAN_KEY];if(!toolSpan)return;recordStageEvent(toolSpan,"execute.done",flowCtx.state);endSpanOk(toolSpan);flowCtx.state[EXEC_SPAN_KEY]=void 0;clearActiveSpan(flowCtx)}function onToolWillValidateOutput(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,"validateOutput",flowCtx.state)}function onToolWillApplyUI(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,"applyUI",flowCtx.state)}function onToolDidFinalize(flowCtx){const rpcSpan=flowCtx.state?.[SPAN_KEY];const toolSpan=flowCtx.state?.[EXEC_SPAN_KEY];const error=flowCtx.state?.flowError;if(error){if(toolSpan)endFailedSpan(toolSpan,error);if(rpcSpan)endFailedSpan(rpcSpan,error)}else if(rpcSpan){recordStageEvent(rpcSpan,"finalize",flowCtx.state);endSpanOk(rpcSpan)}}function onResourceWillParse(options,flowCtx){if(options.executionSpans===false)return;const ctx=extractContext(flowCtx);if(!ctx)return;const tracer=getTracer();const parentOTelCtx=parentContextOf(ctx);const sessionHash=sessionTracingId(ctx.sessionId);const{span,context:spanCtx}=startRpcSpan(tracer,{method:"resources/read",scopeId:ctx.scopeId,sessionIdHash:sessionHash,parentContext:parentOTelCtx});beginFlowSpan(flowCtx,options,span,spanCtx);recordStageEvent(span,"parseInput",flowCtx.state)}function onResourceWillFind(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,"findResource",flowCtx.state)}function onResourceWillExecute(options,flowCtx){if(options.executionSpans===false)return;const rpcCtx=flowCtx.state?.[SPAN_CTX_KEY];const tracer=getTracer();const uri=flowCtx.state?.input?.uri??"unknown";const{span:resSpan,context:resOTelCtx}=startResourceSpan(tracer,{uri,parentContext:rpcCtx});flowCtx.state[EXEC_SPAN_KEY]=resSpan;flowCtx.state[STAGE_TS_KEY]=Date.now();recordStageEvent(resSpan,"execute.start",flowCtx.state);storeActiveSpan(flowCtx,resSpan,resOTelCtx)}function onResourceDidExecute(flowCtx){const resSpan=flowCtx.state?.[EXEC_SPAN_KEY];if(!resSpan)return;recordStageEvent(resSpan,"execute.done",flowCtx.state);endSpanOk(resSpan);flowCtx.state[EXEC_SPAN_KEY]=void 0;clearActiveSpan(flowCtx)}function onResourceDidFinalize(flowCtx){const rpcSpan=flowCtx.state?.[SPAN_KEY];const resSpan=flowCtx.state?.[EXEC_SPAN_KEY];const error=flowCtx.state?.flowError;if(error){if(resSpan)endFailedSpan(resSpan,error);if(rpcSpan)endFailedSpan(rpcSpan,error)}else if(rpcSpan){recordStageEvent(rpcSpan,"finalize",flowCtx.state);endSpanOk(rpcSpan)}}function onPromptWillParse(options,flowCtx){if(options.executionSpans===false)return;const ctx=extractContext(flowCtx);if(!ctx)return;const tracer=getTracer();const parentOTelCtx=parentContextOf(ctx);const sessionHash=sessionTracingId(ctx.sessionId);const{span,context:spanCtx}=startRpcSpan(tracer,{method:"prompts/get",scopeId:ctx.scopeId,sessionIdHash:sessionHash,parentContext:parentOTelCtx});beginFlowSpan(flowCtx,options,span,spanCtx);recordStageEvent(span,"parseInput",flowCtx.state)}function onPromptWillFind(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,"findPrompt",flowCtx.state)}function onPromptWillExecute(options,flowCtx){if(options.executionSpans===false)return;const rpcCtx=flowCtx.state?.[SPAN_CTX_KEY];const tracer=getTracer();const promptName=flowCtx.state?.input?.name??"unknown";const{span:promptSpan,context:promptOTelCtx}=startPromptSpan(tracer,{name:promptName,parentContext:rpcCtx});flowCtx.state[EXEC_SPAN_KEY]=promptSpan;flowCtx.state[STAGE_TS_KEY]=Date.now();recordStageEvent(promptSpan,"execute.start",flowCtx.state);storeActiveSpan(flowCtx,promptSpan,promptOTelCtx)}function onPromptDidExecute(flowCtx){const promptSpan=flowCtx.state?.[EXEC_SPAN_KEY];if(!promptSpan)return;recordStageEvent(promptSpan,"execute.done",flowCtx.state);endSpanOk(promptSpan);flowCtx.state[EXEC_SPAN_KEY]=void 0;clearActiveSpan(flowCtx)}function onPromptDidFinalize(flowCtx){const rpcSpan=flowCtx.state?.[SPAN_KEY];const promptSpan=flowCtx.state?.[EXEC_SPAN_KEY];const error=flowCtx.state?.flowError;if(error){if(promptSpan)endFailedSpan(promptSpan,error);if(rpcSpan)endFailedSpan(rpcSpan,error)}else if(rpcSpan){recordStageEvent(rpcSpan,"finalize",flowCtx.state);endSpanOk(rpcSpan)}}function onAgentWillParse(options,flowCtx){if(options.executionSpans===false)return;const ctx=extractContext(flowCtx);if(!ctx)return;const tracer=getTracer();const parentOTelCtx=parentContextOf(ctx);const sessionHash=sessionTracingId(ctx.sessionId);const{span,context:spanCtx}=startRpcSpan(tracer,{method:"agents/call",scopeId:ctx.scopeId,sessionIdHash:sessionHash,parentContext:parentOTelCtx});beginFlowSpan(flowCtx,options,span,spanCtx);recordStageEvent(span,"parseInput",flowCtx.state)}function onAgentWillFind(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,"findAgent",flowCtx.state)}function onAgentWillExecute(options,flowCtx){if(options.executionSpans===false)return;const rpcCtx=flowCtx.state?.[SPAN_CTX_KEY];const tracer=getTracer();const agentName=flowCtx.state?.input?.name??"unknown";const{span:agentSpan}=startSpan(tracer,{name:`agent ${agentName}`,kind:SpanKind12.INTERNAL,attributes:{[FrontMcpAttributes.FLOW_NAME]:"agents:call-agent",[McpAttributes.COMPONENT_TYPE]:"agent",[McpAttributes.COMPONENT_KEY]:`agent:${agentName}`},parentContext:rpcCtx});const agentOTelCtx=trace3.setSpan(rpcCtx??otelContext3.active(),agentSpan);flowCtx.state[EXEC_SPAN_KEY]=agentSpan;flowCtx.state[STAGE_TS_KEY]=Date.now();recordStageEvent(agentSpan,"execute.start",flowCtx.state);storeActiveSpan(flowCtx,agentSpan,agentOTelCtx)}function onAgentDidExecute(flowCtx){const agentSpan=flowCtx.state?.[EXEC_SPAN_KEY];if(!agentSpan)return;recordStageEvent(agentSpan,"execute.done",flowCtx.state);endSpanOk(agentSpan);flowCtx.state[EXEC_SPAN_KEY]=void 0;clearActiveSpan(flowCtx)}function onAgentDidFinalize(flowCtx){const rpcSpan=flowCtx.state?.[SPAN_KEY];const agentSpan=flowCtx.state?.[EXEC_SPAN_KEY];const error=flowCtx.state?.flowError;if(error){if(agentSpan)endFailedSpan(agentSpan,error);if(rpcSpan)endFailedSpan(rpcSpan,error)}else if(rpcSpan){recordStageEvent(rpcSpan,"finalize",flowCtx.state);endSpanOk(rpcSpan)}}function onGenericFlowWillStart(flowName,options,flowCtx){if(options.executionSpans===false)return;const ctx=extractContext(flowCtx);if(!ctx)return;const tracer=getTracer();const parentOTelCtx=parentContextOf(ctx);const sessionHash=sessionTracingId(ctx.sessionId);const{span,context:spanCtx}=startSpan(tracer,{name:flowName,kind:SpanKind12.INTERNAL,attributes:{[FrontMcpAttributes.FLOW_NAME]:flowName,[McpAttributes.SESSION_ID]:sessionHash,[FrontMcpAttributes.SESSION_ID_HASH]:sessionHash,[FrontMcpAttributes.SCOPE_ID]:ctx.scopeId,[FrontMcpAttributes.REQUEST_ID]:ctx.requestId},parentContext:parentOTelCtx});beginFlowSpan(flowCtx,options,span,spanCtx)}function onGenericFlowStage(stageName,flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,stageName,flowCtx.state)}function onGenericFlowDidFinalize(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(!span)return;const error=flowCtx.state?.flowError;if(error){endFailedSpan(span,error)}else{endSpanOk(span)}}function onTransportWillStart(transportType,options,flowCtx){if(options.transportSpans===false)return;const ctx=extractContext(flowCtx);if(!ctx)return;const tracer=getTracer();const parentOTelCtx=parentContextOf(ctx);const sessionHash=sessionTracingId(ctx.sessionId);const{span,context:spanCtx}=startTransportSpan(tracer,{type:transportType,sessionIdHash:sessionHash,parentContext:parentOTelCtx});beginFlowSpan(flowCtx,options,span,spanCtx);recordStageEvent(span,"parseInput",flowCtx.state)}function onTransportDidRoute(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(!span)return;recordStageEvent(span,"router",flowCtx.state);const requestType=flowCtx.state?.requestType;if(requestType)setTransportRequestType(span,requestType)}function onTransportStage(stageName,flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,stageName,flowCtx.state)}function onTransportDidFinalize(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(!span)return;recordStageEvent(span,"cleanup",flowCtx.state);const error=flowCtx.state?.flowError;if(error){endFailedSpan(span,error)}else{endSpanOk(span)}}function onAuthWillStart(flowName,options,flowCtx){if(options.authSpans===false)return;const ctx=extractContext(flowCtx);if(!ctx)return;const tracer=getTracer();const parentOTelCtx=parentContextOf(ctx);const{span,context:spanCtx}=startAuthSpan(tracer,{flowName,parentContext:parentOTelCtx});beginFlowSpan(flowCtx,options,span,spanCtx);recordStageEvent(span,"parseInput",flowCtx.state)}function onAuthDidDetermineMode(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(!span)return;recordStageEvent(span,"determineAuthMode",flowCtx.state);const mode=flowCtx.state?.authMode;if(mode)setAuthMode(span,mode)}function onAuthStage(stageName,flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(span)recordStageEvent(span,stageName,flowCtx.state)}function onAuthDidFinalize(flowCtx){const span=flowCtx.state?.[SPAN_KEY];if(!span)return;const error=flowCtx.state?.flowError;if(error){setAuthResult(span,"unauthorized");endFailedSpan(span,error)}else{setAuthResult(span,"authorized");endSpanOk(span)}}function wrapContextFetch(options,flowCtx){const toolCtx=flowCtx.state?.toolContext??flowCtx.state?.toolCallContext;if(!toolCtx||typeof toolCtx.fetch!=="function")return;const originalFetch=toolCtx.fetch.bind(toolCtx);const parentOTelCtx=flowCtx.state?.[SPAN_CTX_KEY];toolCtx.fetch=async(input,init)=>{const fetchSpan=options.fetchSpans===false?void 0:startFetchSpan(getTracer(),{method:init?.method??(input instanceof Request?input.method:"GET"),url:typeof input==="string"?input:input instanceof URL?input.toString():input.url,parentContext:parentOTelCtx}).span;const callingSpan=fetchSpan??flowCtx.state?.[EXEC_SPAN_KEY]??flowCtx.state?.[SPAN_KEY];const headers=new Headers(init?.headers??(input instanceof Request?input.headers:void 0));if(callingSpan&&!headers.has("traceparent"))headers.set("traceparent",traceparentOf(callingSpan));try{const response=await originalFetch(input,{...init,headers});if(fetchSpan){setFetchResponseStatus(fetchSpan,response.status);endSpanOk(fetchSpan)}return response}catch(err){if(fetchSpan)endSpanError(fetchSpan,err instanceof Error?err:String(err));throw err}}}function onAgentDidExecuteEnrich(flowCtx){const agentSpan=flowCtx.state?.[EXEC_SPAN_KEY];if(!agentSpan)return;const meta=flowCtx.state?.executionMeta;if(meta){if(typeof meta.iterations==="number"){agentSpan.setAttribute(FrontMcpAttributes.AGENT_ITERATIONS,meta.iterations)}if(typeof meta.durationMs==="number"){agentSpan.setAttribute(FrontMcpAttributes.AGENT_EXECUTION_DURATION_MS,meta.durationMs)}}}var HOOK_OBSERVER_KEY=Symbol.for("frontmcp:hook-observer");function installHookObserver(flowCtx,observer){const ctx=extractContext(flowCtx);if(ctx&&!ctx.get?.(HOOK_OBSERVER_KEY))ctx.set?.(HOOK_OBSERVER_KEY,observer)}async function runInHookSpan(flowCtx,hook,run){const ctx=extractContext(flowCtx);const{span}=startHookSpan(getTracer(),{...hook,parentContext:flowCtx.state?.[SPAN_CTX_KEY]??(ctx&&parentContextOf(ctx))});try{await run();endSpanOk(span)}catch(error){if(error instanceof FlowControl&&error.type!=="fail"&&error.type!=="abort")endSpanOk(span);else endFailedSpan(span,error);throw error}}function reportStartup(data){const tracer=getTracer();emitStartupReport(tracer,data)}var REQUEST_LOG_COLLECTOR=Symbol.for("frontmcp:observability:request-log-collector");var FRONTMCP_CONTEXT=Symbol.for("frontmcp:CONTEXT");function resolve(flowCtx,token){try{return flowCtx.get?.(token)}catch{return void 0}}function currentRequestLog(flowCtx){return resolve(flowCtx,FRONTMCP_CONTEXT)?.get(REQUEST_LOG_COLLECTOR)}function startRequestLog(flowCtx,options){const context=resolve(flowCtx,FRONTMCP_CONTEXT);if(!context)return;const collector=new RequestLogCollector({requestId:context.requestId,traceId:context.traceContext.traceId,sessionIdHash:sessionTracingId(context.sessionId).slice(0,12),scopeId:context.scopeId},options);context.set(REQUEST_LOG_COLLECTOR,collector);const request=flowCtx.rawInput?.request;if(request?.method&&request.path)collector.setHttpInfo(request.method,request.path);const rpcMethod=request?.body?.method;if(typeof rpcMethod==="string")collector.setRpcMethod(rpcMethod)}function recordRequestLogFailure(flowCtx){const flowError=flowCtx.state?.["flowError"];if(!flowError)return;const{type,message,code,errorId}=flowFailureOf(flowError);currentRequestLog(flowCtx)?.setError({type,message,code,error_id:errorId})}function recordRequestLogAuth(flowCtx){const verifyResult=flowCtx.state?.["verifyResult"];const authorization=flowCtx.rawInput?.request?.headers?.["authorization"];const scheme=typeof authorization==="string"?authorization.trim().split(/\s+/)[0].toLowerCase():"";const sub=verifyResult?.authorization?.user?.sub;const anonymous=typeof sub!=="string"||isAnonymousSubject(sub);currentRequestLog(flowCtx)?.setAuthInfo(anonymous||!scheme?"anonymous":scheme,verifyResult?.kind==="authorized"&&!anonymous)}async function completeRequestLog(flowCtx){const collector=currentRequestLog(flowCtx);if(!collector||collector.isFinalized())return;const statusCode=flowCtx.state?.["statusCode"]??flowCtx.rawInput?.response?.statusCode;if(typeof statusCode==="number")collector.setStatusCode(statusCode);await collector.finalize()}import{SpanKind as SpanKind13,SpanStatusCode as SpanStatusCode3,trace as trace4}from"@opentelemetry/api";import{metrics}from"@opentelemetry/api";function snapshotKey(name,attributes){const keys=Object.keys(attributes).sort();if(keys.length===0)return name;const tail=keys.map(k=>`${k}=${attributes[k]}`).join(",");return`${name}{${tail}}`}var snapshotStore=new Map;var TelemetryCounterImpl=class{constructor(name,otelCounter){this.name=name;this.otelCounter=otelCounter}inc(by=1,attributes={}){if(!Number.isFinite(by)||by<0){return}try{this.otelCounter.add(by,attributes)}catch{}const key=snapshotKey(this.name,attributes);const existing=snapshotStore.get(key);if(existing){existing.count+=by}else{snapshotStore.set(key,{name:this.name,count:by,attributes:{...attributes}})}}};var METER_NAME="@frontmcp/observability";var counterCache=new Map;function createCounter(name,description){const existing=counterCache.get(name);if(existing)return existing;const meter=metrics.getMeter(METER_NAME);const otelCounter=meter.createCounter(name,description?{description}:void 0);const counter=new TelemetryCounterImpl(name,otelCounter);counterCache.set(name,counter);return counter}function getMetricSnapshot(){return Array.from(snapshotStore.values()).map(entry=>({name:entry.name,count:entry.count,attributes:{...entry.attributes}}))}function getCounterTotal(name){let sum=0;for(const entry of snapshotStore.values()){if(entry.name===name)sum+=entry.count}return sum}function resetMetricSnapshot(){snapshotStore.clear()}function resetTelemetrySnapshotForTesting(){snapshotStore.clear()}function resetCounterCacheForTesting(){counterCache.clear()}var KNOWN_BUNDLE_SOURCES=["static","npm","saas-pull","webhook","filesystem","unknown"];function normalizeBundleSource(value){if(typeof value!=="string")return"unknown";return KNOWN_BUNDLE_SOURCES.includes(value)?value:"unknown"}var KNOWN_ERROR_REASONS=["network","timeout","invalid_response","parse_error","unknown"];function normalizeErrorReason(err){if(!err)return"unknown";const name=err instanceof Error?err.name:"";const message=err instanceof Error?err.message:typeof err==="string"?err:"";const haystack=`${name} ${message}`.toLowerCase();if(name==="TimeoutError"||haystack.includes("timeout")||haystack.includes("timed out")){return"timeout"}if(name==="NetworkError"||name==="FetchError"||haystack.includes("network")||haystack.includes("econnrefused")||haystack.includes("econnreset")||haystack.includes("enotfound")||haystack.includes("socket")||haystack.includes("dns")){return"network"}if(name==="SyntaxError"||haystack.includes("parse")||haystack.includes("json")){return"parse_error"}if(name==="TypeError"||name==="RangeError"||haystack.includes("invalid")||haystack.includes("malformed")||haystack.includes("schema")){return"invalid_response"}return"unknown"}var TelemetrySpan=class{constructor(span){this.span=span;this.hasError=false}setAttribute(key,value){this.span.setAttribute(key,value);return this}setAttributes(attrs){this.span.setAttributes(attrs);return this}addEvent(name,attributes){this.span.addEvent(name,attributes);return this}recordError(error){this.span.recordException(error);this.span.setStatus({code:SpanStatusCode3.ERROR,message:error.message});this.hasError=true;return this}end(){if(!this.hasError){this.span.setStatus({code:SpanStatusCode3.OK})}this.span.end()}endWithError(error){const msg=typeof error==="string"?error:error.message;if(error instanceof Error)this.span.recordException(error);this.span.setStatus({code:SpanStatusCode3.ERROR,message:msg});this.span.end()}get raw(){return this.span}};var TelemetryAccessor=class{constructor(ctx){this.ctx=ctx;this.tracer=trace4.getTracer("@frontmcp/observability");this.fallbackContext=createOTelContextFromTrace(ctx.traceContext);this.sessionHash=sessionTracingId(ctx.sessionId);this.baseAttributes={[FrontMcpAttributes.REQUEST_ID]:ctx.requestId,[FrontMcpAttributes.SCOPE_ID]:ctx.scopeId,[McpAttributes.SESSION_ID]:this.sessionHash}}getActiveContext(){const otelCtx=this.ctx.get?.(ACTIVE_OTEL_CTX_KEY);return otelCtx??this.fallbackContext}getActiveSpan(){return this.ctx.get?.(ACTIVE_SPAN_KEY)}startSpan(name,attributes){const span=this.tracer.startSpan(name,{kind:SpanKind13.INTERNAL,attributes:{...this.baseAttributes,...attributes}},this.getActiveContext());return new TelemetrySpan(span)}async withSpan(name,fn,attributes){const telemetrySpan=this.startSpan(name,attributes);try{const result=await fn(telemetrySpan);telemetrySpan.end();return result}catch(err){telemetrySpan.endWithError(err instanceof Error?err:String(err));throw err}}addEvent(name,attributes){const activeSpan=this.getActiveSpan();if(activeSpan){activeSpan.addEvent(name,attributes)}else{const span=this.tracer.startSpan(name,{kind:SpanKind13.INTERNAL,attributes:this.baseAttributes},this.fallbackContext);if(attributes)span.addEvent(name,attributes);span.setStatus({code:SpanStatusCode3.OK});span.end()}}setAttributes(attrs){const activeSpan=this.getActiveSpan();if(activeSpan){activeSpan.setAttributes(attrs)}}createCounter(name,description){return createCounter(name,description)}get traceId(){return trace4.getSpan(this.fallbackContext)?.spanContext().traceId??""}get sessionId(){return this.sessionHash}};import{SpanStatusCode as SpanStatusCode4,trace as trace5}from"@opentelemetry/api";var TelemetryFactory=class{constructor(tracerName="@frontmcp/observability"){this.tracer=trace5.getTracer(tracerName)}createCounter(name,description){return createCounter(name,description)}startSpan(name,attributes,parent){const opts=attributes?{attributes}:void 0;const span=parent?this.tracer.startSpan(name,opts,parent):this.tracer.startSpan(name,opts);return new TelemetrySpan(span)}async withSpan(name,fn,attributes){const span=this.startSpan(name,attributes);try{const result=await fn(span);span.end();return result}catch(err){span.endWithError(err instanceof Error?err:String(err));throw err}}};var TELEMETRY_ACCESSOR=Symbol.for("frontmcp:observability:telemetry-accessor");var TELEMETRY_FACTORY=Symbol.for("frontmcp:observability:telemetry-factory");var PromptHook=FlowHooksOf("prompts:get-prompt");var ListPromptsHook=FlowHooksOf("prompts:list-prompts");var SkillSearchHook=FlowHooksOf("skills:search");var SkillLoadHook=FlowHooksOf("skills:load");var CompletionHook=FlowHooksOf("completion:complete");var LegacySseHook=FlowHooksOf("handle:legacy-sse");var StreamableHttpHook=FlowHooksOf("handle:streamable-http");var StatelessHttpHook=FlowHooksOf("handle:stateless-http");var AuthVerifyHook=FlowHooksOf("auth:verify");var SessionVerifyHook=FlowHooksOf("session:verify");var OAuthTokenHook=FlowHooksOf("oauth:token");var OAuthAuthorizeHook=FlowHooksOf("oauth:authorize");var OAuthCallbackHook=FlowHooksOf("oauth:callback");var OAuthProviderCallbackHook=FlowHooksOf("oauth:provider-callback");var OAuthRegisterHook=FlowHooksOf("oauth:register");var ElicitRequestHook=FlowHooksOf("elicitation:request");var ElicitResultHook=FlowHooksOf("elicitation:result");var SubscribeResourceHook=FlowHooksOf("resources:subscribe");var UnsubscribeResourceHook=FlowHooksOf("resources:unsubscribe");var SkillsHttpLlmTxtHook=FlowHooksOf("skills-http:llm-txt");var SkillsHttpLlmFullTxtHook=FlowHooksOf("skills-http:llm-full-txt");var SkillsHttpApiHook=FlowHooksOf("skills-http:api");var WellKnownJwksHook=FlowHooksOf("well-known.jwks");var WellKnownOAuthServerHook=FlowHooksOf("well-known.oauth-authorization-server");var WellKnownPrmHook=FlowHooksOf("well-known.prm");var LoggingSetLevelHook=FlowHooksOf("logging:set-level");var DEFAULT_TRACING={httpSpans:true,executionSpans:true,hookSpans:false,fetchSpans:true,flowStageEvents:true,transportSpans:true,authSpans:true,oauthSpans:true,elicitationSpans:true,startupReport:true};var ObservabilityPlugin=class extends DynamicPlugin{constructor(options={}){super();this.observeHook=async({flowName,stage,target,flowContext},run)=>{if(target===this)return run();if(this.requestLogsEnabled)currentRequestLog(flowContext)?.addHook(`${flowName}:${stage}`);if(!this.traces("hookSpans"))return run();const owner=target?.constructor?.name;return runInHookSpan(flowContext,{flowName,stage,owner},run)};this.options=resolveOptions(options);this.tracingOpts=this.options.tracing!==false?this.options.tracing:DEFAULT_TRACING}get tracingEnabled(){return this.options.tracing!==false}get requestLogsEnabled(){return this.options.requestLogs!==false}traces(kind){return this.tracingEnabled&&this.tracingOpts[kind]!==false}watchHooks(ctx){if(this.requestLogsEnabled||this.traces("hookSpans"))installHookObserver(ctx,this.observeHook)}annotateRequestLog(ctx,set){if(!this.requestLogsEnabled)return;const flowCtx=ctx;const log=currentRequestLog(ctx);if(log&&flowCtx.state?.input)set(log,flowCtx.state.input)}_httpWillTrace(ctx){if(this.tracingEnabled)onHttpWillTrace(this.tracingOpts,ctx);if(this.options.requestLogs!==false)startRequestLog(ctx,this.options.requestLogs);this.watchHooks(ctx)}_httpWillQuota(ctx){if(this.tracingEnabled)onHttpWillAcquireQuota(ctx)}_httpDidSemaphore(ctx){if(this.tracingEnabled)onHttpDidAcquireQuota(ctx)}_httpWillAuth(ctx){if(this.tracingEnabled)onHttpWillCheckAuth(ctx)}_httpDidAuth(ctx){if(this.tracingEnabled)onHttpDidCheckAuth(ctx);if(this.requestLogsEnabled)recordRequestLogAuth(ctx)}_httpWillRoute(ctx){if(this.tracingEnabled)onHttpWillRoute(ctx)}_httpDidRoute(ctx){if(this.tracingEnabled)onHttpDidRoute(ctx)}_httpDidFinalize(ctx){if(this.tracingEnabled)onHttpDidFinalize(ctx);if(this.requestLogsEnabled)void completeRequestLog(ctx)}_toolWillParse(ctx){this.watchHooks(ctx);if(this.tracingEnabled)onToolWillParse(this.tracingOpts,ctx)}_toolWillFind(ctx){if(this.tracingEnabled)onToolWillFindTool(ctx);this.annotateRequestLog(ctx,(log,input)=>log.setToolName(String(input["name"])))}_toolWillCheckAuth(ctx){if(this.tracingEnabled)onToolWillCheckAuth(ctx)}_toolWillCheckAuthorities(ctx){if(this.tracingEnabled)onEntryWillCheckAuthorities(ctx)}_toolDidCheckAuthorities(ctx){if(this.tracingEnabled)onEntryDidCheckAuthorities(ctx)}_toolWillCreateCtx(ctx){if(this.tracingEnabled)onToolWillCreateContext(ctx)}_toolWillValidate(ctx){if(this.tracingEnabled)onToolWillValidateInput(ctx)}_toolWillExecute(ctx){if(this.tracingEnabled)onToolWillExecute(this.tracingOpts,ctx)}_toolDidExecute(ctx){if(this.tracingEnabled)onToolDidExecute(this.tracingOpts,ctx)}_toolWillValidateOut(ctx){if(this.tracingEnabled)onToolWillValidateOutput(ctx)}_toolWillApplyUI(ctx){if(this.tracingEnabled)onToolWillApplyUI(ctx)}_toolDidFinalize(ctx){if(this.tracingEnabled)onToolDidFinalize(ctx);if(this.requestLogsEnabled)recordRequestLogFailure(ctx)}_resourceWillParse(ctx){this.watchHooks(ctx);if(this.tracingEnabled)onResourceWillParse(this.tracingOpts,ctx)}_resourceWillFind(ctx){if(this.tracingEnabled)onResourceWillFind(ctx);this.annotateRequestLog(ctx,(log,input)=>log.setResourceUri(String(input["uri"])))}_resourceWillCheckAuthorities(ctx){if(this.tracingEnabled)onEntryWillCheckAuthorities(ctx)}_resourceDidCheckAuthorities(ctx){if(this.tracingEnabled)onEntryDidCheckAuthorities(ctx)}_resourceWillExecute(ctx){if(this.tracingEnabled)onResourceWillExecute(this.tracingOpts,ctx)}_resourceDidExecute(ctx){if(this.tracingEnabled)onResourceDidExecute(ctx)}_resourceDidFinalize(ctx){if(this.tracingEnabled)onResourceDidFinalize(ctx);if(this.requestLogsEnabled)recordRequestLogFailure(ctx)}_promptWillParse(ctx){this.watchHooks(ctx);if(this.tracingEnabled)onPromptWillParse(this.tracingOpts,ctx)}_promptWillFind(ctx){if(this.tracingEnabled)onPromptWillFind(ctx);this.annotateRequestLog(ctx,(log,input)=>log.setPromptName(String(input["name"])))}_promptWillCheckAuthorities(ctx){if(this.tracingEnabled)onEntryWillCheckAuthorities(ctx)}_promptDidCheckAuthorities(ctx){if(this.tracingEnabled)onEntryDidCheckAuthorities(ctx)}_promptWillExecute(ctx){if(this.tracingEnabled)onPromptWillExecute(this.tracingOpts,ctx)}_promptDidExecute(ctx){if(this.tracingEnabled)onPromptDidExecute(ctx)}_promptDidFinalize(ctx){if(this.tracingEnabled)onPromptDidFinalize(ctx);if(this.requestLogsEnabled)recordRequestLogFailure(ctx)}_agentWillParse(ctx){this.watchHooks(ctx);if(this.tracingEnabled)onAgentWillParse(this.tracingOpts,ctx)}_agentWillFind(ctx){if(this.tracingEnabled)onAgentWillFind(ctx)}_agentWillCheckAuthorities(ctx){if(this.tracingEnabled)onEntryWillCheckAuthorities(ctx)}_agentDidCheckAuthorities(ctx){if(this.tracingEnabled)onEntryDidCheckAuthorities(ctx)}_agentWillExecute(ctx){if(this.tracingEnabled)onAgentWillExecute(this.tracingOpts,ctx)}_agentDidExecute(ctx){if(this.tracingEnabled)onAgentDidExecute(ctx)}_agentDidFinalize(ctx){if(this.tracingEnabled)onAgentDidFinalize(ctx)}_listToolsWill(ctx){if(this.tracingEnabled)onGenericFlowWillStart("tools/list",this.tracingOpts,ctx)}_listToolsDidFind(ctx){if(this.tracingEnabled)onGenericFlowStage("findTools",ctx)}_listToolsDidFilter(ctx){if(this.tracingEnabled)onGenericFlowStage("filterByAuthorities",ctx)}_listToolsDone(ctx){if(this.tracingEnabled)onGenericFlowDidFinalize(ctx)}_listResourcesWill(ctx){if(this.tracingEnabled)onGenericFlowWillStart("resources/list",this.tracingOpts,ctx)}_listResourcesDidFilter(ctx){if(this.tracingEnabled)onGenericFlowStage("filterByAuthorities",ctx)}_listResourcesDone(ctx){if(this.tracingEnabled)onGenericFlowDidFinalize(ctx)}_listTemplatesWill(ctx){if(this.tracingEnabled)onGenericFlowWillStart("resources/listTemplates",this.tracingOpts,ctx)}_listTemplatesDidFilter(ctx){if(this.tracingEnabled)onGenericFlowStage("filterByAuthorities",ctx)}_listTemplatesDone(ctx){if(this.tracingEnabled)onGenericFlowDidFinalize(ctx)}_listPromptsWill(ctx){if(this.tracingEnabled)onGenericFlowWillStart("prompts/list",this.tracingOpts,ctx)}_listPromptsDidFilter(ctx){if(this.tracingEnabled)onGenericFlowStage("filterByAuthorities",ctx)}_listPromptsDone(ctx){if(this.tracingEnabled)onGenericFlowDidFinalize(ctx)}_skillSearchWill(ctx){if(this.tracingEnabled)onGenericFlowWillStart("skills/search",this.tracingOpts,ctx)}_skillSearchDone(ctx){if(this.tracingEnabled)onGenericFlowDidFinalize(ctx)}_skillLoadWill(ctx){if(this.tracingEnabled)onGenericFlowWillStart("skills/load",this.tracingOpts,ctx)}_skillLoadStage(ctx){if(this.tracingEnabled)onGenericFlowStage("loadSkills",ctx)}_skillLoadDone(ctx){if(this.tracingEnabled)onGenericFlowDidFinalize(ctx)}_completionWill(ctx){if(this.tracingEnabled)onGenericFlowWillStart("completion/complete",this.tracingOpts,ctx)}_completionDone(ctx){if(this.tracingEnabled)onGenericFlowDidFinalize(ctx)}_sseWillParse(ctx){if(this.tracingEnabled)onTransportWillStart("legacy-sse",this.tracingOpts,ctx)}_sseDidRoute(ctx){if(this.tracingEnabled)onTransportDidRoute(ctx)}_sseDidInit(ctx){if(this.tracingEnabled)onTransportStage("onInitialize",ctx)}_sseDidMsg(ctx){if(this.tracingEnabled)onTransportStage("onMessage",ctx)}_sseDidElicit(ctx){if(this.tracingEnabled)onTransportStage("onElicitResult",ctx)}_sseDidCleanup(ctx){if(this.tracingEnabled)onTransportDidFinalize(ctx)}_shttpWillParse(ctx){if(this.tracingEnabled)onTransportWillStart("streamable-http",this.tracingOpts,ctx)}_shttpDidRoute(ctx){if(this.tracingEnabled)onTransportDidRoute(ctx)}_shttpDidInit(ctx){if(this.tracingEnabled)onTransportStage("onInitialize",ctx)}_shttpDidMsg(ctx){if(this.tracingEnabled)onTransportStage("onMessage",ctx)}_shttpDidElicit(ctx){if(this.tracingEnabled)onTransportStage("onElicitResult",ctx)}_shttpDidSse(ctx){if(this.tracingEnabled)onTransportStage("onSseListener",ctx)}_shttpDidExtApps(ctx){if(this.tracingEnabled)onTransportStage("onExtApps",ctx)}_shttpDidCleanup(ctx){if(this.tracingEnabled)onTransportDidFinalize(ctx)}_slhttpWillParse(ctx){if(this.tracingEnabled)onTransportWillStart("stateless-http",this.tracingOpts,ctx)}_slhttpDidHandle(ctx){if(this.tracingEnabled)onTransportStage("handleRequest",ctx)}_slhttpDidCleanup(ctx){if(this.tracingEnabled)onTransportDidFinalize(ctx)}_authVerifyWill(ctx){if(this.tracingEnabled)onAuthWillStart("auth:verify",this.tracingOpts,ctx)}_authVerifyDidMode(ctx){if(this.tracingEnabled)onAuthDidDetermineMode(ctx)}_authVerifyDidToken(ctx){if(this.tracingEnabled)onAuthStage("verifyToken",ctx)}_authVerifyDidBuild(ctx){if(this.tracingEnabled)onAuthDidFinalize(ctx)}_sessionVerifyWill(ctx){if(this.tracingEnabled)onAuthWillStart("session:verify",this.tracingOpts,ctx)}_sessionVerifyDidJwt(ctx){if(this.tracingEnabled)onAuthStage("verifyIfJwt",ctx)}_sessionVerifyDidBuild(ctx){if(this.tracingEnabled)onAuthDidFinalize(ctx)}_oauthTokenWill(ctx){if(this.traces("oauthSpans"))onGenericFlowWillStart("oauth/token",this.tracingOpts,ctx)}_oauthTokenDone(ctx){if(this.traces("oauthSpans"))onGenericFlowDidFinalize(ctx)}_oauthAuthzWill(ctx){if(this.traces("oauthSpans"))onGenericFlowWillStart("oauth/authorize",this.tracingOpts,ctx)}_oauthAuthzDone(ctx){if(this.traces("oauthSpans"))onGenericFlowDidFinalize(ctx)}_oauthCallbackWill(ctx){if(this.traces("oauthSpans"))onGenericFlowWillStart("oauth/callback",this.tracingOpts,ctx)}_oauthCallbackDone(ctx){if(this.traces("oauthSpans"))onGenericFlowDidFinalize(ctx)}_oauthProviderWill(ctx){if(this.traces("oauthSpans"))onGenericFlowWillStart("oauth/provider-callback",this.tracingOpts,ctx)}_oauthProviderDone(ctx){if(this.traces("oauthSpans"))onGenericFlowDidFinalize(ctx)}_oauthRegisterWill(ctx){if(this.traces("oauthSpans"))onGenericFlowWillStart("oauth/register",this.tracingOpts,ctx)}_oauthRegisterDone(ctx){if(this.traces("oauthSpans"))onGenericFlowDidFinalize(ctx)}_elicitReqWill(ctx){if(this.traces("elicitationSpans"))onGenericFlowWillStart("elicitation/request",this.tracingOpts,ctx)}_elicitReqDone(ctx){if(this.traces("elicitationSpans"))onGenericFlowDidFinalize(ctx)}_elicitResWill(ctx){if(this.traces("elicitationSpans"))onGenericFlowWillStart("elicitation/result",this.tracingOpts,ctx)}_elicitResDone(ctx){if(this.traces("elicitationSpans"))onGenericFlowDidFinalize(ctx)}_subscribeWill(ctx){if(this.tracingEnabled)onGenericFlowWillStart("resources/subscribe",this.tracingOpts,ctx)}_subscribeDone(ctx){if(this.tracingEnabled)onGenericFlowDidFinalize(ctx)}_unsubscribeWill(ctx){if(this.tracingEnabled)onGenericFlowWillStart("resources/unsubscribe",this.tracingOpts,ctx)}_unsubscribeDone(ctx){if(this.tracingEnabled)onGenericFlowDidFinalize(ctx)}_skillsLlmTxtWill(ctx){if(this.tracingEnabled)onGenericFlowWillStart("skills-http/llm-txt",this.tracingOpts,ctx)}_skillsLlmTxtDone(ctx){if(this.tracingEnabled)onGenericFlowDidFinalize(ctx)}_skillsLlmFullTxtWill(ctx){if(this.tracingEnabled)onGenericFlowWillStart("skills-http/llm-full-txt",this.tracingOpts,ctx)}_skillsLlmFullTxtDone(ctx){if(this.tracingEnabled)onGenericFlowDidFinalize(ctx)}_skillsApiWill(ctx){if(this.tracingEnabled)onGenericFlowWillStart("skills-http/api",this.tracingOpts,ctx)}_skillsApiDone(ctx){if(this.tracingEnabled)onGenericFlowDidFinalize(ctx)}_jwksWill(ctx){if(this.tracingEnabled)onGenericFlowWillStart("well-known/jwks",this.tracingOpts,ctx)}_jwksDone(ctx){if(this.tracingEnabled)onGenericFlowDidFinalize(ctx)}_oauthServerWill(ctx){if(this.tracingEnabled)onGenericFlowWillStart("well-known/oauth-server",this.tracingOpts,ctx)}_oauthServerDone(ctx){if(this.tracingEnabled)onGenericFlowDidFinalize(ctx)}_prmWill(ctx){if(this.tracingEnabled)onGenericFlowWillStart("well-known/prm",this.tracingOpts,ctx)}_prmDone(ctx){if(this.tracingEnabled)onGenericFlowDidFinalize(ctx)}_setLevelWill(ctx){if(this.tracingEnabled)onGenericFlowWillStart("logging/set-level",this.tracingOpts,ctx)}_setLevelDone(ctx){if(this.tracingEnabled)onGenericFlowDidFinalize(ctx)}_toolDidCreateCtxFetch(ctx){if(this.tracingEnabled)wrapContextFetch(this.tracingOpts,ctx)}_agentDidExecuteMeta(ctx){if(this.tracingEnabled)onAgentDidExecuteEnrich(ctx)}reportStartupTelemetry(data){if(this.traces("startupReport"))reportStartup(data)}};ObservabilityPlugin.defaultOptions={tracing:DEFAULT_TRACING,logging:false,requestLogs:false};ObservabilityPlugin.dynamicProviders=input=>{const options=resolveOptions(input);const providers=[];if(options.tracing!==false){providers.push({name:"observability:tracer",provide:OTEL_TRACER,useValue:trace6.getTracer("@frontmcp/observability")});providers.push({name:"observability:config",provide:OTEL_CONFIG,useValue:options.tracing});providers.push({name:"observability:telemetry-accessor",provide:TELEMETRY_ACCESSOR,scope:ProviderScope.CONTEXT,inject:()=>[FRONTMCP_CONTEXT2],useFactory:ctx=>new TelemetryAccessor(ctx)});providers.push({name:"observability:telemetry-factory",provide:TELEMETRY_FACTORY,useValue:new TelemetryFactory})}if(options.logging!==false){const loggingOpts=options.logging;const sinks=createSinks(loggingOpts.sinks);const transport=new StructuredLogTransport(sinks,{redactFields:loggingOpts.redactFields,includeStacks:loggingOpts.includeStacks,staticFields:loggingOpts.staticFields},void 0);providers.push({name:"observability:structured-log-transport",provide:StructuredLogTransport,useValue:transport})}if(options.requestLogs!==false){const requestLogOpts=options.requestLogs;providers.push({name:"observability:request-log-collector",provide:REQUEST_LOG_COLLECTOR,scope:ProviderScope.CONTEXT,inject:()=>[FRONTMCP_CONTEXT2],useFactory:ctx=>{return new RequestLogCollector({requestId:ctx.requestId,traceId:ctx.traceContext.traceId,sessionIdHash:sessionTracingId(ctx.sessionId).slice(0,12),scopeId:ctx.scopeId},requestLogOpts)}})}return providers};__decorateClass([HttpHook.Will("traceRequest",{priority:-1e3})],ObservabilityPlugin.prototype,"_httpWillTrace",1);__decorateClass([HttpHook.Will("acquireQuota",{priority:-1e3})],ObservabilityPlugin.prototype,"_httpWillQuota",1);__decorateClass([HttpHook.Did("acquireSemaphore",{priority:1e3})],ObservabilityPlugin.prototype,"_httpDidSemaphore",1);__decorateClass([HttpHook.Will("checkAuthorization",{priority:-1e3})],ObservabilityPlugin.prototype,"_httpWillAuth",1);__decorateClass([HttpHook.Did("checkAuthorization",{priority:1e3})],ObservabilityPlugin.prototype,"_httpDidAuth",1);__decorateClass([HttpHook.Will("router",{priority:-1e3})],ObservabilityPlugin.prototype,"_httpWillRoute",1);__decorateClass([HttpHook.Did("router",{priority:1e3})],ObservabilityPlugin.prototype,"_httpDidRoute",1);__decorateClass([HttpHook.Did("finalize",{priority:1e3})],ObservabilityPlugin.prototype,"_httpDidFinalize",1);__decorateClass([ToolHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_toolWillParse",1);__decorateClass([ToolHook.Will("findTool",{priority:-1e3})],ObservabilityPlugin.prototype,"_toolWillFind",1);__decorateClass([ToolHook.Will("checkToolAuthorization",{priority:-1e3})],ObservabilityPlugin.prototype,"_toolWillCheckAuth",1);__decorateClass([ToolHook.Will("checkEntryAuthorities",{priority:-1e3})],ObservabilityPlugin.prototype,"_toolWillCheckAuthorities",1);__decorateClass([ToolHook.Did("checkEntryAuthorities",{priority:1e3})],ObservabilityPlugin.prototype,"_toolDidCheckAuthorities",1);__decorateClass([ToolHook.Will("createToolCallContext",{priority:-1e3})],ObservabilityPlugin.prototype,"_toolWillCreateCtx",1);__decorateClass([ToolHook.Will("validateInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_toolWillValidate",1);__decorateClass([ToolHook.Will("execute",{priority:-1e3})],ObservabilityPlugin.prototype,"_toolWillExecute",1);__decorateClass([ToolHook.Did("execute",{priority:1e3})],ObservabilityPlugin.prototype,"_toolDidExecute",1);__decorateClass([ToolHook.Will("validateOutput",{priority:-1e3})],ObservabilityPlugin.prototype,"_toolWillValidateOut",1);__decorateClass([ToolHook.Will("applyUI",{priority:-1e3})],ObservabilityPlugin.prototype,"_toolWillApplyUI",1);__decorateClass([ToolHook.Did("finalize",{priority:1e3})],ObservabilityPlugin.prototype,"_toolDidFinalize",1);__decorateClass([ResourceHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_resourceWillParse",1);__decorateClass([ResourceHook.Will("findResource",{priority:-1e3})],ObservabilityPlugin.prototype,"_resourceWillFind",1);__decorateClass([ResourceHook.Will("checkEntryAuthorities",{priority:-1e3})],ObservabilityPlugin.prototype,"_resourceWillCheckAuthorities",1);__decorateClass([ResourceHook.Did("checkEntryAuthorities",{priority:1e3})],ObservabilityPlugin.prototype,"_resourceDidCheckAuthorities",1);__decorateClass([ResourceHook.Will("execute",{priority:-1e3})],ObservabilityPlugin.prototype,"_resourceWillExecute",1);__decorateClass([ResourceHook.Did("execute",{priority:1e3})],ObservabilityPlugin.prototype,"_resourceDidExecute",1);__decorateClass([ResourceHook.Did("finalize",{priority:1e3})],ObservabilityPlugin.prototype,"_resourceDidFinalize",1);__decorateClass([PromptHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_promptWillParse",1);__decorateClass([PromptHook.Will("findPrompt",{priority:-1e3})],ObservabilityPlugin.prototype,"_promptWillFind",1);__decorateClass([PromptHook.Will("checkEntryAuthorities",{priority:-1e3})],ObservabilityPlugin.prototype,"_promptWillCheckAuthorities",1);__decorateClass([PromptHook.Did("checkEntryAuthorities",{priority:1e3})],ObservabilityPlugin.prototype,"_promptDidCheckAuthorities",1);__decorateClass([PromptHook.Will("execute",{priority:-1e3})],ObservabilityPlugin.prototype,"_promptWillExecute",1);__decorateClass([PromptHook.Did("execute",{priority:1e3})],ObservabilityPlugin.prototype,"_promptDidExecute",1);__decorateClass([PromptHook.Did("finalize",{priority:1e3})],ObservabilityPlugin.prototype,"_promptDidFinalize",1);__decorateClass([AgentCallHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_agentWillParse",1);__decorateClass([AgentCallHook.Will("findAgent",{priority:-1e3})],ObservabilityPlugin.prototype,"_agentWillFind",1);__decorateClass([AgentCallHook.Will("checkEntryAuthorities",{priority:-1e3})],ObservabilityPlugin.prototype,"_agentWillCheckAuthorities",1);__decorateClass([AgentCallHook.Did("checkEntryAuthorities",{priority:1e3})],ObservabilityPlugin.prototype,"_agentDidCheckAuthorities",1);__decorateClass([AgentCallHook.Will("execute",{priority:-1e3})],ObservabilityPlugin.prototype,"_agentWillExecute",1);__decorateClass([AgentCallHook.Did("execute",{priority:1e3})],ObservabilityPlugin.prototype,"_agentDidExecute",1);__decorateClass([AgentCallHook.Did("finalize",{priority:1e3})],ObservabilityPlugin.prototype,"_agentDidFinalize",1);__decorateClass([ListToolsHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_listToolsWill",1);__decorateClass([ListToolsHook.Did("findTools",{priority:1e3})],ObservabilityPlugin.prototype,"_listToolsDidFind",1);__decorateClass([ListToolsHook.Did("filterByAuthorities",{priority:1e3})],ObservabilityPlugin.prototype,"_listToolsDidFilter",1);__decorateClass([ListToolsHook.Did("parseTools",{priority:1e3})],ObservabilityPlugin.prototype,"_listToolsDone",1);__decorateClass([ListResourcesHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_listResourcesWill",1);__decorateClass([ListResourcesHook.Did("filterByAuthorities",{priority:1e3})],ObservabilityPlugin.prototype,"_listResourcesDidFilter",1);__decorateClass([ListResourcesHook.Did("parseResources",{priority:1e3})],ObservabilityPlugin.prototype,"_listResourcesDone",1);__decorateClass([ListResourceTemplatesHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_listTemplatesWill",1);__decorateClass([ListResourceTemplatesHook.Did("filterByAuthorities",{priority:1e3})],ObservabilityPlugin.prototype,"_listTemplatesDidFilter",1);__decorateClass([ListResourceTemplatesHook.Did("parseTemplates",{priority:1e3})],ObservabilityPlugin.prototype,"_listTemplatesDone",1);__decorateClass([ListPromptsHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_listPromptsWill",1);__decorateClass([ListPromptsHook.Did("filterByAuthorities",{priority:1e3})],ObservabilityPlugin.prototype,"_listPromptsDidFilter",1);__decorateClass([ListPromptsHook.Did("parsePrompts",{priority:1e3})],ObservabilityPlugin.prototype,"_listPromptsDone",1);__decorateClass([SkillSearchHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_skillSearchWill",1);__decorateClass([SkillSearchHook.Did("finalize",{priority:1e3})],ObservabilityPlugin.prototype,"_skillSearchDone",1);__decorateClass([SkillLoadHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_skillLoadWill",1);__decorateClass([SkillLoadHook.Will("loadSkills",{priority:-1e3})],ObservabilityPlugin.prototype,"_skillLoadStage",1);__decorateClass([SkillLoadHook.Did("finalize",{priority:1e3})],ObservabilityPlugin.prototype,"_skillLoadDone",1);__decorateClass([CompletionHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_completionWill",1);__decorateClass([CompletionHook.Did("finalize",{priority:1e3})],ObservabilityPlugin.prototype,"_completionDone",1);__decorateClass([LegacySseHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_sseWillParse",1);__decorateClass([LegacySseHook.Did("router",{priority:1e3})],ObservabilityPlugin.prototype,"_sseDidRoute",1);__decorateClass([LegacySseHook.Did("onInitialize",{priority:1e3})],ObservabilityPlugin.prototype,"_sseDidInit",1);__decorateClass([LegacySseHook.Did("onMessage",{priority:1e3})],ObservabilityPlugin.prototype,"_sseDidMsg",1);__decorateClass([LegacySseHook.Did("onElicitResult",{priority:1e3})],ObservabilityPlugin.prototype,"_sseDidElicit",1);__decorateClass([LegacySseHook.Did("cleanup",{priority:1e3})],ObservabilityPlugin.prototype,"_sseDidCleanup",1);__decorateClass([StreamableHttpHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_shttpWillParse",1);__decorateClass([StreamableHttpHook.Did("router",{priority:1e3})],ObservabilityPlugin.prototype,"_shttpDidRoute",1);__decorateClass([StreamableHttpHook.Did("onInitialize",{priority:1e3})],ObservabilityPlugin.prototype,"_shttpDidInit",1);__decorateClass([StreamableHttpHook.Did("onMessage",{priority:1e3})],ObservabilityPlugin.prototype,"_shttpDidMsg",1);__decorateClass([StreamableHttpHook.Did("onElicitResult",{priority:1e3})],ObservabilityPlugin.prototype,"_shttpDidElicit",1);__decorateClass([StreamableHttpHook.Did("onSseListener",{priority:1e3})],ObservabilityPlugin.prototype,"_shttpDidSse",1);__decorateClass([StreamableHttpHook.Did("onExtApps",{priority:1e3})],ObservabilityPlugin.prototype,"_shttpDidExtApps",1);__decorateClass([StreamableHttpHook.Did("cleanup",{priority:1e3})],ObservabilityPlugin.prototype,"_shttpDidCleanup",1);__decorateClass([StatelessHttpHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_slhttpWillParse",1);__decorateClass([StatelessHttpHook.Did("handleRequest",{priority:1e3})],ObservabilityPlugin.prototype,"_slhttpDidHandle",1);__decorateClass([StatelessHttpHook.Did("cleanup",{priority:1e3})],ObservabilityPlugin.prototype,"_slhttpDidCleanup",1);__decorateClass([AuthVerifyHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_authVerifyWill",1);__decorateClass([AuthVerifyHook.Did("determineAuthMode",{priority:1e3})],ObservabilityPlugin.prototype,"_authVerifyDidMode",1);__decorateClass([AuthVerifyHook.Did("verifyToken",{priority:1e3})],ObservabilityPlugin.prototype,"_authVerifyDidToken",1);__decorateClass([AuthVerifyHook.Did("buildAuthorization",{priority:1e3})],ObservabilityPlugin.prototype,"_authVerifyDidBuild",1);__decorateClass([SessionVerifyHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_sessionVerifyWill",1);__decorateClass([SessionVerifyHook.Did("verifyIfJwt",{priority:1e3})],ObservabilityPlugin.prototype,"_sessionVerifyDidJwt",1);__decorateClass([SessionVerifyHook.Did("buildAuthorizedOutput",{priority:1e3})],ObservabilityPlugin.prototype,"_sessionVerifyDidBuild",1);__decorateClass([OAuthTokenHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_oauthTokenWill",1);__decorateClass([OAuthTokenHook.Did("buildTokenResponse",{priority:1e3})],ObservabilityPlugin.prototype,"_oauthTokenDone",1);__decorateClass([OAuthAuthorizeHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_oauthAuthzWill",1);__decorateClass([OAuthAuthorizeHook.Did("buildAuthorizeOutput",{priority:1e3})],ObservabilityPlugin.prototype,"_oauthAuthzDone",1);__decorateClass([OAuthCallbackHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_oauthCallbackWill",1);__decorateClass([OAuthCallbackHook.Did("redirectToClient",{priority:1e3})],ObservabilityPlugin.prototype,"_oauthCallbackDone",1);__decorateClass([OAuthProviderCallbackHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_oauthProviderWill",1);__decorateClass([OAuthProviderCallbackHook.Did("handleNextProviderOrComplete",{priority:1e3})],ObservabilityPlugin.prototype,"_oauthProviderDone",1);__decorateClass([OAuthRegisterHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_oauthRegisterWill",1);__decorateClass([OAuthRegisterHook.Did("respondRegistration",{priority:1e3})],ObservabilityPlugin.prototype,"_oauthRegisterDone",1);__decorateClass([ElicitRequestHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_elicitReqWill",1);__decorateClass([ElicitRequestHook.Did("finalize",{priority:1e3})],ObservabilityPlugin.prototype,"_elicitReqDone",1);__decorateClass([ElicitResultHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_elicitResWill",1);__decorateClass([ElicitResultHook.Did("finalize",{priority:1e3})],ObservabilityPlugin.prototype,"_elicitResDone",1);__decorateClass([SubscribeResourceHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_subscribeWill",1);__decorateClass([SubscribeResourceHook.Did("finalize",{priority:1e3})],ObservabilityPlugin.prototype,"_subscribeDone",1);__decorateClass([UnsubscribeResourceHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_unsubscribeWill",1);__decorateClass([UnsubscribeResourceHook.Did("finalize",{priority:1e3})],ObservabilityPlugin.prototype,"_unsubscribeDone",1);__decorateClass([SkillsHttpLlmTxtHook.Will("checkEnabled",{priority:-1e3})],ObservabilityPlugin.prototype,"_skillsLlmTxtWill",1);__decorateClass([SkillsHttpLlmTxtHook.Did("generateContent",{priority:1e3})],ObservabilityPlugin.prototype,"_skillsLlmTxtDone",1);__decorateClass([SkillsHttpLlmFullTxtHook.Will("checkEnabled",{priority:-1e3})],ObservabilityPlugin.prototype,"_skillsLlmFullTxtWill",1);__decorateClass([SkillsHttpLlmFullTxtHook.Did("generateContent",{priority:1e3})],ObservabilityPlugin.prototype,"_skillsLlmFullTxtDone",1);__decorateClass([SkillsHttpApiHook.Will("checkEnabled",{priority:-1e3})],ObservabilityPlugin.prototype,"_skillsApiWill",1);__decorateClass([SkillsHttpApiHook.Did("handleRequest",{priority:1e3})],ObservabilityPlugin.prototype,"_skillsApiDone",1);__decorateClass([WellKnownJwksHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_jwksWill",1);__decorateClass([WellKnownJwksHook.Did("collectData",{priority:1e3})],ObservabilityPlugin.prototype,"_jwksDone",1);__decorateClass([WellKnownOAuthServerHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_oauthServerWill",1);__decorateClass([WellKnownOAuthServerHook.Did("collectData",{priority:1e3})],ObservabilityPlugin.prototype,"_oauthServerDone",1);__decorateClass([WellKnownPrmHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_prmWill",1);__decorateClass([WellKnownPrmHook.Did("collectData",{priority:1e3})],ObservabilityPlugin.prototype,"_prmDone",1);__decorateClass([LoggingSetLevelHook.Will("parseInput",{priority:-1e3})],ObservabilityPlugin.prototype,"_setLevelWill",1);__decorateClass([LoggingSetLevelHook.Did("finalize",{priority:1e3})],ObservabilityPlugin.prototype,"_setLevelDone",1);__decorateClass([ToolHook.Did("createToolCallContext",{priority:999})],ObservabilityPlugin.prototype,"_toolDidCreateCtxFetch",1);__decorateClass([AgentCallHook.Did("execute",{priority:999})],ObservabilityPlugin.prototype,"_agentDidExecuteMeta",1);ObservabilityPlugin=__decorateClass([Plugin({name:"observability",description:"Full-system OpenTelemetry instrumentation, structured logging, and request logs",providers:[],contextExtensions:[{property:"telemetry",token:TELEMETRY_ACCESSOR,errorMessage:"ObservabilityPlugin is not installed or tracing is disabled. Add ObservabilityPlugin.init() to your plugins array."}]})],ObservabilityPlugin);function resolveOptions(input){return{tracing:resolveTracingOptions(input.tracing),logging:resolveLoggingOptions(input.logging),requestLogs:resolveRequestLogOptions(input.requestLogs)}}function resolveTracingOptions(input){if(input===false)return false;if(input===true||input===void 0)return DEFAULT_TRACING;return{...DEFAULT_TRACING,...input}}function resolveLoggingOptions(input){if(input===false||input===void 0)return false;if(input===true)return{};return input}function resolveRequestLogOptions(input){if(input===false||input===void 0)return false;if(input===true)return{};return input}import{trace as trace7}from"@opentelemetry/api";var TRACEPARENT_HEADER="traceparent";var FrontMcpPropagator=class{inject(context,carrier,setter){const span=trace7.getSpan(context);if(!span)return;const sc=span.spanContext();if(!sc||!isValidSpanContext(sc))return;const flags=sc.traceFlags.toString(16).padStart(2,"0");const traceparent=`00-${sc.traceId}-${sc.spanId}-${flags}`;setter.set(carrier,TRACEPARENT_HEADER,traceparent)}extract(context,carrier,getter){const traceparent=getter.get(carrier,TRACEPARENT_HEADER);const value=Array.isArray(traceparent)?traceparent[0]:traceparent;if(!value)return context;const parsed=parseTraceparent(value);if(!parsed)return context;const spanContext={traceId:parsed.traceId,spanId:parsed.parentId,traceFlags:parsed.traceFlags,isRemote:true};const span=trace7.wrapSpanContext(spanContext);return trace7.setSpan(context,span)}fields(){return[TRACEPARENT_HEADER]}};function parseTraceparent(value){const parts=value.split("-");if(parts.length!==4)return null;const[version,traceId,parentId,flags]=parts;if(version!=="00")return null;if(!/^[a-f0-9]{32}$/i.test(traceId)||traceId==="00000000000000000000000000000000")return null;if(!/^[a-f0-9]{16}$/i.test(parentId)||parentId==="0000000000000000")return null;if(!/^[0-9a-fA-F]{2}$/.test(flags))return null;const traceFlags=parseInt(flags,16);return{traceId:traceId.toLowerCase(),parentId:parentId.toLowerCase(),traceFlags}}function isValidSpanContext(sc){return sc.traceId!=="00000000000000000000000000000000"&&sc.spanId!=="0000000000000000"&&sc.traceId.length===32&&sc.spanId.length===16}function setupOTel(options){const serviceName=options?.serviceName??process.env["OTEL_SERVICE_NAME"]??"frontmcp-server";const exporterType=options?.exporter??"console";const endpoint=options?.endpoint??process.env["OTEL_EXPORTER_OTLP_ENDPOINT"]??"http://localhost:4318";let traceExporter;if(exporterType==="otlp"){try{const{OTLPTraceExporter}=__require("@opentelemetry/exporter-trace-otlp-http");traceExporter=new OTLPTraceExporter({url:`${endpoint}/v1/traces`})}catch{throw new Error("setupOTel: @opentelemetry/exporter-trace-otlp-http is required for OTLP export. Install it with: npm install @opentelemetry/exporter-trace-otlp-http")}}else if(exporterType==="console"){const{ConsoleSpanExporter}=__require("@opentelemetry/sdk-trace-base");traceExporter=new ConsoleSpanExporter}try{const{NodeSDK}=__require("@opentelemetry/sdk-node");const{resourceFromAttributes}=__require("@opentelemetry/resources");const{ATTR_SERVICE_NAME,ATTR_SERVICE_VERSION}=__require("@opentelemetry/semantic-conventions");const resource=resourceFromAttributes({[ATTR_SERVICE_NAME]:serviceName,...options?.serviceVersion?{[ATTR_SERVICE_VERSION]:options.serviceVersion}:{}});const sdk=new NodeSDK({resource,traceExporter});sdk.start();return async()=>{await sdk.shutdown()}}catch{throw new Error("setupOTel: @opentelemetry/sdk-node is required. Install it with: npm install @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/semantic-conventions")}}import{SpanKind as SpanKind14,SpanStatusCode as SpanStatusCode5}from"@opentelemetry/api";var RESET="\x1B[0m";var DIM="\x1B[2m";var BOLD="\x1B[1m";var CYAN="\x1B[36m";var GREEN="\x1B[32m";var RED="\x1B[31m";var YELLOW="\x1B[33m";var KIND_LABELS={[SpanKind14.INTERNAL]:"INTERNAL",[SpanKind14.SERVER]:"SERVER",[SpanKind14.CLIENT]:"CLIENT",[SpanKind14.PRODUCER]:"PRODUCER",[SpanKind14.CONSUMER]:"CONSUMER"};var SHOW_ATTRS=new Set(["rpc.system","rpc.method","rpc.service","mcp.method.name","mcp.session.id","mcp.component.type","mcp.component.key","http.request.method","http.response.status_code","url.path","frontmcp.tool.name","frontmcp.tool.owner","frontmcp.transport.type","frontmcp.transport.request_type","frontmcp.auth.mode","frontmcp.auth.result","frontmcp.flow.name","enduser.id"]);var PrettySpanExporter=class{constructor(){this.useAnsi=typeof process!=="undefined"&&!!process.stdout?.isTTY}export(spans,resultCallback){for(const span of spans){console.log(this.format(span))}resultCallback({code:0})}shutdown(){return Promise.resolve()}format(span){const traceShort=span.spanContext().traceId.slice(0,8);const durationMs=(span.duration[0]*1e3+span.duration[1]/1e6).toFixed(1);const kind=KIND_LABELS[span.kind]??"UNKNOWN";const statusOk=span.status.code!==SpanStatusCode5.ERROR;const attrs=Object.entries(span.attributes).filter(([k])=>SHOW_ATTRS.has(k)).map(([k,v])=>{const short=k.replace("frontmcp.","").replace("mcp.","");return`${short}=${v}`}).join(" ");const eventCount=span.events.length;const eventSummary=eventCount>0?` (${eventCount} events)`:"";if(this.useAnsi){const statusColor=statusOk?GREEN:RED;const kindColor=span.kind===SpanKind14.SERVER?CYAN:DIM;return[`${DIM}\u21B3${RESET}`,`${BOLD}${statusColor}SPAN${RESET}`,`${BOLD}${span.name}${RESET}`,`${DIM}[${traceShort}]${RESET}`,`${YELLOW}${durationMs}ms${RESET}`,`${kindColor}${kind}${RESET}`,attrs?`${DIM}${attrs}${RESET}`:"",eventSummary?`${DIM}${eventSummary}${RESET}`:""].filter(Boolean).join(" ")}return["\u21B3 SPAN",span.name,`[${traceShort}]`,`${durationMs}ms`,kind,attrs,eventSummary].filter(Boolean).join(" ")}};init_winston_sink();init_pino_sink();init_otlp_sink();var METRIC_NAME_REGEX=/^[a-zA-Z_:][a-zA-Z0-9_:]*$/;var LABEL_NAME_REGEX=/^[a-zA-Z_][a-zA-Z0-9_]*$/;var PROMETHEUS_CONTENT_TYPE="text/plain; version=0.0.4; charset=utf-8";function escapeLabelValue(value){return value.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n")}function sortedLabelString(attributes){const keys=Object.keys(attributes).filter(k=>LABEL_NAME_REGEX.test(k)).sort();if(keys.length===0)return"";const pairs=keys.map(k=>`${k}="${escapeLabelValue(attributes[k]??"")}"`);return`{${pairs.join(",")}}`}function formatFloat(value){if(!Number.isFinite(value))return"";if(Number.isInteger(value))return String(value);return String(value)}function renderPrometheusExposition(counters,gauges=[],options={}){const byName=new Map;for(const entry of counters){if(!METRIC_NAME_REGEX.test(entry.name))continue;const valueStr=formatFloat(entry.count);if(valueStr==="")continue;const labels=sortedLabelString(entry.attributes??{});const line=`${entry.name}${labels} ${valueStr}`;let group=byName.get(entry.name);if(!group){group={type:"counter",help:options.counterHelp?.[entry.name],lines:[]};byName.set(entry.name,group)}group.lines.push(line)}for(const entry of gauges){if(!METRIC_NAME_REGEX.test(entry.name))continue;const valueStr=formatFloat(entry.value);if(valueStr==="")continue;const labels=sortedLabelString(entry.attributes??{});const line=`${entry.name}${labels} ${valueStr}`;let group=byName.get(entry.name);if(!group){group={type:"gauge",help:entry.help,lines:[]};byName.set(entry.name,group)}else if(entry.help&&!group.help){group.help=entry.help}group.lines.push(line)}if(byName.size===0)return"";const sortedNames=Array.from(byName.keys()).sort();const blocks=[];for(const name of sortedNames){const group=byName.get(name);if(!group)continue;const block=[];if(group.help){block.push(`# HELP ${name} ${group.help.replace(/\n/g," ")}`)}block.push(`# TYPE ${name} ${group.type}`);block.push(...group.lines.slice().sort());blocks.push(block.join("\n"))}return blocks.join("\n")+"\n"}function renderJsonExposition(counters,gauges=[]){return{counters:counters.filter(c=>METRIC_NAME_REGEX.test(c.name)&&Number.isFinite(c.count)).map(c=>({name:c.name,count:c.count,attributes:{...c.attributes??{}}})),gauges:gauges.filter(g=>METRIC_NAME_REGEX.test(g.name)&&Number.isFinite(g.value)).map(g=>({name:g.name,value:g.value,attributes:{...g.attributes??{}},...g.help?{help:g.help}:{}}))}}import{readdirSync}from"@frontmcp/utils";var NS_PER_SECOND=1e9;var MICROS_PER_SECOND=1e6;function probeSafely(probe){try{return probe()}catch{return void 0}}function defaultMonitorEventLoopDelay(){try{const{monitorEventLoopDelay}=__require("node:perf_hooks");const histogram=monitorEventLoopDelay({resolution:10});histogram.enable();return histogram}catch{return void 0}}function defaultGetActiveHandles(){const proc=process;if(typeof proc._getActiveHandles!=="function")return void 0;try{return proc._getActiveHandles()}catch{return void 0}}function defaultGetActiveRequests(){const proc=process;if(typeof proc._getActiveRequests!=="function")return void 0;try{return proc._getActiveRequests()}catch{return void 0}}function defaultReadFdCount(){if(process.platform!=="linux")return void 0;try{return readdirSync("/proc/self/fd").length}catch{return void 0}}var ProcessStatsCollector=class{constructor(init={}){this.options=init.options??{};this.cpuUsage=init.cpuUsage??(prev=>process.cpuUsage(prev));this.memoryUsage=init.memoryUsage??(()=>process.memoryUsage());this.uptime=init.uptime??(()=>process.uptime());this.getActiveHandles=init.getActiveHandles??defaultGetActiveHandles;this.getActiveRequests=init.getActiveRequests??defaultGetActiveRequests;this.readFdCount=init.readFdCount??defaultReadFdCount;this.cpuStart=probeSafely(()=>this.cpuUsage());if(this.options.eventLoopLag!==false){this.histogram=init.monitorEventLoopDelay?init.monitorEventLoopDelay():defaultMonitorEventLoopDelay()}}collect(){const entries=[];this.cpuStart??=probeSafely(()=>this.cpuUsage());const cpu=this.cpuStart&&probeSafely(()=>this.cpuUsage(this.cpuStart));if(cpu){entries.push({name:"frontmcp_process_cpu_seconds_total",value:cpu.user/MICROS_PER_SECOND,attributes:{mode:"user"},help:"CPU time consumed since collector start, by mode (seconds)"});entries.push({name:"frontmcp_process_cpu_seconds_total",value:cpu.system/MICROS_PER_SECOND,attributes:{mode:"system"}})}const mem=probeSafely(()=>this.memoryUsage());if(mem&&mem.rss>0){entries.push({name:"frontmcp_process_resident_memory_bytes",value:mem.rss,help:"Resident memory size in bytes"});entries.push({name:"frontmcp_process_heap_bytes",value:mem.heapTotal,help:"Total V8 heap size in bytes"});entries.push({name:"frontmcp_process_heap_used_bytes",value:mem.heapUsed,help:"Used V8 heap size in bytes"});entries.push({name:"frontmcp_process_external_bytes",value:mem.external,help:"Memory used by C++ objects bound to JS in bytes"})}const uptime=probeSafely(()=>this.uptime());if(uptime!==void 0&&uptime>0){entries.push({name:"frontmcp_process_uptime_seconds",value:uptime,help:"Time since process start in seconds"})}const histogram=this.options.eventLoopLag!==false?this.histogram:void 0;const lag=histogram&&probeSafely(()=>{const sample={meanSeconds:histogram.mean/NS_PER_SECOND,p99Seconds:histogram.percentile(99)/NS_PER_SECOND};histogram.reset();return sample});if(lag){const{meanSeconds,p99Seconds}=lag;if(Number.isFinite(meanSeconds)){entries.push({name:"frontmcp_nodejs_eventloop_lag_seconds",value:meanSeconds,attributes:{quantile:"mean"},help:"Event-loop lag in seconds, sampled at 10ms resolution since the last scrape"})}if(Number.isFinite(p99Seconds)){entries.push({name:"frontmcp_nodejs_eventloop_lag_seconds",value:p99Seconds,attributes:{quantile:"p99"}})}}if(this.options.activeHandles!==false){const handles=this.getActiveHandles?.();if(handles!==void 0){entries.push({name:"frontmcp_nodejs_active_handles",value:handles.length,help:"Currently active libuv handles (sockets, timers, etc.)"})}const requests=this.getActiveRequests?.();if(requests!==void 0){entries.push({name:"frontmcp_nodejs_active_requests",value:requests.length,help:"Currently active libuv requests (file I/O, DNS, etc.)"})}}if(this.options.fdCount!==false){const fdCount=this.readFdCount();if(typeof fdCount==="number"){entries.push({name:"frontmcp_nodejs_open_fds",value:fdCount,help:"Number of open file descriptors (Linux only)"})}}return entries}close(){this.histogram?.disable?.()}};function createTestTracer(name="test"){const sdkTraceBase=__require("@opentelemetry/sdk-trace-base");const exporter=new sdkTraceBase.InMemorySpanExporter;const provider=new sdkTraceBase.BasicTracerProvider({spanProcessors:[new sdkTraceBase.SimpleSpanProcessor(exporter)]});const tracer=provider.getTracer(name);return{tracer,exporter,provider,cleanup:async()=>{exporter.reset();await provider.forceFlush();await provider.shutdown()}}}function getFinishedSpans(exporter){return exporter.getFinishedSpans()}function assertSpanExists(spans,name){const match=spans.find(s=>s.name===name);if(!match){const names=spans.map(s=>s.name).join(", ");throw new Error(`Expected span "${name}" but found: [${names}]`)}return match}function assertSpanAttribute(span,key,value){const actual=span.attributes[key];if(actual!==value){throw new Error(`Expected span "${span.name}" attribute "${key}" to be ${JSON.stringify(value)} but got ${JSON.stringify(actual)}`)}}function findSpan(spans,name){return spans.find(s=>s.name===name)}function findSpansByAttribute(spans,key,value){return spans.filter(s=>s.attributes[key]===value)}export{CallbackSink,ConsoleSink,EnduserAttributes,FrontMcpAttributes,FrontMcpPropagator,HttpAttributes,KNOWN_BUNDLE_SOURCES,KNOWN_ERROR_REASONS,LOG_LEVEL_TO_OTEL_SEVERITY,McpAttributes,OTEL_CONFIG,OTEL_TRACER,ObservabilityPlugin,OtlpSink,PROMETHEUS_CONTENT_TYPE,PinoSink,PrettySpanExporter,ProcessStatsCollector,REQUEST_LOG_COLLECTOR,RequestLogCollector,RpcAttributes,StdoutSink,StructuredLogTransport,TELEMETRY_ACCESSOR,TELEMETRY_FACTORY,TelemetryAccessor,TelemetryFactory,TelemetrySpan,WinstonSink,assertSpanAttribute,assertSpanExists,createCounter,createOTelContextFromTrace,createSink,createSinks,createTestTracer,emitStartupReport,endSpanError,endSpanOk,findSpan,findSpansByAttribute,frontmcpToOTelSpanContext,getCounterTotal,getFinishedSpans,getMetricSnapshot,normalizeBundleSource,normalizeErrorReason,otelToFrontmcpContext,recordHookEvent,redactFields,renderJsonExposition,renderPrometheusExposition,reportStartup,resetCounterCacheForTesting,resetMetricSnapshot,resetTelemetrySnapshotForTesting,sessionTracingId,setAuthMode,setAuthResult,setFetchResponseStatus,setHttpResponseStatus,setTransportRequestType,setupOTel,startAuthSpan,startFetchSpan,startHookSpan,startHttpServerSpan,startPromptSpan,startResourceSpan,startRpcSpan,startSpan,startToolSpan,startTransportSpan,withSpan};
|