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