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