@kopai/mcp 0.4.3 → 0.5.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 CHANGED
@@ -2,6 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let _kopai_core = require("@kopai/core");
3
3
  let _modelcontextprotocol_server = require("@modelcontextprotocol/server");
4
4
  let zod = require("zod");
5
+ let node_buffer = require("node:buffer");
5
6
  let _modelcontextprotocol_fastify = require("@modelcontextprotocol/fastify");
6
7
  let _modelcontextprotocol_node = require("@modelcontextprotocol/node");
7
8
  // src/dedupe.ts
@@ -147,15 +148,37 @@ const LIMITS = {
147
148
  */
148
149
  const MAX_RESULT_CHARACTERS = 15e4;
149
150
  /**
150
- * Remedies for a discovery listing too large even with the attributes gone.
151
+ * Caps on `metrics_discover`'s string arguments, in Unicode code points: the
152
+ * unit JSON Schema's `maxLength` counts, so the advertised schema and the
153
+ * handler agree on what is too long. A UTF-16 count would refuse a 200-emoji
154
+ * `service` the schema had just accepted.
151
155
  *
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.
156
+ * The cursor cap leaves room for both filters at their caps, each character
157
+ * escaped at its longest, and a metric name of several thousand characters.
157
158
  */
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
+ const DISCOVER_ARGUMENT_LIMITS = {
160
+ service: 256,
161
+ nameContains: 255,
162
+ cursor: 16384
163
+ };
164
+ /**
165
+ * Remedies for a discovery answer that cannot be cut to fit: one overview row,
166
+ * or one metric with its description already dropped, is above
167
+ * {@link MAX_RESULT_CHARACTERS} on its own, or a page's cursor would be above
168
+ * the `cursor` cap in {@link DISCOVER_ARGUMENT_LIMITS}. Neither happens with
169
+ * real metric names; this is a guard, not a step.
170
+ *
171
+ * WHY its own list: every line in `SIZE_REMEDIES` names a field this tool does
172
+ * not have — a `limit`, a window, a `granularity`. Offering those turned an
173
+ * over-size listing into a dead end dressed up as advice. Its filters are the
174
+ * one thing a caller can change, and while paging they are also the only way
175
+ * past the entry that does not fit, which the caller is owed being told.
176
+ */
177
+ const DISCOVERY_SIZE_REMEDIES = [
178
+ "Filter with `service`, `metricType` or `nameContains` to leave out the entry that does not fit. While paging, the metrics after it can be reached only that way: following the cursor stops at it.",
179
+ "Query a metric by name with the `query` tool — discovery is not a prerequisite for it.",
180
+ "Ask an operator to look at what this deployment ingests: a metric name, description or `service.name` this large is not expected."
181
+ ];
159
182
  /**
160
183
  * ClickHouse error codes for a query stopped at a resource limit: 158
161
184
  * TOO_MANY_ROWS, 159 TIMEOUT_EXCEEDED, 160 TOO_SLOW (the estimated time
@@ -202,9 +225,12 @@ const RESOURCE_LIMIT_REMEDIES = [
202
225
  "For metrics, INCREASE, RATE and HISTOGRAM_QUANTILE read every data point in the window. When an exact increase or quantile is not needed, SUM, COUNT or MAX cost far less: on `Value` for Gauge and Sum metrics, on `Count` or `Sum` for Histogram metrics."
203
226
  ];
204
227
  /**
205
- * Remedies for a discovery listing stopped at a resource limit. Its own list
206
- * for the reason {@link DISCOVERY_SIZE_REMEDIES} is: the tool takes no
207
- * arguments, so there is no window or filter to offer.
228
+ * Remedies for a discovery listing stopped at a resource limit.
229
+ *
230
+ * WHY no filters here, though the tool has them: `metrics_discover` reads the
231
+ * whole listing on every call and filters it afterwards, in this package, so a
232
+ * filter makes the answer smaller but not the read. Suggesting one would send
233
+ * the caller round to the same failure. There is no window to narrow either.
208
234
  */
209
235
  const DISCOVERY_RESOURCE_LIMIT_REMEDIES = ["Query a metric by name with the `query` tool — discovery is not a prerequisite for it.", "Try again shortly: the listing may have run while this deployment was busy."];
210
236
  /** Remedies offered when a result is too large once serialized. */
@@ -377,12 +403,46 @@ const described = applyDescriptions(zod.z.toJSONSchema(QueryToolInput, { io: "in
377
403
  const DESCRIPTION_OVERRIDES_APPLIED = described.applied;
378
404
  const QUERY_TOOL_INPUT_SCHEMA = dedupe(described.document);
379
405
  /**
380
- * The `metrics_discover` tool takes no arguments, but MCP still requires an
381
- * object root.
406
+ * The `metrics_discover` tool's input: four optional string arguments.
407
+ *
408
+ * Written out rather than generated from zod: zod counts a string's length in
409
+ * UTF-16 units and JSON Schema's `maxLength` in code points, and the handler
410
+ * (`parseDiscoverArguments`) counts code points. It validates everything
411
+ * itself, so this document only advertises. The rule that a filter sent with
412
+ * `cursor` must equal the one it holds is the handler's alone: it would need
413
+ * a conditional at the root, which the Anthropic API refuses.
414
+ *
415
+ * The descriptions are flat for the reason the tool descriptions are; see
416
+ * `register.ts`.
382
417
  */
383
418
  const METRICS_DISCOVER_TOOL_INPUT_SCHEMA = {
384
419
  type: "object",
385
- properties: {}
420
+ properties: {
421
+ service: {
422
+ type: "string",
423
+ minLength: 1,
424
+ maxLength: DISCOVER_ARGUMENT_LIMITS.service,
425
+ description: "A `service.name` value, matched exactly. A metric keeps at most 100 `service.name` values, so one reported by more than 100 services may be missing. The attribute values listed for a metric come from every service that reports it, not only this one."
426
+ },
427
+ metricType: {
428
+ type: "string",
429
+ enum: [..._kopai_core.kopaiQuery.METRIC_TYPES],
430
+ description: "The metric's type, in exact case."
431
+ },
432
+ nameContains: {
433
+ type: "string",
434
+ minLength: 1,
435
+ maxLength: DISCOVER_ARGUMENT_LIMITS.nameContains,
436
+ description: "Text the metric's name contains, compared ignoring ASCII case. `%`, `_` and `\\` match themselves."
437
+ },
438
+ cursor: {
439
+ type: "string",
440
+ minLength: 1,
441
+ maxLength: DISCOVER_ARGUMENT_LIMITS.cursor,
442
+ description: "`nextCursor` from a previous response. The filters of the call that returned it apply; a filter sent with it must have the same value."
443
+ }
444
+ },
445
+ additionalProperties: false
386
446
  };
387
447
  // src/results.ts
388
448
  /**
@@ -451,6 +511,490 @@ function prefixIssuePaths(issues) {
451
511
  message
452
512
  }));
453
513
  }
514
+ // src/discover.ts
515
+ const FILTER_NAMES = [
516
+ "service",
517
+ "metricType",
518
+ "nameContains"
519
+ ];
520
+ const ARGUMENT_NAMES = [...FILTER_NAMES, "cursor"];
521
+ const METRIC_TYPES = _kopai_core.kopaiQuery.METRIC_TYPES;
522
+ /**
523
+ * The `note` on each answer that is not the listing in full. Each says what
524
+ * was left out and names the next call, because the answer alone cannot.
525
+ */
526
+ const DISCOVER_NOTES = {
527
+ overview: "The listing is above the size limit even without attributes, so this is an overview instead: the number of metrics for each `service.name` and type, with `service: null` counting the metrics that have no `service.name`. To list the metrics in a row, call again with its `service` and `metricType`; `metricType` alone also lists the metrics without a `service.name`, and `nameContains` narrows by name. A list too long for one answer comes back a page at a time.",
528
+ overviewCut: "The listing is above the size limit even without attributes, so this is an overview instead: the number of metrics for each `service.name` and type, with `service: null` counting the metrics that have no `service.name`. The overview is above the size limit too, so it holds only its largest rows; `totalRows` counts them all. To list the metrics in a row, call again with its `service` and `metricType`; `metricType` alone also lists the metrics in the rows left out here and those without a `service.name`, and `nameContains` narrows by name. A list too long for one answer comes back a page at a time.",
529
+ page: "The metrics matching these filters are above the size limit even without attributes, so they are listed without attributes, sorted by name and then type, a page at a time; `total` counts all of them. For the next page, call again with `cursor` set to `nextCursor`: the cursor keeps these filters. To see a metric's attributes, call with a `nameContains` narrow enough for the listing to fit.",
530
+ lastPage: "This is the last page of the metrics matching these filters, listed without attributes and sorted by name and then type; `total` counts all of them. To see a metric's attributes, call with a `nameContains` narrow enough for the listing to fit.",
531
+ pastTheEnd: "No metrics matching this cursor's filters are left after it: the ones that were left have stopped being listed since the previous page. Paging has ended. To list again from the start, call with the same filters and no `cursor`.",
532
+ nothingMatches: "No metric matches these filters. `service` must equal a `service.name` value exactly, and `nameContains` matches part of the name, ignoring ASCII case. Call again with fewer filters, or with none to see what exists."
533
+ };
534
+ const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
535
+ const code = (text) => `\`${text}\``;
536
+ /** "a", "a or b", "a, b or c". */
537
+ function listOf(items, conjunction) {
538
+ if (items.length <= 1) return items.join("");
539
+ return `${items.slice(0, -1).join(", ")} ${conjunction} ${items.at(-1)}`;
540
+ }
541
+ /**
542
+ * Lower-cases A to Z and nothing else: the folding SQLite's `LIKE` does, so
543
+ * `nameContains` matches what KopaiQuery's `contains` matches there.
544
+ */
545
+ const lowerAscii = (text) => text.replace(/[A-Z]+/g, (run) => run.toLowerCase());
546
+ /** What is wrong with one argument's value, or `undefined` if nothing is. */
547
+ function problemWith(name, value) {
548
+ if (name === "metricType") {
549
+ if (typeof value === "string" && METRIC_TYPES.includes(value)) return;
550
+ const expected = `Expected one of ${listOf(METRIC_TYPES, "or")}, in exact case`;
551
+ const meant = typeof value === "string" ? METRIC_TYPES.find((type) => lowerAscii(type) === lowerAscii(value)) : void 0;
552
+ return meant === void 0 ? `${expected}.` : `${expected}: did you mean "${meant}"?`;
553
+ }
554
+ if (typeof value !== "string") return "Expected a string.";
555
+ if (value === "") return "Expected a non-empty string. Leave the argument out rather than sending it empty.";
556
+ const max = DISCOVER_ARGUMENT_LIMITS[name];
557
+ const length = [...value].length;
558
+ if (length > max) return `Expected at most ${max.toLocaleString("en-US")} characters, received ${length.toLocaleString("en-US")}.`;
559
+ }
560
+ /** Built key by key, so the filters always serialize in the same order. */
561
+ function filtersOf(values) {
562
+ const filters = {};
563
+ if (typeof values.service === "string") filters.service = values.service;
564
+ if (typeof values.metricType === "string") filters.metricType = values.metricType;
565
+ if (typeof values.nameContains === "string") filters.nameContains = values.nameContains;
566
+ return filters;
567
+ }
568
+ const hasFilters = (filters) => Object.keys(filters).length > 0;
569
+ /**
570
+ * Bumped whenever what a cursor holds changes meaning. A cursor in any other
571
+ * version is refused rather than read the new way.
572
+ */
573
+ const CURSOR_VERSION = 1;
574
+ /**
575
+ * A cursor: base64url over JSON holding the format version, the call's
576
+ * filters and the last (name, type) its page returned.
577
+ *
578
+ * WHY the filters travel in the cursor: a cursor is a position in one sorted
579
+ * list, and under other filters that position means nothing. Holding them
580
+ * lets a call send the cursor alone, and lets the handler refuse a page asked
581
+ * for under different filters rather than skip or repeat metrics silently.
582
+ *
583
+ * WHY JSON inside: `JSON.stringify` escapes a lone surrogate, so any name or
584
+ * filter survives the trip through UTF-8 unchanged.
585
+ */
586
+ function encodeCursor(filters, last) {
587
+ const body = {
588
+ v: CURSOR_VERSION,
589
+ f: filters,
590
+ k: [last.name, last.type]
591
+ };
592
+ return node_buffer.Buffer.from(JSON.stringify(body), "utf8").toString("base64url");
593
+ }
594
+ const BASE64URL = /^[A-Za-z0-9_-]+$/;
595
+ function decodeCursor(cursor) {
596
+ if (!BASE64URL.test(cursor)) return "malformed";
597
+ let body;
598
+ try {
599
+ body = JSON.parse(node_buffer.Buffer.from(cursor, "base64url").toString("utf8"));
600
+ } catch {
601
+ return "malformed";
602
+ }
603
+ if (!isRecord$1(body)) return "malformed";
604
+ if (body.v !== CURSOR_VERSION) return typeof body.v === "number" ? "otherVersion" : "malformed";
605
+ const { f, k } = body;
606
+ if (!isRecord$1(f) || !Array.isArray(k) || k.length !== 2 || typeof k[0] !== "string" || typeof k[1] !== "string") return "malformed";
607
+ for (const [name, value] of Object.entries(f)) if (!FILTER_NAMES.includes(name) || problemWith(name, value) !== void 0) return "malformed";
608
+ return {
609
+ filters: filtersOf(f),
610
+ after: {
611
+ name: k[0],
612
+ type: k[1]
613
+ }
614
+ };
615
+ }
616
+ const sameFilter = (name, stored, sent) => name === "nameContains" ? lowerAscii(stored) === lowerAscii(sent) : stored === sent;
617
+ const START_OVER = "Repeat the first call's filters without `cursor` to list from the start.";
618
+ /**
619
+ * Validates `metrics_discover`'s input in full, cursor included, before
620
+ * anything is read.
621
+ *
622
+ * WHY here and not in the SDK: the validator is pass-through (see
623
+ * `validator.ts`), so nothing above this sees the input. The tool used to
624
+ * ignore its input altogether, which was harmless only while it had none.
625
+ */
626
+ function parseDiscoverArguments(input) {
627
+ const args = input ?? {};
628
+ if (!isRecord$1(args)) return {
629
+ ok: false,
630
+ message: "Expected an object of arguments, or no arguments."
631
+ };
632
+ const unknownKeys = Object.keys(args).filter((key) => !ARGUMENT_NAMES.includes(key));
633
+ const issues = unknownKeys.map((key) => ({
634
+ path: key,
635
+ message: "Unknown argument."
636
+ }));
637
+ const sent = {};
638
+ for (const name of ARGUMENT_NAMES) {
639
+ const value = args[name];
640
+ if (value === void 0 || value === null) continue;
641
+ const problem = problemWith(name, value);
642
+ if (problem === void 0) sent[name] = value;
643
+ else issues.push({
644
+ path: name,
645
+ message: problem
646
+ });
647
+ }
648
+ if (issues.length > 0) {
649
+ const arguments_ = listOf(ARGUMENT_NAMES.map(code), "and");
650
+ return {
651
+ ok: false,
652
+ message: unknownKeys.length > 0 ? `${listOf(unknownKeys.map(code), "and")} ${unknownKeys.length > 1 ? "are not arguments" : "is not an argument"} of this tool. Its arguments are ${arguments_}, all optional.` : "The arguments are not valid.",
653
+ issues
654
+ };
655
+ }
656
+ if (sent.cursor === void 0) return {
657
+ ok: true,
658
+ value: { filters: filtersOf(sent) }
659
+ };
660
+ const decoded = decodeCursor(sent.cursor);
661
+ if (decoded === "malformed") return {
662
+ ok: false,
663
+ message: `\`cursor\` is not a cursor this tool returned. ${START_OVER}`,
664
+ issues: [{
665
+ path: "cursor",
666
+ message: "Not a cursor this tool returned."
667
+ }]
668
+ };
669
+ if (decoded === "otherVersion") return {
670
+ ok: false,
671
+ message: `\`cursor\` was returned by another version of this tool. ${START_OVER}`,
672
+ issues: [{
673
+ path: "cursor",
674
+ message: `A cursor in another format version; this tool reads version ${CURSOR_VERSION}.`
675
+ }]
676
+ };
677
+ for (const name of FILTER_NAMES) {
678
+ const value = sent[name];
679
+ if (value === void 0) continue;
680
+ const stored = decoded.filters[name];
681
+ if (stored === void 0) issues.push({
682
+ path: "cursor",
683
+ message: `The call that returned this cursor had no \`${name}\`, so one cannot be added while paging.`
684
+ });
685
+ else if (!sameFilter(name, stored, value)) issues.push({
686
+ path: "cursor",
687
+ message: `The call that returned this cursor had \`${name}\` ${JSON.stringify(stored)}, not ${JSON.stringify(value)}.`
688
+ });
689
+ }
690
+ if (issues.length > 0) return {
691
+ ok: false,
692
+ message: "The filters sent with `cursor` differ from the ones it was returned for. Send `cursor` alone to continue, or start a new listing without it.",
693
+ issues
694
+ };
695
+ return {
696
+ ok: true,
697
+ value: decoded
698
+ };
699
+ }
700
+ function serviceNamesOf(metric) {
701
+ const values = metric.resourceAttributes?.values?.["service.name"];
702
+ return Array.isArray(values) ? values : [];
703
+ }
704
+ /**
705
+ * The number of values both datasources keep per attribute. ClickHouse's
706
+ * discover table itself holds no more (`groupUniqArray(101)`), so the rest of
707
+ * a metric's services are not known to discovery at all.
708
+ */
709
+ const SERVICE_NAMES_KEPT = 100;
710
+ /**
711
+ * Whether a metric's `service.name` values may have been cut at that cap.
712
+ * `_truncated` covers all of a metric's resource attributes, not one key, so a
713
+ * metric with exactly 100 services and another attribute cut passes too.
714
+ */
715
+ function servicesCut(metric) {
716
+ return metric.resourceAttributes?._truncated === true && serviceNamesOf(metric).length >= SERVICE_NAMES_KEPT;
717
+ }
718
+ /**
719
+ * Whether a metric passes every filter given.
720
+ *
721
+ * `service` is an exact match on one of the metric's `service.name` values.
722
+ * Both datasources keep at most 100 values per attribute, so a metric seen in
723
+ * more services than that may be missed; the argument's description says so,
724
+ * and so does the answer when nothing matches ({@link nothingMatches}).
725
+ */
726
+ function matcher(filters) {
727
+ const { service, metricType, nameContains } = filters;
728
+ const needle = nameContains === void 0 ? void 0 : lowerAscii(nameContains);
729
+ return (metric) => (metricType === void 0 || metric.type === metricType) && (service === void 0 || serviceNamesOf(metric).includes(service)) && (needle === void 0 || lowerAscii(metric.name).includes(needle));
730
+ }
731
+ /**
732
+ * Compares by UTF-16 code unit, which is what `<` does on strings.
733
+ *
734
+ * WHY not `localeCompare`: its order depends on the runtime's ICU data and
735
+ * locale, and two orders between pages would skip or repeat metrics.
736
+ */
737
+ const byCodeUnit = (a, b) => a < b ? -1 : a > b ? 1 : 0;
738
+ const byKey = (a, b) => byCodeUnit(a.name, b.name) || byCodeUnit(a.type, b.type);
739
+ /**
740
+ * Removes duplicate (name, type) entries, keeping the first, and sorts the
741
+ * rest by name and then type.
742
+ *
743
+ * WHY sort here rather than trust the datasource: SQLite returns insertion
744
+ * order and ClickHouse sorts by UTF-8 bytes, which disagrees with code units
745
+ * for characters past U+FFFF. A cursor is only a position in a fixed order.
746
+ */
747
+ function sortedUnique(metrics) {
748
+ const typesByName = /* @__PURE__ */ new Map();
749
+ const unique = [];
750
+ for (const metric of metrics) {
751
+ let types = typesByName.get(metric.name);
752
+ if (types === void 0) {
753
+ types = /* @__PURE__ */ new Set();
754
+ typesByName.set(metric.name, types);
755
+ }
756
+ if (types.has(metric.type)) continue;
757
+ types.add(metric.type);
758
+ unique.push(metric);
759
+ }
760
+ return unique.sort(byKey);
761
+ }
762
+ /** The index of the first metric that sorts strictly after `key`. */
763
+ function firstAfter(sorted, key) {
764
+ let low = 0;
765
+ let high = sorted.length;
766
+ while (low < high) {
767
+ const mid = low + high >>> 1;
768
+ if (byKey(sorted[mid], key) <= 0) low = mid + 1;
769
+ else high = mid;
770
+ }
771
+ return low;
772
+ }
773
+ function identityOf(metric) {
774
+ const { name, type, unit, description } = metric;
775
+ return {
776
+ name,
777
+ type,
778
+ ...unit === void 0 ? {} : { unit },
779
+ ...description === void 0 ? {} : { description }
780
+ };
781
+ }
782
+ function withoutDescription(entry) {
783
+ const { name, type, unit } = entry;
784
+ return {
785
+ name,
786
+ type,
787
+ ...unit === void 0 ? {} : { unit },
788
+ descriptionOmitted: true
789
+ };
790
+ }
791
+ const serializedLength = (value) => JSON.stringify(value).length;
792
+ const MAX = MAX_RESULT_CHARACTERS.toLocaleString("en-US");
793
+ /**
794
+ * The filtered call that matched nothing. It replaces the first step.
795
+ *
796
+ * WHY count the metrics whose services may have been cut: one reported by
797
+ * more than 100 services is matched against only the 100 discovery kept, so
798
+ * for a `service` filter an empty answer is not proof that the service reports
799
+ * none. The ones that pass the other filters are those it may have missed, and
800
+ * the note says how to list them rather than leave the empty answer to read as
801
+ * definite. It says "may": the cut flag does not name the attribute.
802
+ */
803
+ function nothingMatches(metrics, filters) {
804
+ const { service, ...others } = filters;
805
+ const passesOthers = matcher(others);
806
+ const missed = service === void 0 ? 0 : sortedUnique(metrics.filter((m) => servicesCut(m) && passesOthers(m))).length;
807
+ if (missed === 0) return {
808
+ metrics: [],
809
+ total: 0,
810
+ note: DISCOVER_NOTES.nothingMatches
811
+ };
812
+ const one = missed === 1;
813
+ const counted = one ? "1 metric" : `${missed.toLocaleString("en-US")} metrics`;
814
+ const matching = hasFilters(others) ? " matching the other filters" : "";
815
+ const them = one ? "it" : "them";
816
+ return {
817
+ metrics: [],
818
+ total: 0,
819
+ note: `No metric matches these filters. \`service\` must equal a \`service.name\` value exactly, and \`nameContains\` matches part of the name, ignoring ASCII case. But ${counted}${matching} may be reported by more than ${SERVICE_NAMES_KEPT} services, and only ${SERVICE_NAMES_KEPT} \`service.name\` values are kept for each, so this service may report ${them}. To list ${them}, call again without \`service\`, narrowing with \`metricType\` or \`nameContains\` instead.`
820
+ };
821
+ }
822
+ /**
823
+ * The overview: one row per (`service.name` value, type), counting the metrics
824
+ * of that type reported with that value.
825
+ *
826
+ * A metric with several values counts in each of their rows, so the rows add
827
+ * up to more than `metricCount`. One with none, or only empty ones, counts in
828
+ * its type's `service: null` row. Duplicate (name, type) entries count once,
829
+ * with their values merged.
830
+ */
831
+ function overviewRows(metrics) {
832
+ const servicesByMetric = /* @__PURE__ */ new Map();
833
+ for (const metric of metrics) {
834
+ const key = JSON.stringify([metric.name, metric.type]);
835
+ let entry = servicesByMetric.get(key);
836
+ if (entry === void 0) {
837
+ entry = {
838
+ type: metric.type,
839
+ services: /* @__PURE__ */ new Set()
840
+ };
841
+ servicesByMetric.set(key, entry);
842
+ }
843
+ for (const service of serviceNamesOf(metric)) if (service !== "") entry.services.add(service);
844
+ }
845
+ const rows = /* @__PURE__ */ new Map();
846
+ for (const { type, services } of servicesByMetric.values()) for (const service of services.size > 0 ? services : [null]) {
847
+ const key = JSON.stringify([service, type]);
848
+ const row = rows.get(key);
849
+ if (row === void 0) rows.set(key, {
850
+ service,
851
+ type,
852
+ count: 1
853
+ });
854
+ else row.count += 1;
855
+ }
856
+ const byService = (a, b) => a === b ? 0 : a === null ? 1 : b === null ? -1 : byCodeUnit(a, b);
857
+ return {
858
+ rows: [...rows.values()].sort((a, b) => b.count - a.count || byService(a.service, b.service) || byCodeUnit(a.type, b.type)),
859
+ metricCount: servicesByMetric.size
860
+ };
861
+ }
862
+ /**
863
+ * The answer to a call with no arguments whose listing does not fit even
864
+ * without attributes.
865
+ *
866
+ * WHY counts rather than the first names that fit: a caller asking "what
867
+ * metrics are there" on a large workspace needs to know where to look next,
868
+ * and an arbitrary slice of names answers a different question. Every row
869
+ * names the filters that list it.
870
+ */
871
+ function overviewAnswer(metrics) {
872
+ const { rows, metricCount } = overviewRows(metrics);
873
+ const whole = {
874
+ overview: rows,
875
+ omitted: "metrics",
876
+ metricCount,
877
+ totalRows: rows.length,
878
+ note: DISCOVER_NOTES.overview
879
+ };
880
+ if (serializedLength(whole) <= 15e4) return {
881
+ ok: true,
882
+ payload: whole,
883
+ rowCount: rows.length
884
+ };
885
+ const cut = (kept) => ({
886
+ overview: kept,
887
+ omitted: "metrics",
888
+ truncated: true,
889
+ metricCount,
890
+ totalRows: rows.length,
891
+ note: DISCOVER_NOTES.overviewCut
892
+ });
893
+ let used = serializedLength(cut([]));
894
+ let count = 0;
895
+ for (const row of rows) {
896
+ used += serializedLength(row) + (count > 0 ? 1 : 0);
897
+ if (used > 15e4) break;
898
+ count += 1;
899
+ }
900
+ if (count === 0) return {
901
+ ok: false,
902
+ message: `The overview's first row, a \`service.name\` of ${[...rows[0]?.service ?? ""].length.toLocaleString("en-US")} characters, is above the ${MAX} characters the host will accept on its own.`
903
+ };
904
+ return {
905
+ ok: true,
906
+ payload: cut(rows.slice(0, count)),
907
+ rowCount: count
908
+ };
909
+ }
910
+ const page = (metrics, total, nextCursor, note) => ({
911
+ metrics,
912
+ omitted: "attributes",
913
+ truncated: true,
914
+ total,
915
+ nextCursor,
916
+ note
917
+ });
918
+ /**
919
+ * The longest run of entries from `start` that fits with its cursor, or
920
+ * `undefined` if not even one does.
921
+ *
922
+ * WHY the longest that fits rather than the first run that stops fitting: the
923
+ * cursor's length depends on the last entry's name, so a page that does not
924
+ * fit ending at one metric can still fit ending at the next. A page may end
925
+ * anywhere, a name's types included — the cursor holds the type too.
926
+ */
927
+ function fitPage(sorted, start, filters, first) {
928
+ const total = sorted.length;
929
+ const lastIndex = total - 1;
930
+ const shellMore = serializedLength(page([], total, "", DISCOVER_NOTES.page));
931
+ const shellLast = serializedLength(page([], total, null, DISCOVER_NOTES.lastPage));
932
+ const entries = [];
933
+ let used = 0;
934
+ let best;
935
+ for (let i = start; i <= lastIndex; i++) {
936
+ const metric = sorted[i];
937
+ const entry = i === start ? first : identityOf(metric);
938
+ used += serializedLength(entry) + (entries.length > 0 ? 1 : 0);
939
+ if (Math.min(shellMore, shellLast) + used > 15e4) break;
940
+ entries.push(entry);
941
+ if (i === lastIndex) {
942
+ if (shellLast + used <= 15e4) best = {
943
+ count: entries.length,
944
+ nextCursor: null
945
+ };
946
+ continue;
947
+ }
948
+ const cursor = encodeCursor(filters, metric);
949
+ if (cursor.length <= DISCOVER_ARGUMENT_LIMITS.cursor && shellMore + cursor.length + used <= 15e4) best = {
950
+ count: entries.length,
951
+ nextCursor: cursor
952
+ };
953
+ }
954
+ return best && {
955
+ entries: entries.slice(0, best.count),
956
+ nextCursor: best.nextCursor
957
+ };
958
+ }
959
+ /**
960
+ * One page of a cut list: the metrics matching the filters, without
961
+ * attributes, sorted, from just after `after` (or the start) for as many as
962
+ * fit.
963
+ *
964
+ * `sorted` comes from {@link sortedUnique}. `truncated` is on every page, the
965
+ * last included, because each holds fewer metrics than match; paging ends
966
+ * when `nextCursor` is `null`.
967
+ *
968
+ * A page holds at least one metric while any remain. When the next one does
969
+ * not fit on its own, its description is dropped and it carries
970
+ * `descriptionOmitted: true`; when it still does not fit, or its cursor would
971
+ * be above the cap, there is no page, and the caller refuses.
972
+ */
973
+ function pageAnswer(sorted, filters, after) {
974
+ const total = sorted.length;
975
+ const start = after === void 0 ? 0 : firstAfter(sorted, after);
976
+ const next = sorted[start];
977
+ if (next === void 0) return {
978
+ ok: true,
979
+ payload: page([], total, null, DISCOVER_NOTES.pastTheEnd),
980
+ rowCount: 0
981
+ };
982
+ const first = identityOf(next);
983
+ const fitted = fitPage(sorted, start, filters, first) ?? (first.description === void 0 ? void 0 : fitPage(sorted, start, filters, withoutDescription(first)));
984
+ if (fitted === void 0) {
985
+ const alone = serializedLength(page([withoutDescription(first)], total, null, DISCOVER_NOTES.page));
986
+ const cursorTooLong = encodeCursor(filters, next).length > DISCOVER_ARGUMENT_LIMITS.cursor;
987
+ return {
988
+ ok: false,
989
+ message: alone > 15e4 ? `The next metric serialized to ${serializedLength(withoutDescription(first)).toLocaleString("en-US")} characters even without its description, above the ${MAX} the host will accept.` : cursorTooLong ? `The next metric's name is ${[...next.name].length.toLocaleString("en-US")} characters long, too long for a cursor of at most ${DISCOVER_ARGUMENT_LIMITS.cursor.toLocaleString("en-US")} characters, so the listing cannot be paged past it.` : `The next metric, without its description, and the cursor after it are together above the ${MAX} the host will accept, and the metrics after it do not fit beside it, so no page can hold it.`
990
+ };
991
+ }
992
+ return {
993
+ ok: true,
994
+ payload: page(fitted.entries, total, fitted.nextCursor, fitted.nextCursor === null ? DISCOVER_NOTES.lastPage : DISCOVER_NOTES.page),
995
+ rowCount: fitted.entries.length
996
+ };
997
+ }
454
998
  // src/tools.ts
455
999
  function invalidInput(message, issues) {
456
1000
  return {
@@ -510,8 +1054,8 @@ function tooExpensive(message, remedies) {
510
1054
  * resource limit is logged: it is the caller's query, but which queries the
511
1055
  * datasource cannot afford is for whoever runs it to know.
512
1056
  *
513
- * `limitRemedies` is for `metrics_discover`, which takes no arguments and so
514
- * cannot narrow a window.
1057
+ * `limitRemedies` is for `metrics_discover`, which has no window to narrow,
1058
+ * and whose filters do not make the read cheaper.
515
1059
  */
516
1060
  function fromThrown(error, logger, limitRemedies = RESOURCE_LIMIT_REMEDIES) {
517
1061
  if (error instanceof _kopai_core.kopaiQueryCompiler.KopaiQueryValidationError) return invalidInput(error.message);
@@ -591,25 +1135,18 @@ async function runQueryTool(input, ctx) {
591
1135
  rowCount: rowsOf(payload)
592
1136
  };
593
1137
  }
594
- function identityOf(metric) {
595
- const { name, type, unit, description } = metric;
596
- return {
597
- name,
598
- type,
599
- ...unit === void 0 ? {} : { unit },
600
- ...description === void 0 ? {} : { description }
601
- };
602
- }
603
1138
  /**
604
1139
  * The discovery listing, given up a piece at a time until it fits.
605
1140
  *
606
- * WHY degrade rather than refuse: `metrics_discover` takes no arguments, so a
607
- * caller handed `result_too_large` has nothing to change and no way to learn a
608
- * metric name — which the `query` tool's own description tells them to do
609
- * first. The values seen on each attribute are the bulk of the document and
610
- * the metric names are the part that cannot be guessed, so they are given up in
611
- * that order, and the response says which step was taken rather than leaving a
612
- * thinner answer to pass as the whole one.
1141
+ * WHY degrade rather than refuse: a caller handed `result_too_large` has no
1142
+ * way to learn a metric name — which the `query` tool's own description tells
1143
+ * them to do first. The values seen on each attribute are the bulk of the
1144
+ * document and the metric names are the part that cannot be guessed, so they
1145
+ * are given up in that order, and the response says which step was taken
1146
+ * rather than leaving a thinner answer to pass as the whole one.
1147
+ *
1148
+ * Each step keeps the datasource's order. When even the last one does not
1149
+ * fit, the caller gets an overview or a page of a cut list (`discover.ts`).
613
1150
  */
614
1151
  function degradations(full) {
615
1152
  return [
@@ -636,23 +1173,56 @@ function degradations(full) {
636
1173
  }
637
1174
  ];
638
1175
  }
639
- async function runMetricsDiscoverTool(ctx) {
1176
+ function discoverAnswered(answer, detail) {
1177
+ if (!answer.ok) return tooLarge(answer.message, DISCOVERY_SIZE_REMEDIES);
1178
+ return {
1179
+ result: okResult(answer.payload),
1180
+ outcome: "ok",
1181
+ rowCount: answer.rowCount,
1182
+ detail
1183
+ };
1184
+ }
1185
+ /**
1186
+ * Lists the metrics in this workspace, filtered by `service`, `metricType`
1187
+ * and `nameContains` when given, and paged by `cursor`.
1188
+ *
1189
+ * In order: the listing, through the steps in {@link degradations}, for a call
1190
+ * without a cursor; then, when no step fits, an overview for a call with no
1191
+ * filters and the first page of a cut list for one with filters. A call with
1192
+ * a cursor always gets a page.
1193
+ */
1194
+ async function runMetricsDiscoverTool(input, ctx) {
1195
+ const parsed = parseDiscoverArguments(input);
1196
+ if (!parsed.ok) return invalidInput(parsed.message, parsed.issues);
1197
+ const { filters, after } = parsed.value;
640
1198
  let full;
641
1199
  try {
642
1200
  full = await ctx.readTelemetryDatasource.discoverMetrics({ requestContext: ctx.requestContext });
643
1201
  } catch (error) {
644
1202
  return fromThrown(error, ctx.logger, DISCOVERY_RESOURCE_LIMIT_REMEDIES);
645
1203
  }
646
- let serialized = "";
647
- for (const stage of degradations(full)) {
648
- serialized = JSON.stringify(stage.payload);
649
- if (serialized.length <= 15e4) return {
1204
+ const filtered = hasFilters(filters);
1205
+ const matching = filtered ? full.metrics.filter(matcher(filters)) : full.metrics;
1206
+ if (after === void 0) {
1207
+ if (filtered && matching.length === 0) return {
1208
+ result: okResult(nothingMatches(full.metrics, filters)),
1209
+ outcome: "ok",
1210
+ rowCount: 0,
1211
+ detail: "full"
1212
+ };
1213
+ const listing = filtered ? {
1214
+ ...full,
1215
+ metrics: matching
1216
+ } : full;
1217
+ for (const stage of degradations(listing)) if (JSON.stringify(stage.payload).length <= 15e4) return {
650
1218
  result: okResult(stage.payload),
651
1219
  outcome: "ok",
652
- rowCount: full.metrics.length
1220
+ rowCount: matching.length,
1221
+ detail: stage.omitted ?? "full"
653
1222
  };
1223
+ if (!filtered) return discoverAnswered(overviewAnswer(full.metrics), "overview");
654
1224
  }
655
- 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);
1225
+ return discoverAnswered(pageAnswer(sortedUnique(matching), filters, after), "truncated");
656
1226
  }
657
1227
  // src/types.ts
658
1228
  /**
@@ -676,6 +1246,28 @@ const TOOL_CALL_OUTCOMES = [
676
1246
  "not_found",
677
1247
  "forbidden"
678
1248
  ];
1249
+ /**
1250
+ * How much of the listing an `ok` `metrics_discover` answer carries:
1251
+ *
1252
+ * - `full`, `attributeValues`, `attributes`: the listing, whole or with that
1253
+ * part omitted to fit the size limit, with or without filters. `full` also
1254
+ * covers a filtered call that matched nothing.
1255
+ * - `overview`: counts per `service.name` and type instead of the listing,
1256
+ * whether or not the overview itself was cut.
1257
+ * - `truncated`: one page of a list cut to fit, including the last page and an
1258
+ * empty one.
1259
+ *
1260
+ * WHY on the event: an `ok` from this tool ranges from everything to a count
1261
+ * per service, and the outcome alone cannot tell a host how often callers get
1262
+ * which.
1263
+ */
1264
+ const TOOL_CALL_DETAILS = [
1265
+ "full",
1266
+ "attributeValues",
1267
+ "attributes",
1268
+ "overview",
1269
+ "truncated"
1270
+ ];
679
1271
  // src/validator.ts
680
1272
  /**
681
1273
  * A validator provider that accepts everything, so that the tool handler is
@@ -740,12 +1332,13 @@ const QUERY_DESCRIPTION = [
740
1332
  "Aggregate is the compact shape; raw returns whole records and is for inspecting individual spans, logs or data points.",
741
1333
  "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.",
742
1334
  "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`.",
743
- "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."
1335
+ "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; on a large workspace it does so for a call whose filters narrow the listing enough to fit."
744
1336
  ].join(" ");
745
1337
  const METRICS_DISCOVER_DESCRIPTION = [
746
1338
  "List the metrics present in this workspace, with each metric's type, unit, description and the attribute keys and values seen on it.",
747
- "Takes no arguments.",
748
- `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.`
1339
+ "All arguments are optional: `service`, `metricType` and `nameContains` filter the listing, and a metric is listed when it matches every filter given.",
1340
+ `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.`,
1341
+ "When it does not fit even without attributes, a call with no arguments returns an overview instead, the number of metrics for each `service.name` and type, and a filtered call returns the matching metrics without attributes, sorted by name and type, in pages linked by `nextCursor`."
749
1342
  ].join(" ");
750
1343
  /** The tools this package registers itself. A host tool may not reuse them. */
751
1344
  const BUILT_IN_TOOL_NAMES = ["query", "metrics_discover"];
@@ -763,14 +1356,15 @@ const BUILT_IN_TOOL_NAMES = ["query", "metrics_discover"];
763
1356
  * one: a structured payload, a logged cause, and one observer event.
764
1357
  */
765
1358
  function observedCall(opts) {
766
- const observe = (tool, startedAt, outcome, rowCount) => {
1359
+ const observe = (tool, startedAt, { outcome, rowCount, detail }) => {
767
1360
  if (!opts.onToolCall) return;
768
1361
  try {
769
1362
  opts.onToolCall({
770
1363
  tool,
771
1364
  outcome,
772
1365
  durationMs: Date.now() - startedAt,
773
- ...rowCount !== void 0 ? { rowCount } : {}
1366
+ ...rowCount !== void 0 ? { rowCount } : {},
1367
+ ...detail !== void 0 ? { detail } : {}
774
1368
  });
775
1369
  } catch {}
776
1370
  };
@@ -782,7 +1376,7 @@ function observedCall(opts) {
782
1376
  } catch (error) {
783
1377
  run = fromThrown(error, opts.logger);
784
1378
  }
785
- observe(tool, startedAt, run.outcome, run.rowCount);
1379
+ observe(tool, startedAt, run);
786
1380
  return run.result;
787
1381
  };
788
1382
  }
@@ -811,7 +1405,7 @@ function registerTools(server, opts) {
811
1405
  ...READ_ONLY,
812
1406
  title: "Discover metrics"
813
1407
  }
814
- }, async () => call("metrics_discover", () => runMetricsDiscoverTool(opts)));
1408
+ }, async (input) => call("metrics_discover", () => runMetricsDiscoverTool(input, opts)));
815
1409
  }
816
1410
  const ERROR_CODES = new Set(TOOL_CALL_OUTCOMES.filter((outcome) => outcome !== "ok"));
817
1411
  const isRecord = (value) => typeof value === "object" && value !== null;
@@ -1033,11 +1627,13 @@ const mcpRoutes = async function mcpRoutes(fastify, opts) {
1033
1627
  exports.BUILT_IN_TOOL_NAMES = BUILT_IN_TOOL_NAMES;
1034
1628
  exports.DESCRIPTION_OVERRIDES_APPLIED = DESCRIPTION_OVERRIDES_APPLIED;
1035
1629
  exports.DISCOVERY_SIZE_REMEDIES = DISCOVERY_SIZE_REMEDIES;
1630
+ exports.DISCOVER_ARGUMENT_LIMITS = DISCOVER_ARGUMENT_LIMITS;
1036
1631
  exports.LIMITS = LIMITS;
1037
1632
  exports.MAX_RESULT_CHARACTERS = MAX_RESULT_CHARACTERS;
1038
1633
  exports.METRICS_DISCOVER_TOOL_INPUT_SCHEMA = METRICS_DISCOVER_TOOL_INPUT_SCHEMA;
1039
1634
  exports.QUERY_TOOL_INPUT_SCHEMA = QUERY_TOOL_INPUT_SCHEMA;
1040
1635
  exports.SIZE_REMEDIES = SIZE_REMEDIES;
1636
+ exports.TOOL_CALL_DETAILS = TOOL_CALL_DETAILS;
1041
1637
  exports.TOOL_CALL_OUTCOMES = TOOL_CALL_OUTCOMES;
1042
1638
  exports.applyDescriptions = applyDescriptions;
1043
1639
  exports.dedupe = dedupe;