@kopai/mcp 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,769 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _kopai_core = require("@kopai/core");
3
+ let _modelcontextprotocol_server = require("@modelcontextprotocol/server");
4
+ let zod = require("zod");
5
+ let _modelcontextprotocol_fastify = require("@modelcontextprotocol/fastify");
6
+ let _modelcontextprotocol_node = require("@modelcontextprotocol/node");
7
+ //#region src/dedupe.ts
8
+ /** Keywords whose value is a single schema. */
9
+ const SCHEMA_VALUE = /* @__PURE__ */ new Set([
10
+ "items",
11
+ "additionalProperties",
12
+ "additionalItems",
13
+ "contains",
14
+ "propertyNames",
15
+ "not",
16
+ "if",
17
+ "then",
18
+ "else",
19
+ "unevaluatedItems",
20
+ "unevaluatedProperties"
21
+ ]);
22
+ /** Keywords whose value is an array of schemas. */
23
+ const SCHEMA_ARRAY = /* @__PURE__ */ new Set([
24
+ "allOf",
25
+ "anyOf",
26
+ "oneOf",
27
+ "prefixItems"
28
+ ]);
29
+ /** Keywords whose value maps arbitrary names to schemas. */
30
+ const SCHEMA_MAP = /* @__PURE__ */ new Set([
31
+ "properties",
32
+ "patternProperties",
33
+ "dependentSchemas",
34
+ "$defs",
35
+ "definitions"
36
+ ]);
37
+ /**
38
+ * Rebuilds `node`, invoking `cb` on every descendant that is itself a schema.
39
+ * Returning a value from `cb` replaces that subtree; returning `undefined`
40
+ * descends into it. The root is never offered to `cb` — a document cannot be
41
+ * replaced by a reference to itself.
42
+ */
43
+ function eachSchema(node, cb, isRoot = false) {
44
+ if (!node || typeof node !== "object" || Array.isArray(node)) return node;
45
+ const obj = node;
46
+ if (!isRoot) {
47
+ const replacement = cb(obj);
48
+ if (replacement !== void 0) return replacement;
49
+ }
50
+ const out = {};
51
+ for (const [key, value] of Object.entries(obj)) if (SCHEMA_VALUE.has(key) && value && typeof value === "object" && !Array.isArray(value)) out[key] = eachSchema(value, cb);
52
+ else if (SCHEMA_ARRAY.has(key) && Array.isArray(value)) out[key] = value.map((s) => eachSchema(s, cb));
53
+ else if (SCHEMA_MAP.has(key) && value && typeof value === "object") out[key] = Object.fromEntries(Object.entries(value).map(([name, s]) => [name, eachSchema(s, cb)]));
54
+ else out[key] = value;
55
+ return out;
56
+ }
57
+ /**
58
+ * Returns `doc` with every subschema that occurs more than once hoisted into
59
+ * `$defs`.
60
+ *
61
+ * `minLen` is the serialized length below which a repeat is not worth a
62
+ * reference — a `$ref` costs about 30 characters, so hoisting anything
63
+ * shorter makes the document bigger. Any existing `$defs` are preserved and
64
+ * deduplicated alongside the body.
65
+ */
66
+ function dedupe(doc, minLen = 60) {
67
+ const existingDefs = doc.$defs ?? {};
68
+ const counts = /* @__PURE__ */ new Map();
69
+ const body = { ...doc };
70
+ delete body.$defs;
71
+ const count = (n) => {
72
+ const key = JSON.stringify(n);
73
+ if (key.length >= minLen) counts.set(key, (counts.get(key) ?? 0) + 1);
74
+ };
75
+ eachSchema(body, count, true);
76
+ for (const def of Object.values(existingDefs)) eachSchema(def, count, true);
77
+ const refNames = /* @__PURE__ */ new Map();
78
+ const newDefs = {};
79
+ let next = 0;
80
+ for (const [key, seen] of [...counts.entries()].sort((a, b) => b[0].length - a[0].length)) {
81
+ if (seen < 2) continue;
82
+ let name = `s${next++}`;
83
+ while (Object.hasOwn(existingDefs, name)) name = `s${next++}`;
84
+ refNames.set(key, name);
85
+ newDefs[name] = JSON.parse(key);
86
+ }
87
+ const substitute = (n) => {
88
+ const name = refNames.get(JSON.stringify(n));
89
+ return name === void 0 ? void 0 : { $ref: `#/$defs/${name}` };
90
+ };
91
+ const result = eachSchema(doc, substitute, true);
92
+ const defs = { ...result.$defs ?? {} };
93
+ for (const [name, defBody] of [...Object.entries(newDefs), ...Object.entries(existingDefs)]) {
94
+ const self = JSON.stringify(defBody);
95
+ defs[name] = eachSchema(defBody, (n) => JSON.stringify(n) === self ? void 0 : substitute(n), true);
96
+ }
97
+ result.$defs = defs;
98
+ return result;
99
+ }
100
+ //#endregion
101
+ //#region src/limits.ts
102
+ /**
103
+ * Row caps, per mode.
104
+ *
105
+ * WHY per mode rather than one number: measured serialized row sizes differ by
106
+ * an order of magnitude. A raw trace row is ~703 characters, a raw log row
107
+ * ~418, a raw metric row 408-653 (OTel repeats the metric name, description
108
+ * and unit on every data point), against ~96 for an aggregate summary row and
109
+ * ~134 for a `timeSeries` row. Against the character ceiling below, a uniform
110
+ * cap of 500 would let every raw shape overrun — traces by 134%, logs by 39%,
111
+ * metrics by 36-118% — so a raw query that used its own cap would pay for a
112
+ * full round trip and then have the result refused.
113
+ *
114
+ * At 200 they all fit, though traces land at ~94% of budget, which is why the
115
+ * post-serialization check stays load-bearing rather than being a formality.
116
+ * Treat these figures as optimistic: they come from fixtures, and production
117
+ * attribute maps are heavier.
118
+ *
119
+ * The consequence for callers, worth stating in the tool description: the
120
+ * aggregate shape is the efficient one and raw is for inspecting individual
121
+ * records. One hour of one gauge costs roughly 116,400 characters as raw rows
122
+ * against 8,040 as a `timeSeries` aggregate at `1m` — fourteen times less, for
123
+ * the same chart, with the bucketing done in the database.
124
+ */
125
+ const LIMITS = {
126
+ raw: {
127
+ /** Applied when the caller sends no `limit`; matches the backend default. */
128
+ fallback: 100,
129
+ max: 200
130
+ },
131
+ aggregate: {
132
+ /**
133
+ * Applied when the caller sends no `limit`. Unlike raw, this is not a
134
+ * backend default being restated: both backends emit `LIMIT` for an
135
+ * aggregate query only when one is explicitly set, so an aggregate query
136
+ * with no limit runs unbounded.
137
+ */
138
+ fallback: 500,
139
+ max: 500
140
+ }
141
+ };
142
+ /**
143
+ * The serialized size past which a result is refused rather than returned.
144
+ *
145
+ * Measured after serialization, on one copy of the payload — the result
146
+ * carries the same JSON in two channels, but a client forwards one or the
147
+ * other, so the model only ever ingests it once.
148
+ */
149
+ const MAX_RESULT_CHARACTERS = 15e4;
150
+ /**
151
+ * Remedies for a discovery listing too large even with the attributes gone.
152
+ *
153
+ * WHY its own list: `metrics_discover` takes no arguments, so every line in
154
+ * `SIZE_REMEDIES` names a field the caller cannot set — a `limit`, a window, a
155
+ * `granularity`. Offering those turned an over-size listing into a dead end
156
+ * dressed up as advice. Nothing the caller writes can shrink this result, so
157
+ * the honest answer is what remains possible without it.
158
+ */
159
+ const DISCOVERY_SIZE_REMEDIES = ["Query a metric by name with the `query` tool — discovery is not a prerequisite for it.", "Ask an operator to reduce what this deployment ingests: this workspace holds more metrics than one response can carry."];
160
+ /** Remedies offered when a result is too large once serialized. */
161
+ const SIZE_REMEDIES = [
162
+ "Lower `limit`.",
163
+ "Narrow the time window.",
164
+ "Use a coarser `granularity`, or `output: {type: 'summary'}` instead of a time series."
165
+ ];
166
+ /**
167
+ * How many time buckets the window will be cut into, or 1 for a summary.
168
+ *
169
+ * WHY this is worth computing: an aggregate's row count is groups times
170
+ * buckets, and the two need opposite advice. Buckets are exactly derivable
171
+ * from the window and the granularity, which is enough to tell the two causes
172
+ * apart — if the buckets alone exceed the cap then no amount of regrouping
173
+ * will help, and if they do not then the group cardinality is what overran.
174
+ *
175
+ * WHY boundaries rather than whole spans: neither backend cuts the window into
176
+ * granularity-sized pieces starting at its own start. Both snap each timestamp
177
+ * to a fixed boundary measured from the epoch — `(ts / g) * g` in SQLite,
178
+ * `toStartOfInterval(ts, INTERVAL n SECOND)` in ClickHouse — so a window that
179
+ * does not begin on a boundary straddles one more bucket than it has whole
180
+ * granularities. Measured against a real SQLite datasource: an hour at `5m`
181
+ * starting at :02:30 produces thirteen distinct `bucket_start` values, not
182
+ * twelve. Counting whole spans understated every unaligned window by one.
183
+ */
184
+ function bucketCount(query) {
185
+ if (query.mode !== "aggregate" || query.output.type !== "timeSeries") return 1;
186
+ const granularityNs = _kopai_core.kopaiQuery.durationStringToNanos(query.output.granularity);
187
+ if (typeof granularityNs !== "number" || granularityNs <= 0) return 1;
188
+ const window = query.timeDimension;
189
+ if (window.type === "relative") {
190
+ const lookbackNs = _kopai_core.kopaiQuery.durationStringToNanos(window.lookback);
191
+ if (typeof lookbackNs !== "number" || lookbackNs <= 0) return 1;
192
+ return Math.ceil(lookbackNs / granularityNs) + 1;
193
+ }
194
+ const startMs = Date.parse(window.startTime);
195
+ const endMs = Date.parse(window.endTime);
196
+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs) || endMs <= startMs) return 1;
197
+ const granularityMs = granularityNs / 1e6;
198
+ const firstBoundary = Math.floor(startMs / granularityMs);
199
+ const lastBoundary = Math.ceil(endMs / granularityMs) - 1;
200
+ return Math.max(1, lastBoundary - firstBoundary + 1);
201
+ }
202
+ /**
203
+ * Remedies for an aggregate query that overran its cap, ordered by whichever
204
+ * factor actually caused it.
205
+ *
206
+ * WHY ordered rather than a fixed list: an aggregate returns groups times
207
+ * buckets rows, and advice for one is useless for the other. Telling someone
208
+ * grouping by a high-cardinality column in a `summary` query to use a coarser
209
+ * granularity names a field their query does not have; telling someone whose
210
+ * window is cut into more buckets than the cap allows to group by less will
211
+ * not help them either.
212
+ *
213
+ * WHY there is no "add an `orderBy`" line: an ordering does not change the
214
+ * outcome. An overflow is refused whether or not the query is ordered, because
215
+ * a live page cannot act on a remedy — its query was fixed at authoring time
216
+ * and its viewer did not write it — so a truncated result would be drawn as
217
+ * though it were the whole set.
218
+ */
219
+ function overflowRemedies(query, limit, max) {
220
+ const isTimeSeries = query.mode === "aggregate" && query.output.type === "timeSeries";
221
+ const buckets = bucketCount(query);
222
+ const grouped = query.mode === "aggregate" && (query.dimensions?.length ?? 0) > 0;
223
+ const raiseLimit = limit < max ? [`Raise \`limit\`, up to ${max}.`] : [];
224
+ const coarser = `Use a coarser \`granularity\`: at this granularity the window spans up to ${buckets.toLocaleString("en-US")} buckets, and every group is counted once per bucket.`;
225
+ const fewerGroups = "Group by fewer dimensions, or filter to the groups you care about — a high-cardinality column such as a span name or a route produces a row per distinct value.";
226
+ const narrower = "Narrow the time window.";
227
+ const summarise_ = "Use `output: { type: \"summary\" }` if the trend over time is not what you need.";
228
+ if (isTimeSeries && buckets > limit) return [
229
+ ...raiseLimit,
230
+ coarser,
231
+ narrower,
232
+ summarise_
233
+ ];
234
+ if (isTimeSeries) {
235
+ const coarserIfItHelps = buckets > 1 ? [coarser] : [];
236
+ return grouped ? [
237
+ ...raiseLimit,
238
+ fewerGroups,
239
+ ...coarserIfItHelps,
240
+ narrower,
241
+ summarise_
242
+ ] : [
243
+ ...raiseLimit,
244
+ ...coarserIfItHelps,
245
+ narrower,
246
+ summarise_
247
+ ];
248
+ }
249
+ return [
250
+ ...raiseLimit,
251
+ fewerGroups,
252
+ narrower
253
+ ];
254
+ }
255
+ //#endregion
256
+ //#region src/describe.ts
257
+ function descriptionOverrides(rawMax, aggregateMax, rawDefault, aggregateDefault) {
258
+ return [
259
+ {
260
+ prefix: "Maximum rows to return.",
261
+ mode: "replace",
262
+ text: `Maximum rows to return. This tool caps it at ${rawMax} in raw mode and ${aggregateMax} in aggregate mode, and refuses a higher value rather than quietly lowering it. Omit it for ${rawDefault} in raw mode and ${aggregateDefault} in aggregate mode. The two modes then differ: raw mode truncates to the limit and returns a cursor for the rest, while aggregate mode refuses a result that exceeds it outright, returning no rows.`
263
+ },
264
+ {
265
+ prefix: "Bucket width.",
266
+ mode: "append",
267
+ text: " A time series returns one row per group per bucket, so halving this doubles the rows returned."
268
+ },
269
+ {
270
+ prefix: "GROUP BY columns.",
271
+ mode: "append",
272
+ text: " The row count is the number of distinct value combinations here, multiplied by the bucket count when output is a time series. A high-cardinality column such as a span name, a route or a user id can exceed the row cap on its own."
273
+ }
274
+ ];
275
+ }
276
+ /**
277
+ * Returns `doc` with each override applied wherever its prefix matches, and a
278
+ * count per override so a caller can tell whether any stopped matching.
279
+ */
280
+ function applyDescriptions(doc, overrides) {
281
+ const applied = Object.fromEntries(overrides.map((o) => [o.prefix, 0]));
282
+ const rewrite = (value) => {
283
+ if (Array.isArray(value)) return value.map(rewrite);
284
+ if (!value || typeof value !== "object") return value;
285
+ const node = { ...value };
286
+ const description = node.description;
287
+ if (typeof description === "string") for (const override of overrides) {
288
+ if (!description.startsWith(override.prefix)) continue;
289
+ node.description = override.mode === "replace" ? override.text : description + override.text;
290
+ applied[override.prefix] = (applied[override.prefix] ?? 0) + 1;
291
+ break;
292
+ }
293
+ for (const [key, child] of Object.entries(node)) {
294
+ if (key === "description") continue;
295
+ node[key] = rewrite(child);
296
+ }
297
+ return node;
298
+ };
299
+ return {
300
+ document: rewrite(doc),
301
+ applied
302
+ };
303
+ }
304
+ //#endregion
305
+ //#region src/schema.ts
306
+ /**
307
+ * The `query` tool's input: the KopaiQuery body under a single `query`
308
+ * property, because an MCP tool's input schema must have an object root and
309
+ * KopaiQuery is a union.
310
+ *
311
+ * Strict, so the document says `additionalProperties: false` on the root as
312
+ * well as on every node inside it. In `io: "input"` mode zod leaves a plain
313
+ * `z.object` open, which advertised a tool that accepted arguments it would
314
+ * then ignore; `runQueryTool` rejects them, and the schema now agrees.
315
+ */
316
+ const QueryToolInput = zod.z.strictObject({ query: _kopai_core.kopaiQuery.KopaiQuery });
317
+ /**
318
+ * The advertised input schema for the `query` tool, deduplicated into `$defs`.
319
+ *
320
+ * WHY generated here, at module scope, rather than inside the per-request
321
+ * server factory: the transport builds a fresh server per request, and
322
+ * generating plus deduplicating this document costs ~11 ms — around a hundred
323
+ * times a request's own work. The document depends on nothing request-scoped,
324
+ * so it is built once per process and shared.
325
+ */
326
+ const OVERRIDES = descriptionOverrides(LIMITS.raw.max, LIMITS.aggregate.max, LIMITS.raw.fallback, LIMITS.aggregate.fallback);
327
+ const described = applyDescriptions(zod.z.toJSONSchema(QueryToolInput, { io: "input" }), OVERRIDES);
328
+ /** How many nodes each override matched. Asserted in the tests, not at runtime. */
329
+ const DESCRIPTION_OVERRIDES_APPLIED = described.applied;
330
+ const QUERY_TOOL_INPUT_SCHEMA = dedupe(described.document);
331
+ /**
332
+ * The `metrics_discover` tool takes no arguments, but MCP still requires an
333
+ * object root.
334
+ */
335
+ const METRICS_DISCOVER_TOOL_INPUT_SCHEMA = {
336
+ type: "object",
337
+ properties: {}
338
+ };
339
+ //#endregion
340
+ //#region src/results.ts
341
+ /**
342
+ * Builds a result carrying `payload` in BOTH channels — as
343
+ * `structuredContent`, and as a single text block holding exactly
344
+ * `JSON.stringify` of the same object.
345
+ *
346
+ * WHY both, when the specification suggests one: the two consumers read
347
+ * different channels and neither reads both. A live page reads
348
+ * `structuredContent` through the artifact runtime's `payload` convenience. A
349
+ * conversational agent reads `content` — Anthropic's own MCP helper returns
350
+ * `result.content.map(...)` and discards `structuredContent` entirely whenever
351
+ * `content` is non-empty, falling back to the structured value only when
352
+ * `content` is empty. So rows in `structuredContent` plus a prose summary in
353
+ * the text block is the one combination that fails: the fallback never fires,
354
+ * and the agent receives the summary and none of the rows, with no error
355
+ * raised anywhere.
356
+ *
357
+ * Sending both costs wire bytes only, never context: a client forwards one
358
+ * channel or the other, so the model ingests the payload once. The text block
359
+ * stays pure JSON so that the "first text block parsed as JSON" path a page
360
+ * may fall back to remains valid.
361
+ */
362
+ function okResult(payload) {
363
+ return {
364
+ structuredContent: payload,
365
+ content: [{
366
+ type: "text",
367
+ text: JSON.stringify(payload)
368
+ }]
369
+ };
370
+ }
371
+ /**
372
+ * Builds a failed result. Same duplication as {@link okResult}, and more
373
+ * load-bearing here: the empty-content fallback to the structured value sits
374
+ * below the `isError` branch in the agent's helper, so it never fires on a
375
+ * failure. A structured-only success degrades; a structured-only error
376
+ * vanishes, leaving the agent an empty error and nothing to repair from.
377
+ *
378
+ * `error` is written first so the serialized JSON opens with the code.
379
+ */
380
+ function errorResult(payload) {
381
+ const ordered = {
382
+ error: payload.error,
383
+ message: payload.message
384
+ };
385
+ if (payload.issues !== void 0) ordered.issues = payload.issues;
386
+ if (payload.remedies !== void 0) ordered.remedies = payload.remedies;
387
+ return {
388
+ structuredContent: ordered,
389
+ content: [{
390
+ type: "text",
391
+ text: JSON.stringify(ordered)
392
+ }],
393
+ isError: true
394
+ };
395
+ }
396
+ /**
397
+ * Re-points issue paths from `@kopai/core`'s query-relative form onto the
398
+ * tool's input, whose single property is `query`. The empty root path becomes
399
+ * `query` rather than `query.`.
400
+ */
401
+ function prefixIssuePaths(issues) {
402
+ return issues.map(({ path, message }) => ({
403
+ path: path === "" ? "query" : `query.${path}`,
404
+ message
405
+ }));
406
+ }
407
+ //#endregion
408
+ //#region src/tools.ts
409
+ function invalidInput(message, issues) {
410
+ return {
411
+ result: errorResult({
412
+ error: "invalid_input",
413
+ message,
414
+ issues
415
+ }),
416
+ outcome: "invalid_input"
417
+ };
418
+ }
419
+ function tooLarge(message, remedies) {
420
+ return {
421
+ result: errorResult({
422
+ error: "result_too_large",
423
+ message,
424
+ remedies: [...remedies]
425
+ }),
426
+ outcome: "result_too_large"
427
+ };
428
+ }
429
+ /**
430
+ * Maps a thrown error onto an outcome, mirroring the REST error handler:
431
+ * a recognised validation error surfaces its own message, and anything
432
+ * unrecognised surfaces a generic string with the detail written to the log.
433
+ *
434
+ * WHY the log matters as much as the result: "The query could not be
435
+ * completed." is the whole of what a model can act on, and it is also the
436
+ * whole of what anyone got. A datasource that was refusing connections
437
+ * produced that one string for the caller and not a line for whoever runs the
438
+ * server — in a product whose purpose is making failures visible. The REST
439
+ * side has always logged this class of error (`error-handler.ts`); this is the
440
+ * same thing at the other entry point.
441
+ *
442
+ * A validation error is not logged: it is the caller's mistake, it is reported
443
+ * back in full, and logging every malformed query would bury the outages.
444
+ */
445
+ function fromThrown(error, logger) {
446
+ if (error instanceof _kopai_core.kopaiQueryCompiler.KopaiQueryValidationError) return invalidInput(error.message);
447
+ logger?.error(error, "MCP tool call failed");
448
+ return {
449
+ result: errorResult({
450
+ error: "upstream_error",
451
+ message: "The query could not be completed."
452
+ }),
453
+ outcome: "upstream_error"
454
+ };
455
+ }
456
+ /**
457
+ * The branch a query was judged against, when the pair selects one.
458
+ *
459
+ * WHY the message names it: the issues name fields, and the six shapes share
460
+ * field names — `measures` is on three of them, `filters` on all six. A caller
461
+ * told only `query.measures.0.column` does not know which shape its query was
462
+ * read as, and the `signal`/`mode` pair that decides that is the one thing it
463
+ * can get wrong without any issue pointing at it. Where the pair itself is
464
+ * wrong there is no branch to name, and the issues on `signal` and `mode` say
465
+ * so instead.
466
+ */
467
+ function branchOf(query) {
468
+ const { signal, mode } = query ?? {};
469
+ return _kopai_core.kopaiQuery.isSignal(signal) && _kopai_core.kopaiQuery.isQueryMode(mode) ? `${signal}/${mode}` : void 0;
470
+ }
471
+ /** Rows in a payload, for the observer. Aggregate and raw both key on `data`. */
472
+ function rowsOf(payload) {
473
+ const data = payload?.data;
474
+ return Array.isArray(data) ? data.length : void 0;
475
+ }
476
+ async function runQueryTool(input, ctx) {
477
+ if (typeof input !== "object" || input === null || Array.isArray(input)) return invalidInput("Expected an object with a `query` property.", [{
478
+ path: "query",
479
+ message: "Expected a query object."
480
+ }]);
481
+ const extraArgs = Object.keys(input).filter((key) => key !== "query");
482
+ if (extraArgs.length > 0) return invalidInput(`${extraArgs.map((key) => `\`${key}\``).join(", ")} ${extraArgs.length > 1 ? "are not arguments" : "is not an argument"} of this tool. \`query\` is the only one.`, extraArgs.map((key) => ({
483
+ path: key,
484
+ message: `Unknown argument. If it is a query field, it belongs at \`query.${key}\`.`
485
+ })));
486
+ const query_ = input.query;
487
+ const parsed = _kopai_core.kopaiQueryCompiler.parseKopaiQuery(query_);
488
+ if (!parsed.ok) {
489
+ const branch = branchOf(query_);
490
+ return invalidInput(branch ? `The ${branch} query is not valid.` : "The query is not valid.", prefixIssuePaths(parsed.issues));
491
+ }
492
+ const query = parsed.data;
493
+ const { fallback, max } = LIMITS[query.mode];
494
+ if (query.limit !== void 0 && query.limit > max) return invalidInput(`\`limit\` must be at most ${max} in ${query.mode} mode.`, [{
495
+ path: "query.limit",
496
+ message: `Expected at most ${max}, received ${query.limit}.`
497
+ }]);
498
+ const limit = query.limit ?? fallback;
499
+ const isAggregate = query.mode === "aggregate";
500
+ const probeLimit = isAggregate ? limit + 1 : limit;
501
+ let payload;
502
+ try {
503
+ payload = await ctx.readTelemetryDatasource.query({
504
+ ...query,
505
+ limit: probeLimit,
506
+ requestContext: ctx.requestContext
507
+ });
508
+ } catch (error) {
509
+ return fromThrown(error, ctx.logger);
510
+ }
511
+ if (isAggregate) {
512
+ if ((payload.data ?? []).length > limit) return tooLarge(`The query returned more than the ${limit} rows it asked for.`, overflowRemedies(query, limit, max));
513
+ }
514
+ const serialized = JSON.stringify(payload);
515
+ if (serialized.length > 15e4) return tooLarge(`The result serialized to ${serialized.length.toLocaleString("en-US")} characters, above the ${MAX_RESULT_CHARACTERS.toLocaleString("en-US")} the host will accept.`, SIZE_REMEDIES);
516
+ return {
517
+ result: okResult(payload),
518
+ outcome: "ok",
519
+ rowCount: rowsOf(payload)
520
+ };
521
+ }
522
+ function identityOf(metric) {
523
+ const { name, type, unit, description } = metric;
524
+ return {
525
+ name,
526
+ type,
527
+ ...unit === void 0 ? {} : { unit },
528
+ ...description === void 0 ? {} : { description }
529
+ };
530
+ }
531
+ /**
532
+ * The discovery listing, given up a piece at a time until it fits.
533
+ *
534
+ * WHY degrade rather than refuse: `metrics_discover` takes no arguments, so a
535
+ * caller handed `result_too_large` has nothing to change and no way to learn a
536
+ * metric name — which the `query` tool's own description tells them to do
537
+ * first. The values seen on each attribute are the bulk of the document and
538
+ * the metric names are the part that cannot be guessed, so they are given up in
539
+ * that order, and the response says which step was taken rather than leaving a
540
+ * thinner answer to pass as the whole one.
541
+ */
542
+ function degradations(full) {
543
+ return [
544
+ { payload: { ...full } },
545
+ {
546
+ omitted: "attributeValues",
547
+ payload: {
548
+ metrics: full.metrics.map((metric) => ({
549
+ ...identityOf(metric),
550
+ attributeKeys: Object.keys(metric.attributes?.values ?? {}),
551
+ resourceAttributeKeys: Object.keys(metric.resourceAttributes?.values ?? {})
552
+ })),
553
+ omitted: "attributeValues",
554
+ note: "The full listing was above the size limit, so the values seen on each attribute were dropped. The attribute keys are complete; query a metric grouped by a key to see its values."
555
+ }
556
+ },
557
+ {
558
+ omitted: "attributes",
559
+ payload: {
560
+ metrics: full.metrics.map(identityOf),
561
+ omitted: "attributes",
562
+ note: "The listing was above the size limit even without attribute values, so the attributes were dropped too. Every metric present is named; query one to see its attributes."
563
+ }
564
+ }
565
+ ];
566
+ }
567
+ async function runMetricsDiscoverTool(ctx) {
568
+ let full;
569
+ try {
570
+ full = await ctx.readTelemetryDatasource.discoverMetrics({ requestContext: ctx.requestContext });
571
+ } catch (error) {
572
+ return fromThrown(error, ctx.logger);
573
+ }
574
+ let serialized = "";
575
+ for (const stage of degradations(full)) {
576
+ serialized = JSON.stringify(stage.payload);
577
+ if (serialized.length <= 15e4) return {
578
+ result: okResult(stage.payload),
579
+ outcome: "ok",
580
+ rowCount: full.metrics.length
581
+ };
582
+ }
583
+ return tooLarge(`The listing of ${full.metrics.length.toLocaleString("en-US")} metrics serialized to ${serialized.length.toLocaleString("en-US")} characters even without their attributes, above the ${MAX_RESULT_CHARACTERS.toLocaleString("en-US")} the host will accept.`, DISCOVERY_SIZE_REMEDIES);
584
+ }
585
+ //#endregion
586
+ //#region src/validator.ts
587
+ /**
588
+ * A validator provider that accepts everything, so that the tool handler is
589
+ * what validates.
590
+ *
591
+ * Three reasons, and each would be sufficient on its own:
592
+ *
593
+ * 1. Correctness. The `query` schema is a union of six branches. The SDK's
594
+ * default validator rejects before dispatch and answers with one text line
595
+ * listing every branch's failures, which tells a model nothing about which
596
+ * field it got wrong. The handler instead selects the one branch the
597
+ * caller's `signal`/`mode` names and reports issues against it.
598
+ * 2. Cost. The default provider is AJV-backed and compiles the schema it is
599
+ * given. The transport builds a fresh server per request, so that
600
+ * compilation would happen on every call.
601
+ * 3. Observability. A rejection made before dispatch never reaches the
602
+ * handler, so it never reaches `onToolCall` — the counter would undercount
603
+ * exactly the failures most worth seeing.
604
+ *
605
+ * NOTE the shape: `fromJsonSchema`'s second argument is a provider object with
606
+ * a `getValidator` method, not a validator function. Passing a bare function
607
+ * throws `TypeError: validator.getValidator is not a function`, which the SDK
608
+ * swallows into a 500 on `initialize` — presenting as "the whole server is
609
+ * broken" rather than as a bad argument.
610
+ */
611
+ const passThroughValidator = { getValidator() {
612
+ return (input) => ({
613
+ valid: true,
614
+ data: input,
615
+ errorMessage: void 0
616
+ });
617
+ } };
618
+ //#endregion
619
+ //#region src/register.ts
620
+ /**
621
+ * Both tools read and never write, always return the same answer for the same
622
+ * arguments and window, and reach nothing outside this deployment.
623
+ */
624
+ const READ_ONLY = {
625
+ readOnlyHint: true,
626
+ idempotentHint: true,
627
+ openWorldHint: false
628
+ };
629
+ /**
630
+ * Descriptions are deliberately flat: what the tool does, the shape of its
631
+ * input, and the limits. They carry no instructions aimed at the model —
632
+ * these strings are read by Directory review, and a tool description is not a
633
+ * place to steer behaviour.
634
+ */
635
+ const QUERY_DESCRIPTION = [
636
+ "Query this workspace's OpenTelemetry traces, logs and metrics.",
637
+ "Takes one KopaiQuery object under `query`, keyed on `signal` (traces, logs, metrics) and `mode` (raw, aggregate); the rest of the shape follows from that pair.",
638
+ `Row caps are ${LIMITS.raw.max} in raw mode and ${LIMITS.aggregate.max} in aggregate mode, and a result above ${MAX_RESULT_CHARACTERS.toLocaleString("en-US")} characters is refused rather than truncated.`,
639
+ "Aggregate is the compact shape; raw returns whole records and is for inspecting individual spans, logs or data points.",
640
+ "An aggregate returns one row per distinct grouping, multiplied by the number of time buckets when `output` is a time series; that product is what the row cap applies to, not the number of records scanned.",
641
+ "Ranking over time takes two calls: a `summary` ordered by the measure to find the top groups, then a `timeSeries` filtered to those groups with `in`. One query cannot do both, because the ordering that picks them and the bucketing that draws them compete for the same `limit`.",
642
+ "For metrics, `metrics_discover` lists each metric's attribute keys and the values seen on them, which is how to judge a grouping column's cardinality before querying."
643
+ ].join(" ");
644
+ const METRICS_DISCOVER_DESCRIPTION = [
645
+ "List the metrics present in this workspace, with each metric's type, unit, description and the attribute keys and values seen on it.",
646
+ "Takes no arguments.",
647
+ `A listing above ${MAX_RESULT_CHARACTERS.toLocaleString("en-US")} characters is returned without its attribute values, or without its attributes, and the response names what was omitted.`
648
+ ].join(" ");
649
+ function registerTools(server, opts) {
650
+ const observe = (tool, startedAt, outcome, rowCount) => {
651
+ if (!opts.onToolCall) return;
652
+ try {
653
+ opts.onToolCall({
654
+ tool,
655
+ outcome,
656
+ durationMs: Date.now() - startedAt,
657
+ rowCount
658
+ });
659
+ } catch {}
660
+ };
661
+ /**
662
+ * Runs one tool call and reports it, whatever happens.
663
+ *
664
+ * WHY the catch: a throw out of a tool used to skip `observe` altogether, so
665
+ * the host's counter lost exactly the calls most worth seeing — and the SDK
666
+ * turned it into a bare message with no `structuredContent`, which is the
667
+ * one error shape a page cannot read. Nothing in the tools is expected to
668
+ * throw; that is the reason to handle it here rather than to assume it, and
669
+ * converting it gives an unexpected failure the same contract as an expected
670
+ * one: a structured payload, a logged cause, and one observer event.
671
+ */
672
+ const call = async (tool, execute) => {
673
+ const startedAt = Date.now();
674
+ let run;
675
+ try {
676
+ run = await execute();
677
+ } catch (error) {
678
+ run = fromThrown(error, opts.logger);
679
+ }
680
+ observe(tool, startedAt, run.outcome, run.rowCount);
681
+ return run.result;
682
+ };
683
+ server.registerTool("query", {
684
+ title: "Query telemetry",
685
+ description: QUERY_DESCRIPTION,
686
+ inputSchema: (0, _modelcontextprotocol_server.fromJsonSchema)(QUERY_TOOL_INPUT_SCHEMA, passThroughValidator),
687
+ annotations: READ_ONLY
688
+ }, async (input) => call("query", () => runQueryTool(input, opts)));
689
+ server.registerTool("metrics_discover", {
690
+ title: "Discover metrics",
691
+ description: METRICS_DISCOVER_DESCRIPTION,
692
+ inputSchema: (0, _modelcontextprotocol_server.fromJsonSchema)(METRICS_DISCOVER_TOOL_INPUT_SCHEMA, passThroughValidator),
693
+ annotations: READ_ONLY
694
+ }, async () => call("metrics_discover", () => runMetricsDiscoverTool(opts)));
695
+ }
696
+ //#endregion
697
+ //#region src/routes.ts
698
+ const SERVER_NAME = "kopai";
699
+ const SERVER_VERSION = "0.0.0";
700
+ /**
701
+ * Mounts the MCP endpoint at `/mcp`, relative to wherever this plugin is
702
+ * registered.
703
+ *
704
+ * The server is stateless: no session id, no server push, and a fresh
705
+ * `McpServer` per request.
706
+ */
707
+ const mcpRoutes = async function mcpRoutes(fastify, opts) {
708
+ fastify.addHook("onRequest", (0, _modelcontextprotocol_fastify.hostHeaderValidation)(opts.allowedHosts));
709
+ if (opts.allowedOriginHostnames !== void 0) {
710
+ if (!Array.isArray(opts.allowedOriginHostnames) || opts.allowedOriginHostnames.some((name) => typeof name !== "string")) throw new TypeError("allowedOriginHostnames must be an array of hostname strings, e.g. [\"localhost\", \"127.0.0.1\"]. Omit it to mount no origin validation.");
711
+ fastify.addHook("onRequest", (0, _modelcontextprotocol_fastify.originValidation)(opts.allowedOriginHostnames));
712
+ }
713
+ const handleMcp = async (request, reply) => {
714
+ if (request.method !== "POST") reply.raw.setHeader("Allow", "POST");
715
+ const handler = (0, _modelcontextprotocol_server.createMcpHandler)(() => {
716
+ const server = new _modelcontextprotocol_server.McpServer({
717
+ name: SERVER_NAME,
718
+ version: SERVER_VERSION
719
+ });
720
+ registerTools(server, {
721
+ readTelemetryDatasource: opts.readTelemetryDatasource,
722
+ requestContext: request.requestContext,
723
+ logger: opts.logger ?? request.log,
724
+ onToolCall: opts.onToolCall ? (event) => opts.onToolCall?.({
725
+ ...event,
726
+ request
727
+ }) : void 0
728
+ });
729
+ return server;
730
+ });
731
+ reply.hijack();
732
+ await (0, _modelcontextprotocol_node.toNodeHandler)(handler, { onerror: (error) => fastify.log.error(error) })(request.raw, reply.raw, request.body);
733
+ };
734
+ fastify.route({
735
+ method: "POST",
736
+ url: "/mcp",
737
+ handler: handleMcp
738
+ });
739
+ fastify.route({
740
+ method: "GET",
741
+ url: "/mcp",
742
+ handler: handleMcp
743
+ });
744
+ fastify.route({
745
+ method: "DELETE",
746
+ url: "/mcp",
747
+ handler: handleMcp
748
+ });
749
+ };
750
+ //#endregion
751
+ exports.DESCRIPTION_OVERRIDES_APPLIED = DESCRIPTION_OVERRIDES_APPLIED;
752
+ exports.DISCOVERY_SIZE_REMEDIES = DISCOVERY_SIZE_REMEDIES;
753
+ exports.LIMITS = LIMITS;
754
+ exports.MAX_RESULT_CHARACTERS = MAX_RESULT_CHARACTERS;
755
+ exports.METRICS_DISCOVER_TOOL_INPUT_SCHEMA = METRICS_DISCOVER_TOOL_INPUT_SCHEMA;
756
+ exports.QUERY_TOOL_INPUT_SCHEMA = QUERY_TOOL_INPUT_SCHEMA;
757
+ exports.SIZE_REMEDIES = SIZE_REMEDIES;
758
+ exports.applyDescriptions = applyDescriptions;
759
+ exports.dedupe = dedupe;
760
+ exports.descriptionOverrides = descriptionOverrides;
761
+ exports.errorResult = errorResult;
762
+ exports.mcpRoutes = mcpRoutes;
763
+ exports.okResult = okResult;
764
+ exports.overflowRemedies = overflowRemedies;
765
+ exports.passThroughValidator = passThroughValidator;
766
+ exports.prefixIssuePaths = prefixIssuePaths;
767
+ exports.registerTools = registerTools;
768
+ exports.runMetricsDiscoverTool = runMetricsDiscoverTool;
769
+ exports.runQueryTool = runQueryTool;