@kopai/mcp 0.4.1 → 0.4.3

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
@@ -716,9 +716,14 @@ const passThroughValidator = { getValidator() {
716
716
  * Each tool repeats its `title` inside `annotations`: the 2025-03-26 spec has
717
717
  * no top-level tool `title`, so clients and checks built on it (including the
718
718
  * Claude connector directory check) read it only from there.
719
+ *
720
+ * `destructiveHint` is stated even though the spec ignores it when
721
+ * `readOnlyHint` is true: OpenAI's plugin review requires `readOnlyHint`,
722
+ * `destructiveHint` and `openWorldHint` as explicit booleans on every tool.
719
723
  */
720
724
  const READ_ONLY = {
721
725
  readOnlyHint: true,
726
+ destructiveHint: false,
722
727
  idempotentHint: true,
723
728
  openWorldHint: false
724
729
  };
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":["SchemaNode","McpServer","McpServer"],"sources":["../src/dedupe.ts","../src/limits.ts","../src/types.ts","../src/results.ts","../src/tools.ts","../src/register.ts","../src/routes.ts","../src/describe.ts","../src/schema.ts","../src/validator.ts"],"mappings":";;;KAoBKA,eAAa;;;;;;;;;;wBAkFF,OAAO,KAAKA,cAAY,kBAAcA;;;;;;;;;;;;;;;;;;;;;;;;qBC7EzC;;;;;;;;;;;;;;;;;;;;;;;;qBAyBA;;;;;;;;;;qBAWA;;qBAkEA;;;;;;;;;;;;;;;;;;wBA6EG,iBACd,OAAO,WAAW,YAClB,eACA;;;;;;;;;;;;;qBC/LW;KAUD,0BAA0B;;;;;;;;;UAUrB;EACf,MAAM,kBAAkB;;;;;;;;;;UAWT;EACf;EACA,SAAS;EACT;;EAEA;EACA,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAkCM;;;;;;;EAOf;;;;;;;;;;;;;;;EAeA,WAAW,QAAQC,aAAW,SAAS;;UAGxB;EACf,yBAAyB,WAAW;;;;;;EAMpC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+BA;;;;;EAKA,SAAS;;EAET,cAAc,OAAO;;EAErB,YAAY;;;YAQF;IACR;;;;KCtKQ,gBAAgB,QAAQ;UAEnB;EACf;EACA;;UAGe;EACf,OAAO;EACP;EACA,SAAS;EACT;;;;;;;KAQU;EACV;EACA,SAAS;IAAQ;IAAc;;EAC/B;;;;;;;;;;;;;;;;;;;;;;;wBAwBc,SAAS,mBAAmB;;;;;;;;;;wBAgB5B,YAAY,SAAS,mBAAmB;;;;;;wBAsBxC,iBAAiB,QAAQ,cAAc;UCnEtC;EACf,yBAAyB,WAAW;;EAEpC;;EAEA,SAAS;;;;;;;UAQM;EACf,QAAQ;EACR,SAAS;EACT;;wBAwHoB,aACpB,gBACA,KAAK,cACJ,QAAQ;wBA4LW,uBACpB,KAAK,cACJ,QAAQ;;qBCvRE;UAEI,6BAA6B;;;;;EAK5C,cAAc;IACZ;IACA,SAAS;IACT;IACA;;;;;;;;;wBAoEY,cACd,QAAQC,aACR,MAAM;;;;;;;;qBCjFK,WAAW,mBAAmB;KCnDtC,aAAa;UAED;;WAEN;;WAEA;WACA;;wBAGK,qBACd,gBACA,sBACA,oBACA,2BACC;;;;;wBAwBa,kBACd,KAAK,YACL,oBAAoB;EACjB,UAAU;EAAY,SAAS;;;qBCpBvB,+BAA6B;qBAE7B,yBAAyB;;;;;qBAQzB,oCAAoC;;;;;;;;;;;;;;;;;;;;;;;;;qBCtBpC,sBAAsB"}
1
+ {"version":3,"file":"index.d.cts","names":["SchemaNode","McpServer","McpServer"],"sources":["../src/dedupe.ts","../src/limits.ts","../src/types.ts","../src/results.ts","../src/tools.ts","../src/register.ts","../src/routes.ts","../src/describe.ts","../src/schema.ts","../src/validator.ts"],"mappings":";;;KAoBKA,eAAa;;;;;;;;;;wBAkFF,OAAO,KAAKA,cAAY,kBAAcA;;;;;;;;;;;;;;;;;;;;;;;;qBC7EzC;;;;;;;;;;;;;;;;;;;;;;;;qBAyBA;;;;;;;;;;qBAWA;;qBAkEA;;;;;;;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BpC,sBAAsB"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":["SchemaNode","McpServer","McpServer"],"sources":["../src/dedupe.ts","../src/limits.ts","../src/types.ts","../src/results.ts","../src/tools.ts","../src/register.ts","../src/routes.ts","../src/describe.ts","../src/schema.ts","../src/validator.ts"],"mappings":";;;KAoBKA,eAAa;;;;;;;;;;wBAkFF,OAAO,KAAKA,cAAY,kBAAcA;;;;;;;;;;;;;;;;;;;;;;;;qBC7EzC;;;;;;;;;;;;;;;;;;;;;;;;qBAyBA;;;;;;;;;;qBAWA;;qBAkEA;;;;;;;;;;;;;;;;;;wBA6EG,iBACd,OAAO,WAAW,YAClB,eACA;;;;;;;;;;;;;qBC/LW;KAUD,0BAA0B;;;;;;;;;UAUrB;EACf,MAAM,kBAAkB;;;;;;;;;;UAWT;EACf;EACA,SAAS;EACT;;EAEA;EACA,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAkCM;;;;;;;EAOf;;;;;;;;;;;;;;;EAeA,WAAW,QAAQC,aAAW,SAAS;;UAGxB;EACf,yBAAyB,WAAW;;;;;;EAMpC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+BA;;;;;EAKA,SAAS;;EAET,cAAc,OAAO;;EAErB,YAAY;;;YAQF;IACR;;;;KCtKQ,gBAAgB,QAAQ;UAEnB;EACf;EACA;;UAGe;EACf,OAAO;EACP;EACA,SAAS;EACT;;;;;;;KAQU;EACV;EACA,SAAS;IAAQ;IAAc;;EAC/B;;;;;;;;;;;;;;;;;;;;;;;wBAwBc,SAAS,mBAAmB;;;;;;;;;;wBAgB5B,YAAY,SAAS,mBAAmB;;;;;;wBAsBxC,iBAAiB,QAAQ,cAAc;UCnEtC;EACf,yBAAyB,WAAW;;EAEpC;;EAEA,SAAS;;;;;;;UAQM;EACf,QAAQ;EACR,SAAS;EACT;;wBAwHoB,aACpB,gBACA,KAAK,cACJ,QAAQ;wBA4LW,uBACpB,KAAK,cACJ,QAAQ;;qBCvRE;UAEI,6BAA6B;;;;;EAK5C,cAAc;IACZ;IACA,SAAS;IACT;IACA;;;;;;;;;wBAoEY,cACd,QAAQC,aACR,MAAM;;;;;;;;qBCjFK,WAAW,mBAAmB;KCnDtC,aAAa;UAED;;WAEN;;WAEA;WACA;;wBAGK,qBACd,gBACA,sBACA,oBACA,2BACC;;;;;wBAwBa,kBACd,KAAK,YACL,oBAAoB;EACjB,UAAU;EAAY,SAAS;;;qBCpBvB,+BAA6B;qBAE7B,yBAAyB;;;;;qBAQzB,oCAAoC;;;;;;;;;;;;;;;;;;;;;;;;;qBCtBpC,sBAAsB"}
1
+ {"version":3,"file":"index.d.mts","names":["SchemaNode","McpServer","McpServer"],"sources":["../src/dedupe.ts","../src/limits.ts","../src/types.ts","../src/results.ts","../src/tools.ts","../src/register.ts","../src/routes.ts","../src/describe.ts","../src/schema.ts","../src/validator.ts"],"mappings":";;;KAoBKA,eAAa;;;;;;;;;;wBAkFF,OAAO,KAAKA,cAAY,kBAAcA;;;;;;;;;;;;;;;;;;;;;;;;qBC7EzC;;;;;;;;;;;;;;;;;;;;;;;;qBAyBA;;;;;;;;;;qBAWA;;qBAkEA;;;;;;;;;;;;;;;;;;wBA6EG,iBACd,OAAO,WAAW,YAClB,eACA;;;;;;;;;;;;;qBC/LW;KAUD,0BAA0B;;;;;;;;;UAUrB;EACf,MAAM,kBAAkB;;;;;;;;;;UAWT;EACf;EACA,SAAS;EACT;;EAEA;EACA,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAkCM;;;;;;;EAOf;;;;;;;;;;;;;;;EAeA,WAAW,QAAQC,aAAW,SAAS;;UAGxB;EACf,yBAAyB,WAAW;;;;;;EAMpC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+BA;;;;;EAKA,SAAS;;EAET,cAAc,OAAO;;EAErB,YAAY;;;YAQF;IACR;;;;KCtKQ,gBAAgB,QAAQ;UAEnB;EACf;EACA;;UAGe;EACf,OAAO;EACP;EACA,SAAS;EACT;;;;;;;KAQU;EACV;EACA,SAAS;IAAQ;IAAc;;EAC/B;;;;;;;;;;;;;;;;;;;;;;;wBAwBc,SAAS,mBAAmB;;;;;;;;;;wBAgB5B,YAAY,SAAS,mBAAmB;;;;;;wBAsBxC,iBAAiB,QAAQ,cAAc;UCnEtC;EACf,yBAAyB,WAAW;;EAEpC;;EAEA,SAAS;;;;;;;UAQM;EACf,QAAQ;EACR,SAAS;EACT;;wBAwHoB,aACpB,gBACA,KAAK,cACJ,QAAQ;wBA4LW,uBACpB,KAAK,cACJ,QAAQ;;qBClRE;UAEI,6BAA6B;;;;;EAK5C,cAAc;IACZ;IACA,SAAS;IACT;IACA;;;;;;;;;wBAoEY,cACd,QAAQC,aACR,MAAM;;;;;;;;qBCtFK,WAAW,mBAAmB;KCnDtC,aAAa;UAED;;WAEN;;WAEA;WACA;;wBAGK,qBACd,gBACA,sBACA,oBACA,2BACC;;;;;wBAwBa,kBACd,KAAK,YACL,oBAAoB;EACjB,UAAU;EAAY,SAAS;;;qBCpBvB,+BAA6B;qBAE7B,yBAAyB;;;;;qBAQzB,oCAAoC;;;;;;;;;;;;;;;;;;;;;;;;;qBCtBpC,sBAAsB"}
package/dist/index.mjs CHANGED
@@ -715,9 +715,14 @@ const passThroughValidator = { getValidator() {
715
715
  * Each tool repeats its `title` inside `annotations`: the 2025-03-26 spec has
716
716
  * no top-level tool `title`, so clients and checks built on it (including the
717
717
  * Claude connector directory check) read it only from there.
718
+ *
719
+ * `destructiveHint` is stated even though the spec ignores it when
720
+ * `readOnlyHint` is true: OpenAI's plugin review requires `readOnlyHint`,
721
+ * `destructiveHint` and `openWorldHint` as explicit booleans on every tool.
718
722
  */
719
723
  const READ_ONLY = {
720
724
  readOnlyHint: true,
725
+ destructiveHint: false,
721
726
  idempotentHint: true,
722
727
  openWorldHint: false
723
728
  };
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["fromJsonSchema"],"sources":["../src/dedupe.ts","../src/limits.ts","../src/describe.ts","../src/schema.ts","../src/results.ts","../src/tools.ts","../src/types.ts","../src/validator.ts","../src/register.ts","../src/routes.ts"],"sourcesContent":["// Hoists structurally identical subschemas of a JSON Schema 2020-12 document\n// into `$defs` and replaces each occurrence with a `$ref`.\n//\n// WHY: the `query` tool advertises the whole KopaiQuery union as its input\n// schema, and the union repeats the same column enums, filter expressions and\n// time-dimension shapes across all six branches. Emitted verbatim the document\n// is ~132k characters, and a host carries it in its `tools:` array on every\n// turn, not once per connection. Deduplication is the only reduction that\n// costs the model nothing: every alternative measured (dropping descriptions,\n// collapsing enums) removes exactly the text a model needs to build a correct\n// query.\n//\n// WHY keyword-aware rather than a blind object walk: in JSON Schema a nested\n// object is not always a schema. `properties` maps property *names* to\n// schemas, so its keys must not be treated as keywords; `const`, `enum`,\n// `examples` and `default` hold data that may look like a schema but is not.\n// Hoisting a value out of one of those would change what the document\n// accepts. The three sets below enumerate the only places a schema may\n// legally appear.\n\ntype SchemaNode = Record<string, unknown>;\n\n/** Keywords whose value is a single schema. */\nconst SCHEMA_VALUE = new Set([\n \"items\",\n \"additionalProperties\",\n \"additionalItems\",\n \"contains\",\n \"propertyNames\",\n \"not\",\n \"if\",\n \"then\",\n \"else\",\n \"unevaluatedItems\",\n \"unevaluatedProperties\",\n]);\n\n/** Keywords whose value is an array of schemas. */\nconst SCHEMA_ARRAY = new Set([\"allOf\", \"anyOf\", \"oneOf\", \"prefixItems\"]);\n\n/** Keywords whose value maps arbitrary names to schemas. */\nconst SCHEMA_MAP = new Set([\n \"properties\",\n \"patternProperties\",\n \"dependentSchemas\",\n \"$defs\",\n \"definitions\",\n]);\n\n/**\n * Rebuilds `node`, invoking `cb` on every descendant that is itself a schema.\n * Returning a value from `cb` replaces that subtree; returning `undefined`\n * descends into it. The root is never offered to `cb` — a document cannot be\n * replaced by a reference to itself.\n */\nfunction eachSchema(\n node: unknown,\n cb: (node: SchemaNode) => SchemaNode | undefined,\n isRoot = false\n): unknown {\n if (!node || typeof node !== \"object\" || Array.isArray(node)) return node;\n const obj = node as SchemaNode;\n\n if (!isRoot) {\n const replacement = cb(obj);\n if (replacement !== undefined) return replacement;\n }\n\n const out: SchemaNode = {};\n for (const [key, value] of Object.entries(obj)) {\n if (\n SCHEMA_VALUE.has(key) &&\n value &&\n typeof value === \"object\" &&\n !Array.isArray(value)\n ) {\n out[key] = eachSchema(value, cb);\n } else if (SCHEMA_ARRAY.has(key) && Array.isArray(value)) {\n out[key] = value.map((s) => eachSchema(s, cb));\n } else if (SCHEMA_MAP.has(key) && value && typeof value === \"object\") {\n out[key] = Object.fromEntries(\n Object.entries(value as SchemaNode).map(([name, s]) => [\n name,\n eachSchema(s, cb),\n ])\n );\n } else {\n out[key] = value;\n }\n }\n return out;\n}\n\n/**\n * Returns `doc` with every subschema that occurs more than once hoisted into\n * `$defs`.\n *\n * `minLen` is the serialized length below which a repeat is not worth a\n * reference — a `$ref` costs about 30 characters, so hoisting anything\n * shorter makes the document bigger. Any existing `$defs` are preserved and\n * deduplicated alongside the body.\n */\nexport function dedupe(doc: SchemaNode, minLen = 60): SchemaNode {\n const existingDefs = (doc.$defs as Record<string, SchemaNode>) ?? {};\n\n // 1. Count structurally identical nodes. The root is excluded, and each\n // existing $defs body is counted from its own root for the same reason.\n const counts = new Map<string, number>();\n const body = { ...doc };\n delete body.$defs;\n\n const count = (n: SchemaNode): undefined => {\n const key = JSON.stringify(n);\n if (key.length >= minLen) counts.set(key, (counts.get(key) ?? 0) + 1);\n return undefined;\n };\n\n eachSchema(body, count, true);\n for (const def of Object.values(existingDefs)) eachSchema(def, count, true);\n\n // 2. Hoist everything seen at least twice. Longest first, so that a large\n // repeated shape becomes one definition rather than being shredded into\n // references to its own parts.\n const refNames = new Map<string, string>();\n const newDefs: Record<string, SchemaNode> = {};\n let next = 0;\n for (const [key, seen] of [...counts.entries()].sort(\n (a, b) => b[0].length - a[0].length\n )) {\n if (seen < 2) continue;\n // Step over any name the document already defines. The write loop below\n // lets an existing definition win, so a collision would drop the hoisted\n // body and leave every `$ref` substituted for it pointing at an\n // unrelated schema — a document that still compiles but accepts\n // different input.\n let name = `s${next++}`;\n while (Object.hasOwn(existingDefs, name)) name = `s${next++}`;\n refNames.set(key, name);\n newDefs[name] = JSON.parse(key) as SchemaNode;\n }\n\n const substitute = (n: SchemaNode): SchemaNode | undefined => {\n const name = refNames.get(JSON.stringify(n));\n return name === undefined ? undefined : { $ref: `#/$defs/${name}` };\n };\n\n // 3. Rewrite the document, then each hoisted body. A body must skip the\n // match against itself, or every definition becomes a reference to\n // itself and the document stops meaning anything.\n const result = eachSchema(doc, substitute, true) as SchemaNode;\n const defs: Record<string, SchemaNode> = {\n ...((result.$defs as Record<string, SchemaNode>) ?? {}),\n };\n\n for (const [name, defBody] of [\n ...Object.entries(newDefs),\n ...Object.entries(existingDefs),\n ]) {\n const self = JSON.stringify(defBody);\n defs[name] = eachSchema(\n defBody,\n (n) => (JSON.stringify(n) === self ? undefined : substitute(n)),\n true\n ) as SchemaNode;\n }\n\n result.$defs = defs;\n return result;\n}\n","import { kopaiQuery } from \"@kopai/core\";\n\n/**\n * Row caps, per mode.\n *\n * WHY per mode rather than one number: measured serialized row sizes differ by\n * an order of magnitude. A raw trace row is ~703 characters, a raw log row\n * ~418, a raw metric row 408-653 (OTel repeats the metric name, description\n * and unit on every data point), against ~96 for an aggregate summary row and\n * ~134 for a `timeSeries` row. Against the character ceiling below, a uniform\n * cap of 500 would let every raw shape overrun — traces by 134%, logs by 39%,\n * metrics by 36-118% — so a raw query that used its own cap would pay for a\n * full round trip and then have the result refused.\n *\n * At 200 they all fit, though traces land at ~94% of budget, which is why the\n * post-serialization check stays load-bearing rather than being a formality.\n * Treat these figures as optimistic: they come from fixtures, and production\n * attribute maps are heavier.\n *\n * The consequence for callers, worth stating in the tool description: the\n * aggregate shape is the efficient one and raw is for inspecting individual\n * records. One hour of one gauge costs roughly 116,400 characters as raw rows\n * against 8,040 as a `timeSeries` aggregate at `1m` — fourteen times less, for\n * the same chart, with the bucketing done in the database.\n */\nexport const LIMITS = {\n raw: {\n /** Applied when the caller sends no `limit`; matches the backend default. */\n fallback: 100,\n max: 200,\n },\n aggregate: {\n /**\n * Applied when the caller sends no `limit`. Unlike raw, this is not a\n * backend default being restated: both backends emit `LIMIT` for an\n * aggregate query only when one is explicitly set, so an aggregate query\n * with no limit runs unbounded.\n */\n fallback: 500,\n max: 500,\n },\n} as const;\n\n/**\n * The serialized size past which a result is refused rather than returned.\n *\n * Measured after serialization, on one copy of the payload — the result\n * carries the same JSON in two channels, but a client forwards one or the\n * other, so the model only ever ingests it once.\n */\nexport const MAX_RESULT_CHARACTERS = 150_000;\n\n/**\n * Remedies for a discovery listing too large even with the attributes gone.\n *\n * WHY its own list: `metrics_discover` takes no arguments, so every line in\n * `SIZE_REMEDIES` names a field the caller cannot set — a `limit`, a window, a\n * `granularity`. Offering those turned an over-size listing into a dead end\n * dressed up as advice. Nothing the caller writes can shrink this result, so\n * the honest answer is what remains possible without it.\n */\nexport const DISCOVERY_SIZE_REMEDIES = [\n \"Query a metric by name with the `query` tool — discovery is not a prerequisite for it.\",\n \"Ask an operator to reduce what this deployment ingests: this workspace holds more metrics than one response can carry.\",\n] as const;\n\n/**\n * ClickHouse error codes for a query stopped at a resource limit: 158\n * TOO_MANY_ROWS, 159 TIMEOUT_EXCEEDED, 160 TOO_SLOW (the estimated time\n * already exceeds `max_execution_time`), 241 MEMORY_LIMIT_EXCEEDED, 307\n * TOO_MANY_BYTES, 396 TOO_MANY_ROWS_OR_BYTES.\n *\n * WHY ClickHouse codes in a package that knows no backend: the datasource\n * rethrows `@clickhouse/client`'s error as it is, so its `code` is the only\n * signal that reaches this layer. The SQLite datasource sets no such limits.\n * Mirrored in `@kopai/api`'s error handler, which cannot import from here.\n *\n * WHY not `@clickhouse/client`'s own \"Timeout error.\": it is a socket timeout,\n * and fires as readily for a server that stopped answering as for a heavy\n * query. A heavy query is expected to meet the server's `max_execution_time`\n * first, set by the host below the client's `request_timeout`, and fail with\n * 159; a client timeout is then an outage, and stays one.\n */\nconst RESOURCE_LIMIT_CODES: ReadonlySet<string> = new Set([\n \"158\",\n \"159\",\n \"160\",\n \"241\",\n \"307\",\n \"396\",\n]);\n\n/**\n * Whether a throw is a query stopped at a resource limit, which the caller\n * can get past by asking for less. Anything else stays an upstream error.\n *\n * A 241 for the server as a whole (\"(total) memory limit exceeded\") is\n * excluded: other queries or ingest used the memory, so asking for less does\n * not help.\n */\nexport function isResourceLimitError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n const { code } = error as { code?: unknown };\n if (typeof code !== \"string\" || !RESOURCE_LIMIT_CODES.has(code)) {\n return false;\n }\n return !(code === \"241\" && error.message.includes(\"(total)\"));\n}\n\n/** Remedies for a query stopped at a resource limit. */\nexport const RESOURCE_LIMIT_REMEDIES = [\n \"Narrow the time window.\",\n \"Add filters so fewer rows are read: `service.name` or another attribute, and for metrics a single `MetricName`.\",\n \"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.\",\n] as const;\n\n/**\n * Remedies for a discovery listing stopped at a resource limit. Its own list\n * for the reason {@link DISCOVERY_SIZE_REMEDIES} is: the tool takes no\n * arguments, so there is no window or filter to offer.\n */\nexport const DISCOVERY_RESOURCE_LIMIT_REMEDIES = [\n \"Query a metric by name with the `query` tool — discovery is not a prerequisite for it.\",\n \"Try again shortly: the listing may have run while this deployment was busy.\",\n] as const;\n\n/** Remedies offered when a result is too large once serialized. */\nexport const SIZE_REMEDIES = [\n \"Lower `limit`.\",\n \"Narrow the time window.\",\n \"Use a coarser `granularity`, or `output: {type: 'summary'}` instead of a time series.\",\n] as const;\n\n/**\n * How many time buckets the window will be cut into, or 1 for a summary.\n *\n * WHY this is worth computing: an aggregate's row count is groups times\n * buckets, and the two need opposite advice. Buckets are exactly derivable\n * from the window and the granularity, which is enough to tell the two causes\n * apart — if the buckets alone exceed the cap then no amount of regrouping\n * will help, and if they do not then the group cardinality is what overran.\n *\n * WHY boundaries rather than whole spans: neither backend cuts the window into\n * granularity-sized pieces starting at its own start. Both snap each timestamp\n * to a fixed boundary measured from the epoch — `(ts / g) * g` in SQLite,\n * `toStartOfInterval(ts, INTERVAL n SECOND)` in ClickHouse — so a window that\n * does not begin on a boundary straddles one more bucket than it has whole\n * granularities. Measured against a real SQLite datasource: an hour at `5m`\n * starting at :02:30 produces thirteen distinct `bucket_start` values, not\n * twelve. Counting whole spans understated every unaligned window by one.\n */\nfunction bucketCount(query: kopaiQuery.KopaiQuery): number {\n if (query.mode !== \"aggregate\" || query.output.type !== \"timeSeries\")\n return 1;\n\n const granularityNs = kopaiQuery.durationStringToNanos(\n query.output.granularity\n );\n if (typeof granularityNs !== \"number\" || granularityNs <= 0) return 1;\n\n const window = query.timeDimension;\n\n if (window.type === \"relative\") {\n const lookbackNs = kopaiQuery.durationStringToNanos(window.lookback);\n if (typeof lookbackNs !== \"number\" || lookbackNs <= 0) return 1;\n // A relative window ends at the clock reading taken when the query runs,\n // so where it falls against the boundaries is not knowable from the query\n // alone. One extra bucket is the bound that holds for every alignment.\n return Math.ceil(lookbackNs / granularityNs) + 1;\n }\n\n // An absolute window is exact. Work in milliseconds: a granularity is a\n // whole number of seconds, and epoch nanoseconds are past the range a\n // double represents exactly.\n const startMs = Date.parse(window.startTime);\n const endMs = Date.parse(window.endTime);\n if (!Number.isFinite(startMs) || !Number.isFinite(endMs) || endMs <= startMs)\n return 1;\n const granularityMs = granularityNs / 1e6;\n\n // The window is half-open (`>= start AND < end` in both backends), so the\n // last bucket is the last boundary strictly below `endTime`.\n const firstBoundary = Math.floor(startMs / granularityMs);\n const lastBoundary = Math.ceil(endMs / granularityMs) - 1;\n return Math.max(1, lastBoundary - firstBoundary + 1);\n}\n\n/**\n * Remedies for an aggregate query that overran its cap, ordered by whichever\n * factor actually caused it.\n *\n * WHY ordered rather than a fixed list: an aggregate returns groups times\n * buckets rows, and advice for one is useless for the other. Telling someone\n * grouping by a high-cardinality column in a `summary` query to use a coarser\n * granularity names a field their query does not have; telling someone whose\n * window is cut into more buckets than the cap allows to group by less will\n * not help them either.\n *\n * WHY there is no \"add an `orderBy`\" line: an ordering does not change the\n * outcome. An overflow is refused whether or not the query is ordered, because\n * a live page cannot act on a remedy — its query was fixed at authoring time\n * and its viewer did not write it — so a truncated result would be drawn as\n * though it were the whole set.\n */\nexport function overflowRemedies(\n query: kopaiQuery.KopaiQuery,\n limit: number,\n max: number\n): string[] {\n // Read off the query rather than inferred from the bucket count: a window\n // that happens to span one bucket is still a time series, and classifying it\n // as a summary dropped the one remedy that always works on it — asking for a\n // summary instead — while offering advice about a `granularity` the caller\n // was told the query does not have. `output.type` is the authoritative\n // discriminator; the bucket count only orders the advice.\n const isTimeSeries =\n query.mode === \"aggregate\" && query.output.type === \"timeSeries\";\n const buckets = bucketCount(query);\n const grouped =\n query.mode === \"aggregate\" && (query.dimensions?.length ?? 0) > 0;\n\n const raiseLimit = limit < max ? [`Raise \\`limit\\`, up to ${max}.`] : [];\n // States what the declared window spans, not how many rows came back: a\n // bucket only materialises where there is data, so this is an upper bound.\n // It is still the useful number, because it is the one the caller chose.\n 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.`;\n const fewerGroups =\n \"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.\";\n const narrower = \"Narrow the time window.\";\n const summarise_ =\n 'Use `output: { type: \"summary\" }` if the trend over time is not what you need.';\n\n // The buckets alone exceed the cap, so this cannot be regrouped out of.\n if (isTimeSeries && buckets > limit) {\n return [...raiseLimit, coarser, narrower, summarise_];\n }\n\n if (isTimeSeries) {\n // Rows are groups times buckets and the buckets fit, so the groups are\n // what overran — but a coarser granularity still divides the total, so it\n // stays on the list, second. Not where the window spans a single bucket,\n // though: there is nothing for a coarser one to merge, and the line would\n // read \"spans up to 1 buckets\".\n const coarserIfItHelps = buckets > 1 ? [coarser] : [];\n return grouped\n ? [...raiseLimit, fewerGroups, ...coarserIfItHelps, narrower, summarise_]\n : [...raiseLimit, ...coarserIfItHelps, narrower, summarise_];\n }\n\n // A summary query has no granularity at all; naming one would be noise.\n return [...raiseLimit, fewerGroups, narrower];\n}\n","// Rewriting the advertised schema's guidance without touching the shared one.\n//\n// WHY this exists: the `KopaiQuery` schema is shared with the REST routes, and\n// some of what it says is true there and false here. Its `limit` field\n// advertises \"Hard cap = 10000\", which is REST's cap; this tool refuses\n// anything above 200 or 500. A model reading the field-level description —\n// the text nearest the decision — writes a limit it will be refused for.\n//\n// The same schema is also silent on cost. It says what `granularity` and\n// `dimensions` mean, but not that together they set the row count, which is\n// the thing that decides whether a query succeeds.\n//\n// Both are fixed in the copy this tool advertises, leaving the shared schema\n// alone. Matching is by description prefix rather than by path, because the\n// same field appears once per signal with slightly different wording, and a\n// path list would rot silently. A test asserts every override still matches\n// something, so a reworded schema fails loudly instead of quietly dropping\n// the guidance.\n\ntype SchemaNode = Record<string, unknown>;\n\nexport interface DescriptionOverride {\n /** Start of the description to match, in the shared schema. */\n readonly prefix: string;\n /** Replaces the description outright, or extends it. */\n readonly mode: \"replace\" | \"append\";\n readonly text: string;\n}\n\nexport function descriptionOverrides(\n rawMax: number,\n aggregateMax: number,\n rawDefault: number,\n aggregateDefault: number\n): DescriptionOverride[] {\n return [\n {\n prefix: \"Maximum rows to return.\",\n mode: \"replace\",\n 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.`,\n },\n {\n prefix: \"Bucket width.\",\n mode: \"append\",\n text: \" A time series returns one row per group per bucket, so halving this doubles the rows returned.\",\n },\n {\n prefix: \"GROUP BY columns.\",\n mode: \"append\",\n 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.\",\n },\n ];\n}\n\n/**\n * Returns `doc` with each override applied wherever its prefix matches, and a\n * count per override so a caller can tell whether any stopped matching.\n */\nexport function applyDescriptions(\n doc: SchemaNode,\n overrides: readonly DescriptionOverride[]\n): { document: SchemaNode; applied: Record<string, number> } {\n const applied: Record<string, number> = Object.fromEntries(\n overrides.map((o) => [o.prefix, 0])\n );\n\n const rewrite = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(rewrite);\n if (!value || typeof value !== \"object\") return value;\n\n const node = { ...(value as SchemaNode) };\n const description = node.description;\n if (typeof description === \"string\") {\n for (const override of overrides) {\n if (!description.startsWith(override.prefix)) continue;\n node.description =\n override.mode === \"replace\"\n ? override.text\n : description + override.text;\n applied[override.prefix] = (applied[override.prefix] ?? 0) + 1;\n break;\n }\n }\n\n for (const [key, child] of Object.entries(node)) {\n if (key === \"description\") continue;\n node[key] = rewrite(child);\n }\n return node;\n };\n\n return { document: rewrite(doc) as SchemaNode, applied };\n}\n","import { kopaiQuery } from \"@kopai/core\";\nimport { z } from \"zod\";\n\nimport { dedupe } from \"./dedupe.js\";\nimport { applyDescriptions, descriptionOverrides } from \"./describe.js\";\nimport { LIMITS } from \"./limits.js\";\n\n/**\n * The `query` tool's input: the KopaiQuery body under a single `query`\n * property, because an MCP tool's input schema must have an object root and\n * KopaiQuery is a union.\n *\n * Strict, so the document says `additionalProperties: false` on the root as\n * well as on every node inside it. In `io: \"input\"` mode zod leaves a plain\n * `z.object` open, which advertised a tool that accepted arguments it would\n * then ignore; `runQueryTool` rejects them, and the schema now agrees.\n */\nconst QueryToolInput = z.strictObject({ query: kopaiQuery.KopaiQuery });\n\n/**\n * The advertised input schema for the `query` tool, deduplicated into `$defs`.\n *\n * WHY generated here, at module scope, rather than inside the per-request\n * server factory: the transport builds a fresh server per request, and\n * generating plus deduplicating this document costs ~11 ms — around a hundred\n * times a request's own work. The document depends on nothing request-scoped,\n * so it is built once per process and shared.\n */\nconst OVERRIDES = descriptionOverrides(\n LIMITS.raw.max,\n LIMITS.aggregate.max,\n LIMITS.raw.fallback,\n LIMITS.aggregate.fallback\n);\n\nconst described = applyDescriptions(\n z.toJSONSchema(QueryToolInput, { io: \"input\" }) as Record<string, unknown>,\n OVERRIDES\n);\n\n/** How many nodes each override matched. Asserted in the tests, not at runtime. */\nexport const DESCRIPTION_OVERRIDES_APPLIED = described.applied;\n\nexport const QUERY_TOOL_INPUT_SCHEMA: Record<string, unknown> = dedupe(\n described.document\n);\n\n/**\n * The `metrics_discover` tool takes no arguments, but MCP still requires an\n * object root.\n */\nexport const METRICS_DISCOVER_TOOL_INPUT_SCHEMA: Record<string, unknown> = {\n type: \"object\",\n properties: {},\n};\n","import type { ToolCallOutcome } from \"./types.js\";\n\n/** An error code a tool can return. `ok` is not one of them. */\nexport type ToolErrorCode = Exclude<ToolCallOutcome, \"ok\">;\n\nexport interface ToolIssue {\n path: string;\n message: string;\n}\n\nexport interface ToolErrorPayload {\n error: ToolErrorCode;\n message: string;\n issues?: ToolIssue[];\n remedies?: string[];\n}\n\n/**\n * The shape every tool on the server returns, built-in or host. Deliberately not the MCP SDK's own result type\n * — this stays a plain object so it can be asserted on in tests without a\n * server.\n */\nexport type ToolResult = {\n structuredContent: unknown;\n content: Array<{ type: \"text\"; text: string }>;\n isError?: true;\n};\n\n/**\n * Builds a result carrying `payload` in BOTH channels — as\n * `structuredContent`, and as a single text block holding exactly\n * `JSON.stringify` of the same object.\n *\n * WHY both, when the specification suggests one: the two consumers read\n * different channels and neither reads both. A live page reads\n * `structuredContent` through the artifact runtime's `payload` convenience. A\n * conversational agent reads `content` — Anthropic's own MCP helper returns\n * `result.content.map(...)` and discards `structuredContent` entirely whenever\n * `content` is non-empty, falling back to the structured value only when\n * `content` is empty. So rows in `structuredContent` plus a prose summary in\n * the text block is the one combination that fails: the fallback never fires,\n * and the agent receives the summary and none of the rows, with no error\n * raised anywhere.\n *\n * Sending both costs wire bytes only, never context: a client forwards one\n * channel or the other, so the model ingests the payload once. The text block\n * stays pure JSON so that the \"first text block parsed as JSON\" path a page\n * may fall back to remains valid.\n */\nexport function okResult(payload: unknown): ToolResult {\n return {\n structuredContent: payload,\n content: [{ type: \"text\", text: JSON.stringify(payload) }],\n };\n}\n\n/**\n * Builds a failed result. Same duplication as {@link okResult}, and more\n * load-bearing here: the empty-content fallback to the structured value sits\n * below the `isError` branch in the agent's helper, so it never fires on a\n * failure. A structured-only success degrades; a structured-only error\n * vanishes, leaving the agent an empty error and nothing to repair from.\n *\n * `error` is written first so the serialized JSON opens with the code.\n */\nexport function errorResult(payload: ToolErrorPayload): ToolResult {\n // Rebuilt key by key rather than spread, because the key order is the\n // contract: `error` must serialize first.\n const ordered: ToolErrorPayload = {\n error: payload.error,\n message: payload.message,\n };\n if (payload.issues !== undefined) ordered.issues = payload.issues;\n if (payload.remedies !== undefined) ordered.remedies = payload.remedies;\n\n return {\n structuredContent: ordered,\n content: [{ type: \"text\", text: JSON.stringify(ordered) }],\n isError: true,\n };\n}\n\n/**\n * Re-points issue paths from `@kopai/core`'s query-relative form onto the\n * tool's input, whose single property is `query`. The empty root path becomes\n * `query` rather than `query.`.\n */\nexport function prefixIssuePaths(issues: ToolIssue[]): ToolIssue[] {\n return issues.map(({ path, message }) => ({\n path: path === \"\" ? \"query\" : `query.${path}`,\n message,\n }));\n}\n","import { kopaiQuery, kopaiQueryCompiler, type datasource } from \"@kopai/core\";\n\nimport {\n DISCOVERY_RESOURCE_LIMIT_REMEDIES,\n DISCOVERY_SIZE_REMEDIES,\n isResourceLimitError,\n LIMITS,\n MAX_RESULT_CHARACTERS,\n overflowRemedies,\n RESOURCE_LIMIT_REMEDIES,\n SIZE_REMEDIES,\n} from \"./limits.js\";\nimport {\n errorResult,\n okResult,\n prefixIssuePaths,\n type ToolResult,\n} from \"./results.js\";\nimport type { ToolCallOutcome, ToolLogger } from \"./types.js\";\n\nexport interface ToolContext {\n readTelemetryDatasource: datasource.ReadTelemetryDatasource;\n /** Whatever the host application attached to the request; passed through. */\n requestContext?: unknown;\n /** Where an upstream failure is written. See {@link fromThrown}. */\n logger?: ToolLogger;\n}\n\n/**\n * A completed tool run. The outcome is returned rather than inferred from the\n * result so that the observer and any counter read the same value the caller\n * sees, with no second classification step to drift.\n */\nexport interface ToolRun {\n result: ToolResult;\n outcome: ToolCallOutcome;\n rowCount?: number;\n}\n\nfunction invalidInput(\n message: string,\n issues?: { path: string; message: string }[]\n): ToolRun {\n return {\n result: errorResult({ error: \"invalid_input\", message, issues }),\n outcome: \"invalid_input\",\n };\n}\n\nfunction tooLarge(message: string, remedies: readonly string[]): ToolRun {\n return {\n result: errorResult({\n error: \"result_too_large\",\n message,\n remedies: [...remedies],\n }),\n outcome: \"result_too_large\",\n };\n}\n\n/**\n * A query the datasource stopped at a resource limit. Exported for the host\n * tools' throw handler in `register.ts`.\n */\nexport function tooExpensive(\n message: string,\n remedies: readonly string[]\n): ToolRun {\n return {\n result: errorResult({\n error: \"query_too_expensive\",\n message,\n remedies: [...remedies],\n }),\n outcome: \"query_too_expensive\",\n };\n}\n\n/**\n * Maps a thrown error onto an outcome, mirroring the REST error handler:\n * a recognised validation error surfaces its own message, a resource limit\n * surfaces what to ask for instead, and anything unrecognised surfaces a\n * generic string with the detail written to the log.\n *\n * WHY a resource limit gets its own outcome: it is the failure a caller can\n * get past, by asking for less, and a generic \"could not be completed\" gave\n * it nothing to change. Directory review fails a connector whose errors carry\n * no detail.\n *\n * WHY the log matters as much as the result: \"The query could not be\n * completed.\" is the whole of what a model can act on, and it is also the\n * whole of what anyone got. A datasource that was refusing connections\n * produced that one string for the caller and not a line for whoever runs the\n * server — in a product whose purpose is making failures visible. The REST\n * side has always logged this class of error (`error-handler.ts`); this is the\n * same thing at the other entry point.\n *\n * A validation error is not logged: it is the caller's mistake, it is reported\n * back in full, and logging every malformed query would bury the outages. A\n * resource limit is logged: it is the caller's query, but which queries the\n * datasource cannot afford is for whoever runs it to know.\n *\n * `limitRemedies` is for `metrics_discover`, which takes no arguments and so\n * cannot narrow a window.\n */\nexport function fromThrown(\n error: unknown,\n logger?: ToolLogger,\n limitRemedies: readonly string[] = RESOURCE_LIMIT_REMEDIES\n): ToolRun {\n if (error instanceof kopaiQueryCompiler.KopaiQueryValidationError) {\n return invalidInput(error.message);\n }\n logger?.error(error, \"MCP tool call failed\");\n if (isResourceLimitError(error)) {\n return tooExpensive(\n \"The query was stopped at this deployment's limit on query time, memory or rows read.\",\n limitRemedies\n );\n }\n return {\n result: errorResult({\n error: \"upstream_error\",\n message: \"The query could not be completed.\",\n }),\n outcome: \"upstream_error\",\n };\n}\n\n/**\n * The branch a query was judged against, when the pair selects one.\n *\n * WHY the message names it: the issues name fields, and the six shapes share\n * field names — `measures` is on three of them, `filters` on all six. A caller\n * told only `query.measures.0.column` does not know which shape its query was\n * read as, and the `signal`/`mode` pair that decides that is the one thing it\n * can get wrong without any issue pointing at it. Where the pair itself is\n * wrong there is no branch to name, and the issues on `signal` and `mode` say\n * so instead.\n */\nfunction branchOf(query: unknown): string | undefined {\n const { signal, mode } = (query ?? {}) as {\n signal?: unknown;\n mode?: unknown;\n };\n return kopaiQuery.isSignal(signal) && kopaiQuery.isQueryMode(mode)\n ? `${signal}/${mode}`\n : undefined;\n}\n\n/** Rows in a payload, for the observer. Aggregate and raw both key on `data`. */\nfunction rowsOf(payload: unknown): number | undefined {\n const data = (payload as { data?: unknown })?.data;\n return Array.isArray(data) ? data.length : undefined;\n}\n\nexport async function runQueryTool(\n input: unknown,\n ctx: ToolContext\n): Promise<ToolRun> {\n if (typeof input !== \"object\" || input === null || Array.isArray(input)) {\n return invalidInput(\"Expected an object with a `query` property.\", [\n { path: \"query\", message: \"Expected a query object.\" },\n ]);\n }\n\n // `query` is the only argument, and the handler reads nothing else, so an\n // extra key would be dropped without a word. The slip that produces one is\n // writing a query field at the top level — `limit` beside `query` rather\n // than inside it — and dropping that ran a different query than the caller\n // described and then answered `ok`. The pass-through validator means no\n // layer above this one will catch it either.\n const extraArgs = Object.keys(input as Record<string, unknown>).filter(\n (key) => key !== \"query\"\n );\n if (extraArgs.length > 0) {\n return invalidInput(\n `${extraArgs.map((key) => `\\`${key}\\``).join(\", \")} ${\n extraArgs.length > 1 ? \"are not arguments\" : \"is not an argument\"\n } of this tool. \\`query\\` is the only one.`,\n extraArgs.map((key) => ({\n path: key,\n message: `Unknown argument. If it is a query field, it belongs at \\`query.${key}\\`.`,\n }))\n );\n }\n\n const query_ = (input as { query?: unknown }).query;\n const parsed = kopaiQueryCompiler.parseKopaiQuery(query_);\n if (!parsed.ok) {\n const branch = branchOf(query_);\n return invalidInput(\n branch ? `The ${branch} query is not valid.` : \"The query is not valid.\",\n prefixIssuePaths(parsed.issues)\n );\n }\n\n const query = parsed.data;\n const { fallback, max } = LIMITS[query.mode];\n\n // Rejected, never clamped: a caller that asked for 500 raw rows and\n // silently received 200 would read the result as complete.\n if (query.limit !== undefined && query.limit > max) {\n return invalidInput(\n `\\`limit\\` must be at most ${max} in ${query.mode} mode.`,\n [\n {\n path: \"query.limit\",\n message: `Expected at most ${max}, received ${query.limit}.`,\n },\n ]\n );\n }\n\n const limit = query.limit ?? fallback;\n\n // Aggregate runs one row over the cap so that an overflow is detectable.\n // Raw does not need this: the backend already fetches limit + 1 and reports\n // the remainder as `nextCursor`, so a truncated raw result is both visible\n // and resumable.\n const isAggregate = query.mode === \"aggregate\";\n const probeLimit = isAggregate ? limit + 1 : limit;\n\n let payload: unknown;\n try {\n payload = await ctx.readTelemetryDatasource.query({\n ...query,\n limit: probeLimit,\n requestContext: ctx.requestContext,\n } as kopaiQuery.KopaiQuery & { requestContext?: unknown });\n } catch (error) {\n return fromThrown(error, ctx.logger);\n }\n\n if (isAggregate) {\n const rows = (payload as { data?: unknown[] }).data ?? [];\n if (rows.length > limit) {\n // An aggregate that overruns its cap is refused outright, with no rows,\n // whether or not it carries an `orderBy`.\n //\n // WHY refuse rather than truncate, even when an ordering makes the\n // truncation well defined: a live page cannot act on a remedy. Its query\n // was fixed when the page was authored and its viewer did not write it,\n // so a partial result would simply be drawn as though it were the whole\n // set — the top N groups rendered as if they were all the groups.\n // ADR-059 requires a page to show an explicit \"outgrew its query\" state\n // and never draw a partial chart, and refusing is what makes that hold\n // without every page having to check a flag it may not know about.\n //\n // Without an ordering it would be worse still: the aggregate compiler\n // emits no ORDER BY when `orderBy` is absent, so a LIMIT drops an\n // arbitrary subset — and for a time series, whose rows are groups times\n // buckets, that is a scatter of (group, bucket) pairs that reads as real\n // data. `bucket_start` cannot rescue it either: it is a computed SELECT\n // alias, neither a dimension nor a measure, so a time series cannot be\n // sorted by time at all.\n return tooLarge(\n `The query returned more than the ${limit} rows it asked for.`,\n overflowRemedies(query, limit, max)\n );\n }\n }\n\n // Measured after serialization, on one copy: the result carries the same\n // JSON twice, but a client forwards one channel or the other.\n const serialized = JSON.stringify(payload);\n if (serialized.length > MAX_RESULT_CHARACTERS) {\n return tooLarge(\n `The result serialized to ${serialized.length.toLocaleString(\"en-US\")} characters, above the ${MAX_RESULT_CHARACTERS.toLocaleString(\"en-US\")} the host will accept.`,\n SIZE_REMEDIES\n );\n }\n\n return {\n result: okResult(payload),\n outcome: \"ok\",\n rowCount: rowsOf(payload),\n };\n}\n\n/** A metric with its attribute values dropped, keys kept. */\ninterface MetricWithAttributeKeys {\n name: string;\n type: string;\n unit?: string;\n description?: string;\n attributeKeys: string[];\n resourceAttributeKeys: string[];\n}\n\n/** A metric stripped to what cannot be guessed or derived. */\ntype MetricIdentityOnly = Omit<\n MetricWithAttributeKeys,\n \"attributeKeys\" | \"resourceAttributeKeys\"\n>;\n\nfunction identityOf(metric: datasource.DiscoveredMetric): MetricIdentityOnly {\n const { name, type, unit, description } = metric;\n return {\n name,\n type,\n ...(unit === undefined ? {} : { unit }),\n ...(description === undefined ? {} : { description }),\n };\n}\n\n/**\n * The discovery listing, given up a piece at a time until it fits.\n *\n * WHY degrade rather than refuse: `metrics_discover` takes no arguments, so a\n * caller handed `result_too_large` has nothing to change and no way to learn a\n * metric name — which the `query` tool's own description tells them to do\n * first. The values seen on each attribute are the bulk of the document and\n * the metric names are the part that cannot be guessed, so they are given up in\n * that order, and the response says which step was taken rather than leaving a\n * thinner answer to pass as the whole one.\n */\nfunction degradations(\n full: datasource.MetricsDiscoveryResult\n): { payload: Record<string, unknown>; omitted?: string }[] {\n return [\n { payload: { ...full } },\n {\n omitted: \"attributeValues\",\n payload: {\n metrics: full.metrics.map((metric): MetricWithAttributeKeys => ({\n ...identityOf(metric),\n attributeKeys: Object.keys(metric.attributes?.values ?? {}),\n resourceAttributeKeys: Object.keys(\n metric.resourceAttributes?.values ?? {}\n ),\n })),\n omitted: \"attributeValues\",\n 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.\",\n },\n },\n {\n omitted: \"attributes\",\n payload: {\n metrics: full.metrics.map(identityOf),\n omitted: \"attributes\",\n 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.\",\n },\n },\n ];\n}\n\nexport async function runMetricsDiscoverTool(\n ctx: ToolContext\n): Promise<ToolRun> {\n let full: datasource.MetricsDiscoveryResult;\n try {\n full = await ctx.readTelemetryDatasource.discoverMetrics({\n requestContext: ctx.requestContext,\n });\n } catch (error) {\n return fromThrown(error, ctx.logger, DISCOVERY_RESOURCE_LIMIT_REMEDIES);\n }\n\n // Serialization is outside the try: a payload this cannot stringify is not an\n // upstream failure, and reporting it as one blamed the datasource for a bug\n // here.\n let serialized = \"\";\n for (const stage of degradations(full)) {\n serialized = JSON.stringify(stage.payload);\n if (serialized.length <= MAX_RESULT_CHARACTERS) {\n return {\n result: okResult(stage.payload),\n outcome: \"ok\",\n rowCount: full.metrics.length,\n };\n }\n }\n\n return tooLarge(\n `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.`,\n DISCOVERY_SIZE_REMEDIES\n );\n}\n","import type { datasource } from \"@kopai/core\";\nimport type { McpServer } from \"@modelcontextprotocol/server\";\nimport type { FastifyRequest } from \"fastify\";\n\n/**\n * How a tool call ended. These labels are the server's whole error\n * vocabulary: they are the `error` code on a failed result, the `outcome` on\n * the observer event, and the values a counter is grouped by.\n *\n * `not_found` and `forbidden` are produced only by host tools (see\n * {@link HostTools}); the built-in tools never return them.\n *\n * `query_too_expensive` is a query the datasource stopped at a time, memory,\n * row or byte limit, recognised from the thrown error; see\n * `isResourceLimitError`.\n */\nexport const TOOL_CALL_OUTCOMES = [\n \"ok\",\n \"invalid_input\",\n \"result_too_large\",\n \"query_too_expensive\",\n \"upstream_error\",\n \"not_found\",\n \"forbidden\",\n] as const;\n\nexport type ToolCallOutcome = (typeof TOOL_CALL_OUTCOMES)[number];\n\n/**\n * The one method this package calls on a logger.\n *\n * Structural rather than Fastify's own type: the tool layer knows nothing\n * about HTTP, and a host that mounts this plugin somewhere else should not\n * have to produce a `FastifyBaseLogger` to get its failures written down.\n * `routes.ts` passes `request.log`, which satisfies it.\n */\nexport interface ToolLogger {\n error(payload: unknown, message?: string): void;\n}\n\n/**\n * One completed tool call, handed to `onToolCall`.\n *\n * WHY the raw request is included: this plugin is open source and mounts in\n * two applications that know different things about a caller. It deliberately\n * does not learn about tenants or credentials; the host application reads\n * whatever it attached to the request and does its own counting and logging.\n */\nexport interface ToolCallEvent {\n tool: string;\n outcome: ToolCallOutcome;\n durationMs: number;\n /** Rows returned, when the tool returned rows. */\n rowCount?: number;\n request: FastifyRequest;\n}\n\n/**\n * Tools the host application adds to the same server as `query` and\n * `metrics_discover`, for data only the host has.\n *\n * Host tools follow the built-ins' conventions:\n *\n * - Results are built with `okResult` and `errorResult`, so the\n * error contract holds for every tool on the server.\n * - The package observes them as it observes the built-ins: a throw becomes\n * a logged `upstream_error` (\"The tool call could not be completed.\"), or\n * `query_too_expensive` when it is a query stopped at a resource limit, the\n * outcome is read from the result's `error` code, and `onToolCall` fires\n * once per call (without `rowCount`).\n * A host tool never calls `onToolCall` itself. An error result without a\n * known code is counted as `upstream_error` and logged.\n * - `inputSchema` is built with `fromJsonSchema(schema, passThroughValidator)`\n * and the handler validates, returning `invalid_input` with `issues`. The\n * SDK's own validator rejects before dispatch, so the rejection would go\n * uncounted and lose its `issues`; see `validator.ts`.\n * - No `outputSchema`; registering one, or adding one through `update`,\n * throws. The SDK checks it after the\n * callback returns, so a mismatch would be counted `ok` while the caller\n * got the SDK's bare error.\n * - `McpServer` and `fromJsonSchema` are imported from `@kopai/mcp`, not from\n * `@modelcontextprotocol/server`. They are the SDK's own, re-exported, at\n * the version this package pins (2.3.1). `McpServer` has private fields, so\n * a second copy of the SDK is a different, incompatible type.\n *\n * `register` is for tools. Prompts and resources registered through it are\n * neither checked nor observed.\n */\nexport interface HostTools {\n /**\n * Every name `register` may register. Checked once, at plugin registration:\n * a name that is not an MCP tool name (`[A-Za-z0-9._-]`, 1 to 128\n * characters), a duplicate, or a built-in name is refused with a\n * `TypeError`. An empty list is allowed.\n */\n names: string[];\n /**\n * Runs on each request's server, after the built-in tools are registered.\n * Registering, or renaming a tool to, a name not in `names` throws, and so\n * does renaming a tool onto a name already registered.\n *\n * Synchronous, because the SDK's server factory is; a returned promise\n * fails the request. Do the I/O that decides\n * which tools this caller gets in an async `preHandler`, attach the result\n * to the request, and read it here. A tool not registered for a request is\n * absent from that caller's `tools/list`.\n *\n * A throw fails the request; the server does not fall back to the built-in\n * tools alone.\n */\n register: (server: McpServer, request: FastifyRequest) => void;\n}\n\nexport interface McpRoutesOptions {\n readTelemetryDatasource: datasource.ReadTelemetryDatasource;\n /**\n * Hostnames the MCP endpoint answers for, compared port-agnostically. A\n * request whose `Host` is not on this list is refused, which is what stops\n * a DNS-rebinding page from reaching a local server.\n */\n allowedHosts: string[];\n /**\n * Hostnames that may appear in a browser's `Origin` header. Omit to mount no\n * origin validation at all, which is the default.\n *\n * An empty list is not the same as omitting it: it mounts a validator that\n * refuses every browser origin, which is a coherent thing to ask for and a\n * surprising thing to arrive at by accident. Non-browser clients send no\n * `Origin` and pass either way, so an accidental `[]` looks like \"works for\n * my MCP client, broken for every page\". Omit the option when the intent is\n * no validation. Any other wrong shape — `null` from a config that had no\n * list, a bare string — is refused at registration rather than mounted.\n *\n * WHY hostnames, and why a separate list from {@link allowedHosts}: the two\n * answer different questions. `allowedHosts` is the hostname this server is\n * reached at; this is the hostname of a page allowed to reach it. On a local\n * app they coincide, both being loopback. On a deployed one they do not —\n * the API and the dashboard live at different names — so conflating them\n * either refuses the dashboard or forces the host list wide enough to weaken\n * the rebinding check.\n *\n * WHY hostnames and not origins: the underlying validator compares\n * hostnames, port-agnostically. Passing a full origin such as\n * `\"https://app.example.com\"` refuses that very origin, and passing `\"*\"`\n * refuses everything — both silently, since either is a valid `string[]`.\n * Anything shaped like a CORS `origin` list belongs in a CORS plugin, not\n * here.\n *\n * A request with no `Origin` header passes by design, so non-browser clients\n * are unaffected; only browsers are constrained.\n */\n allowedOriginHostnames?: string[];\n /**\n * Where an upstream failure is written. Defaults to the Fastify instance's\n * own request logger; pass one only to send these somewhere else.\n */\n logger?: ToolLogger;\n /** Called once per completed tool call. Errors thrown here are swallowed. */\n onToolCall?: (event: ToolCallEvent) => void;\n /** Tools the host adds to the server. See {@link HostTools}. */\n hostTools?: HostTools;\n}\n\n// Mirrors the identical augmentation in `@kopai/api`. Both packages mount into\n// the same Fastify instance and neither depends on the other, so each declares\n// what it reads. The declarations are structurally identical, which is what\n// keeps them compatible when both are present.\ndeclare module \"fastify\" {\n interface FastifyRequest {\n requestContext?: unknown;\n }\n}\n","import type {\n JsonSchemaValidator,\n jsonSchemaValidator,\n} from \"@modelcontextprotocol/server\";\n\n/**\n * A validator provider that accepts everything, so that the tool handler is\n * what validates.\n *\n * Three reasons, and each would be sufficient on its own:\n *\n * 1. Correctness. The `query` schema is a union of six branches. The SDK's\n * default validator rejects before dispatch and answers with one text line\n * listing every branch's failures, which tells a model nothing about which\n * field it got wrong. The handler instead selects the one branch the\n * caller's `signal`/`mode` names and reports issues against it.\n * 2. Cost. The default provider is AJV-backed and compiles the schema it is\n * given. The transport builds a fresh server per request, so that\n * compilation would happen on every call.\n * 3. Observability. A rejection made before dispatch never reaches the\n * handler, so it never reaches `onToolCall` — the counter would undercount\n * exactly the failures most worth seeing.\n *\n * NOTE the shape: `fromJsonSchema`'s second argument is a provider object with\n * a `getValidator` method, not a validator function. Passing a bare function\n * throws `TypeError: validator.getValidator is not a function`, which the SDK\n * swallows into a 500 on `initialize` — presenting as \"the whole server is\n * broken\" rather than as a bad argument.\n */\nexport const passThroughValidator: jsonSchemaValidator = {\n getValidator<T>(): JsonSchemaValidator<T> {\n return (input: unknown) => ({\n valid: true,\n data: input as T,\n errorMessage: undefined,\n });\n },\n};\n","import { fromJsonSchema, type McpServer } from \"@modelcontextprotocol/server\";\n\nimport {\n isResourceLimitError,\n LIMITS,\n MAX_RESULT_CHARACTERS,\n RESOURCE_LIMIT_REMEDIES,\n} from \"./limits.js\";\nimport {\n METRICS_DISCOVER_TOOL_INPUT_SCHEMA,\n QUERY_TOOL_INPUT_SCHEMA,\n} from \"./schema.js\";\nimport { errorResult, type ToolResult } from \"./results.js\";\nimport {\n fromThrown,\n runMetricsDiscoverTool,\n runQueryTool,\n tooExpensive,\n type ToolContext,\n} from \"./tools.js\";\nimport {\n TOOL_CALL_OUTCOMES,\n type ToolCallOutcome,\n type ToolLogger,\n} from \"./types.js\";\nimport { passThroughValidator } from \"./validator.js\";\n\n/**\n * Both tools read and never write, always return the same answer for the same\n * arguments and window, and reach nothing outside this deployment.\n *\n * Each tool repeats its `title` inside `annotations`: the 2025-03-26 spec has\n * no top-level tool `title`, so clients and checks built on it (including the\n * Claude connector directory check) read it only from there.\n */\nconst READ_ONLY = {\n readOnlyHint: true,\n idempotentHint: true,\n openWorldHint: false,\n} as const;\n\n/**\n * Descriptions are deliberately flat: what the tool does, the shape of its\n * input, and the limits. They carry no instructions aimed at the model —\n * these strings are read by Directory review, and a tool description is not a\n * place to steer behaviour.\n */\nconst QUERY_DESCRIPTION = [\n \"Query this workspace's OpenTelemetry traces, logs and metrics.\",\n \"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.\",\n `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.`,\n \"Aggregate is the compact shape; raw returns whole records and is for inspecting individual spans, logs or data points.\",\n // What decides whether a query fits. Stated here because the cost is a\n // product of two fields, and a field-level description can only speak for\n // one of them.\n \"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.\",\n \"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`.\",\n \"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.\",\n].join(\" \");\n\nconst METRICS_DISCOVER_DESCRIPTION = [\n \"List the metrics present in this workspace, with each metric's type, unit, description and the attribute keys and values seen on it.\",\n \"Takes no arguments.\",\n // Stated because the tool promises attribute values above, and a caller that\n // gets a response without them is owed the reason in the description as well\n // as in the response.\n `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.`,\n].join(\" \");\n\n/** The tools this package registers itself. A host tool may not reuse them. */\nexport const BUILT_IN_TOOL_NAMES = [\"query\", \"metrics_discover\"] as const;\n\nexport interface RegisterToolsOptions extends ToolContext {\n /**\n * Called once per completed tool call, after the result is built and before\n * it is returned.\n */\n onToolCall?: (event: {\n tool: string;\n outcome: ToolCallOutcome;\n durationMs: number;\n rowCount?: number;\n }) => void;\n}\n\n/** A completed run of any tool, built-in or host. */\ninterface Run<R> {\n result: R;\n outcome: ToolCallOutcome;\n rowCount?: number;\n}\n\n/**\n * Returns the function that runs one tool call and reports it, whatever\n * happens. Shared by the built-in and the host tools, so every tool on the\n * server reaches `onToolCall` through this one place.\n *\n * WHY the catch: a throw out of a tool used to skip `observe` altogether, so\n * the host's counter lost exactly the calls most worth seeing — and the SDK\n * turned it into a bare message with no `structuredContent`, which is the\n * one error shape a page cannot read. Nothing in the tools is expected to\n * throw; that is the reason to handle it here rather than to assume it, and\n * converting it gives an unexpected failure the same contract as an expected\n * one: a structured payload, a logged cause, and one observer event.\n */\nfunction observedCall(opts: RegisterToolsOptions) {\n const observe = (\n tool: string,\n startedAt: number,\n outcome: ToolCallOutcome,\n rowCount?: number\n ): void => {\n if (!opts.onToolCall) return;\n // Guarded: an observer that throws is the host application's problem and\n // must not turn a successful query into a failed tool call.\n try {\n opts.onToolCall({\n tool,\n outcome,\n durationMs: Date.now() - startedAt,\n ...(rowCount !== undefined ? { rowCount } : {}),\n });\n } catch {\n // deliberately swallowed\n }\n };\n\n return async <R>(\n tool: string,\n execute: () => Promise<Run<R>>\n ): Promise<R | ToolResult> => {\n const startedAt = Date.now();\n let run: Run<R | ToolResult>;\n try {\n run = await execute();\n } catch (error) {\n run = fromThrown(error, opts.logger);\n }\n observe(tool, startedAt, run.outcome, run.rowCount);\n return run.result;\n };\n}\n\n/**\n * Registers the `query` and `metrics_discover` tools on `server`.\n *\n * Every call reports to `opts.onToolCall` exactly once, including a call whose\n * tool throws, which is returned as a structured error rather than rethrown.\n */\nexport function registerTools(\n server: McpServer,\n opts: RegisterToolsOptions\n): void {\n const call = observedCall(opts);\n\n server.registerTool(\n \"query\",\n {\n title: \"Query telemetry\",\n description: QUERY_DESCRIPTION,\n inputSchema: fromJsonSchema(\n QUERY_TOOL_INPUT_SCHEMA,\n passThroughValidator\n ),\n annotations: { ...READ_ONLY, title: \"Query telemetry\" },\n },\n async (input: unknown) =>\n call<ToolResult>(\"query\", () => runQueryTool(input, opts))\n );\n\n server.registerTool(\n \"metrics_discover\",\n {\n title: \"Discover metrics\",\n description: METRICS_DISCOVER_DESCRIPTION,\n inputSchema: fromJsonSchema(\n METRICS_DISCOVER_TOOL_INPUT_SCHEMA,\n passThroughValidator\n ),\n annotations: { ...READ_ONLY, title: \"Discover metrics\" },\n },\n async () =>\n call<ToolResult>(\"metrics_discover\", () => runMetricsDiscoverTool(opts))\n );\n}\n\nconst ERROR_CODES: ReadonlySet<string> = new Set(\n TOOL_CALL_OUTCOMES.filter((outcome) => outcome !== \"ok\")\n);\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\n/**\n * Reads a host tool's outcome from the result it returned.\n *\n * WHY reading is safe here, when `ToolRun` returns the outcome rather than\n * inferring it: `errorResult` is the one builder of an error result, and it\n * always writes the code. A hand-built error result has no code to read; it\n * is counted as `upstream_error`, the same label an unexpected throw gets, and\n * logged so the tool can be fixed. It is not thrown: the caller already has\n * an answer, and the tool's own text is more use to it than ours.\n */\nfunction hostOutcome(\n tool: string,\n result: unknown,\n logger: ToolLogger | undefined\n): ToolCallOutcome {\n if (!isRecord(result) || result.isError !== true) return \"ok\";\n const code = isRecord(result.structuredContent)\n ? result.structuredContent.error\n : undefined;\n if (typeof code === \"string\" && ERROR_CODES.has(code)) {\n return code as ToolCallOutcome;\n }\n logger?.error(\n { tool },\n \"MCP host tool returned an error result without a known error code\"\n );\n return \"upstream_error\";\n}\n\n/**\n * A host tool's throw, converted as `fromThrown` converts a built-in's, with\n * two differences: the generic message names no query, since a host tool need\n * not run one, and the log line names the tool.\n *\n * A resource limit is classified here too: a host tool that reads telemetry\n * (a backtest, say) lets its query's throw through, and would otherwise\n * report a limit the caller can get past as a generic failure.\n */\nfunction thrownByHostTool(\n tool: string,\n error: unknown,\n logger: ToolLogger | undefined\n): Run<ToolResult> {\n logger?.error(error, `MCP host tool \"${tool}\" failed`);\n if (isResourceLimitError(error)) {\n return tooExpensive(\n \"The query behind this tool call was stopped at this deployment's limit on query time, memory or rows read.\",\n RESOURCE_LIMIT_REMEDIES\n );\n }\n return {\n result: errorResult({\n error: \"upstream_error\",\n message: \"The tool call could not be completed.\",\n }),\n outcome: \"upstream_error\",\n };\n}\n\ntype HostCallback = (...args: unknown[]) => unknown;\n\nexport interface RegisterHostToolsOptions extends RegisterToolsOptions {\n /** Every name `register` may use; checked at plugin registration. */\n names: ReadonlySet<string>;\n register: (server: McpServer) => void;\n}\n\n/**\n * Runs the host's `register` on `server`, with `registerTool` guarded and\n * observed.\n *\n * The guard is installed on this one per-request instance, through the SDK's\n * public API only. It refuses a name not in `names`, so the check made at\n * boot cannot be bypassed through `registerTool` or `update` — a host that\n * reaches past them, by writing `handle.executor` or calling the prototype's\n * `registerTool`, is not guarded, and is not meant to be. It wraps the\n * returned handle's `update` as well: `update({ name })` renames a registered tool, and `update({ callback\n * })` swaps its callback, either of which would otherwise slip past the guard.\n * `remove()` is `update({ name: null })` in the SDK and passes.\n *\n * A refusal throws, and so does anything else `register` throws. Both fail the\n * request; see {@link HostTools}.\n */\nexport function registerHostTools(\n server: McpServer,\n opts: RegisterHostToolsOptions\n): void {\n const call = observedCall(opts);\n const assertDeclared = (name: string): void => {\n if (opts.names.has(name)) return;\n const declared = [...opts.names].map((n) => `\"${n}\"`).join(\", \");\n throw new TypeError(\n `Host tool \"${name}\" is not in hostTools.names (${declared || \"none declared\"}). Declare every name register may use.`\n );\n };\n\n const registerTool = server.registerTool.bind(server) as (\n name: string,\n config: unknown,\n callback: HostCallback\n ) => ReturnType<McpServer[\"registerTool\"]>;\n\n // Every observed wrapper, mapped to the host callback it wraps; read by the\n // `handler` accessor below.\n const wrapped = new WeakMap<HostCallback, HostCallback>();\n\n // Names in use on this server. The SDK refuses to register a name twice,\n // but a rename onto a name in use silently replaces that tool — a tool\n // missing because of a bug, which is what failing the request is for.\n const inUse = new Set<string>();\n\n const guarded = (name: string, config: unknown, callback: HostCallback) => {\n assertDeclared(name);\n // WHY: the SDK checks an output schema after the callback returns, so a\n // mismatch is counted `ok` while the caller receives the SDK's own bare\n // error, which breaks the error contract for that tool.\n const refuseOutputSchema = (value: unknown, tool: string): void => {\n if (value === undefined) return;\n throw new TypeError(\n `Host tool \"${tool}\" declares an outputSchema; host tools may not.`\n );\n };\n refuseOutputSchema(\n isRecord(config) ? config.outputSchema : undefined,\n name\n );\n let current = name;\n const observed = (inner: HostCallback): HostCallback => {\n const outer: HostCallback = (...args) =>\n call(current, async () => {\n let result: unknown;\n try {\n result = await inner(...args);\n } catch (error) {\n return thrownByHostTool(current, error, opts.logger);\n }\n return {\n result,\n outcome: hostOutcome(current, result, opts.logger),\n };\n });\n wrapped.set(outer, inner);\n return outer;\n };\n\n const handle = registerTool(name, config, observed(callback));\n inUse.add(name);\n\n // WHY an accessor: the SDK keeps the callback it was given on the public\n // `handler` field, which here is the wrapper. A host decorating its tool\n // with `update({ callback: withAudit(handle.handler) })` would wrap the\n // wrapper, and every call would be counted twice. The host reads back its\n // own callback instead; the SDK's write in `update` is mapped the same\n // way. The SDK calls through its own closure, never through this field.\n let raw: unknown = callback;\n Object.defineProperty(handle, \"handler\", {\n get: () => raw,\n set: (value: HostCallback) => {\n raw = wrapped.get(value) ?? value;\n },\n enumerable: true,\n configurable: true,\n });\n const update = handle.update;\n handle.update = (updates) => {\n refuseOutputSchema(updates.outputSchema, current);\n const renamed =\n updates.name !== undefined && updates.name !== current\n ? updates.name\n : undefined;\n if (typeof renamed === \"string\") {\n assertDeclared(renamed);\n if (inUse.has(renamed)) {\n throw new TypeError(\n `Host tool \"${current}\" cannot be renamed to \"${renamed}\", which is already registered.`\n );\n }\n }\n update(\n updates.callback === undefined\n ? updates\n : {\n ...updates,\n callback: observed(\n updates.callback as HostCallback\n ) as typeof updates.callback,\n }\n );\n if (renamed !== undefined) {\n inUse.delete(current);\n // `null` is the SDK's `remove()`.\n if (renamed !== null) {\n inUse.add(renamed);\n current = renamed;\n }\n }\n };\n return handle;\n };\n server.registerTool = guarded as McpServer[\"registerTool\"];\n\n // Typed `void`, but an `async` function satisfies that type. Its promise\n // would be dropped: whatever it registers after an `await` is never\n // listed, and a rejection goes unhandled.\n const returned: unknown = opts.register(server);\n if (returned instanceof Promise) {\n returned.catch(() => {});\n throw new TypeError(\n \"hostTools.register returned a promise; it must be synchronous. Do the I/O in a preHandler and read its result from the request.\"\n );\n }\n}\n","import {\n hostHeaderValidation,\n originValidation,\n} from \"@modelcontextprotocol/fastify\";\nimport { toNodeHandler } from \"@modelcontextprotocol/node\";\nimport { createMcpHandler, McpServer } from \"@modelcontextprotocol/server\";\nimport type { FastifyPluginAsync, FastifyReply, FastifyRequest } from \"fastify\";\n\nimport {\n BUILT_IN_TOOL_NAMES,\n registerHostTools,\n registerTools,\n type RegisterToolsOptions,\n} from \"./register.js\";\nimport type { HostTools, McpRoutesOptions } from \"./types.js\";\n\nconst SERVER_NAME = \"kopai\";\nconst SERVER_VERSION = \"0.0.0\";\n\n// The MCP tool-name rule. The SDK checks the same pattern but only warns,\n// once per server, which on a per-request server is once per request.\nconst TOOL_NAME = /^[A-Za-z0-9._-]{1,128}$/;\n\n/**\n * Checks `hostTools` once, at registration, and returns its names as a set.\n *\n * Refused rather than absorbed, for the reason `allowedOriginHostnames` is: a\n * wrong shape would otherwise fail on every request, and a name colliding\n * with a built-in would fail only when a caller who may use it arrives.\n */\nfunction checkedHostToolNames(hostTools: HostTools): ReadonlySet<string> {\n if (\n typeof hostTools !== \"object\" ||\n hostTools === null ||\n typeof hostTools.register !== \"function\" ||\n !Array.isArray(hostTools.names) ||\n hostTools.names.some((name) => typeof name !== \"string\")\n ) {\n throw new TypeError(\n 'hostTools must be { names: string[]; register: (server, request) => void }, e.g. { names: [\"alert_get\"], register }. Omit it to add no tools.'\n );\n }\n const names = new Set<string>();\n const builtIns: readonly string[] = BUILT_IN_TOOL_NAMES;\n for (const name of hostTools.names) {\n if (!TOOL_NAME.test(name)) {\n throw new TypeError(\n `hostTools.names: \"${name}\" is not an MCP tool name (1 to 128 of A-Z, a-z, 0-9, \".\", \"_\", \"-\").`\n );\n }\n if (builtIns.includes(name)) {\n throw new TypeError(\n `hostTools.names: \"${name}\" is the name of a built-in tool.`\n );\n }\n if (names.has(name)) {\n throw new TypeError(`hostTools.names: \"${name}\" appears more than once.`);\n }\n names.add(name);\n }\n return names;\n}\n\n/**\n * Mounts the MCP endpoint at `/mcp`, relative to wherever this plugin is\n * registered.\n *\n * The server is stateless: no session id, no server push, and a fresh\n * `McpServer` per request.\n */\nexport const mcpRoutes: FastifyPluginAsync<McpRoutesOptions> =\n async function mcpRoutes(fastify, opts) {\n // Port-agnostic allow-list on the Host header. This is what stops a page\n // on another origin from resolving a name it controls to 127.0.0.1 and\n // reaching a local server through the browser — the request arrives with\n // the attacker's hostname in `Host`, and that is what is checked.\n fastify.addHook(\"onRequest\", hostHeaderValidation(opts.allowedHosts));\n\n // Origin validation is opt-in, because the two mounts have different\n // threat models. An unauthenticated local app has nothing but these\n // headers between a web page and the data, and there the host and origin\n // lists genuinely coincide — both are loopback. A deployed, authenticated\n // mount has the credential as its boundary and usually already runs a CORS\n // policy; adding a second, independently configured origin list there buys\n // little and strands a future browser client behind a validator nobody\n // remembers configuring.\n //\n // Host validation alone does not close this: a page that simply fetches\n // http://127.0.0.1:<port>/mcp sends a genuinely loopback `Host`, and only\n // `Origin` says who asked. That such a request is blocked today is\n // incidental — it needs a CORS preflight, `OPTIONS` is unrouted, and the\n // local app registers no CORS — and it stops being true the moment any of\n // those three changes.\n if (opts.allowedOriginHostnames !== undefined) {\n // Checked rather than trusted, and refused here rather than absorbed:\n // every wrong shape fails silently at request time, and two of them fail\n // permissively.\n //\n // `null` — what a config read from JSON or an env var yields where a\n // list is missing — counts as \"configured\", and the validator then calls\n // `null.includes(hostname)` inside an `onRequest` hook, so every request\n // to the endpoint 500s with nothing naming the option that did it. A\n // bare string is worse than broken: `String.prototype.includes` matches\n // substrings, so `\"localhost\"` would admit an origin whose hostname is\n // `\"host\"`.\n //\n // WHY a throw and not a no-op: this option exists to restrict, and the\n // caller who passed it believes they are protected. Quietly mounting\n // nothing would leave them unprotected and unaware — the one outcome\n // worse than a startup failure. Registration runs once, at boot, so this\n // cannot fire on live traffic.\n if (\n !Array.isArray(opts.allowedOriginHostnames) ||\n opts.allowedOriginHostnames.some((name) => typeof name !== \"string\")\n ) {\n throw new TypeError(\n 'allowedOriginHostnames must be an array of hostname strings, e.g. [\"localhost\", \"127.0.0.1\"]. Omit it to mount no origin validation.'\n );\n }\n fastify.addHook(\n \"onRequest\",\n originValidation(opts.allowedOriginHostnames)\n );\n }\n\n const hostTools =\n opts.hostTools === undefined\n ? undefined\n : {\n names: checkedHostToolNames(opts.hostTools),\n register: opts.hostTools.register,\n };\n\n const handleMcp = async (\n request: FastifyRequest,\n reply: FastifyReply\n ): Promise<void> => {\n // RFC 9110 makes `Allow` a MUST on a 405, and the SDK sends none.\n //\n // NOTE it must be set on `reply.raw`, not through `reply.header()`.\n // Fastify stages headers on its own reply object and flushes them when\n // it serializes the response — which never happens once the reply is\n // hijacked, so `reply.header()` here is silently dropped. Writing to the\n // Node response directly is what survives.\n //\n // Only for the methods that will 405: a successful POST has no business\n // advertising `Allow`.\n if (request.method !== \"POST\") {\n reply.raw.setHeader(\"Allow\", \"POST\");\n }\n\n // WHY the factory is built here, inside the route handler, rather than\n // once at registration: the tool callbacks close over `request`\n // lexically, so the host application's per-request context reaches the\n // datasource without this package knowing anything about tenants or\n // credentials. That makes the handler per-request too.\n //\n // The alternative, AsyncLocalStorage, was rejected for consistency:\n // this codebase threads `requestContext` explicitly at every existing\n // call site and uses AsyncLocalStorage nowhere.\n //\n // NOTE `responseMode` is deliberately not passed. It is byte-identical\n // to the `auto` default across every combination measured, its only\n // observable effect is a console.warn emitted once per\n // `createMcpHandler` — which here is once per request — and it silently\n // drops mid-call notifications.\n const handler = createMcpHandler(() => {\n const server = new McpServer({\n name: SERVER_NAME,\n version: SERVER_VERSION,\n });\n const toolOptions: RegisterToolsOptions = {\n readTelemetryDatasource: opts.readTelemetryDatasource,\n requestContext: request.requestContext,\n // Per-request, so an upstream failure is logged with the same\n // request id as everything else Fastify wrote about that call.\n logger: opts.logger ?? request.log,\n // The request is attached here rather than inside the tool layer,\n // which knows nothing about HTTP.\n onToolCall: opts.onToolCall\n ? (event) => opts.onToolCall?.({ ...event, request })\n : undefined,\n };\n registerTools(server, toolOptions);\n // After the built-ins, so a host tool can never take their place. A\n // throw here fails this request rather than falling back to the\n // built-ins alone.\n //\n // NOTE logged here because nothing else logs it: the SDK answers a\n // throwing factory with a bare JSON-RPC internal error and passes the\n // error to no `onerror`.\n if (hostTools !== undefined) {\n try {\n registerHostTools(server, {\n ...toolOptions,\n names: hostTools.names,\n register: (s) => hostTools.register(s, request),\n });\n } catch (error) {\n toolOptions.logger?.error(error, \"MCP hostTools.register failed\");\n throw error;\n }\n }\n return server;\n });\n\n reply.hijack();\n // The third argument is the body Fastify has already parsed and\n // drained; passing it means nothing is read from a stream that is\n // already consumed.\n await toNodeHandler(handler, {\n onerror: (error: unknown) => fastify.log.error(error),\n })(request.raw, reply.raw, request.body);\n };\n\n // POST is the endpoint. GET and DELETE are routed only so that the SDK\n // gets to answer them 405 — with just a POST route, Fastify's own 404\n // handler replies first and the SDK is never consulted. The difference is\n // not cosmetic: Streamable HTTP defines GET as \"open an SSE stream\", and\n // requires either an event-stream response or a 405. A client that probes\n // GET and receives 404 reads the endpoint as gone rather than as healthy\n // and non-streaming.\n //\n // OPTIONS is deliberately left unrouted. The SDK would answer it 405 like\n // any other non-POST method, which would intercept CORS preflight — and\n // preflight belongs to whatever CORS plugin the host application\n // registers, which differs between the two mounts. PUT and PATCH stay\n // unrouted too and fall through to Fastify's 404; the spec says nothing\n // about them and no client sends them.\n fastify.route({ method: \"POST\", url: \"/mcp\", handler: handleMcp });\n fastify.route({ method: \"GET\", url: \"/mcp\", handler: handleMcp });\n fastify.route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Y,KAAK,cACZ,UAAU,KAAK,aAAa;KAAE,GAAG;KAAO;IAAQ,CAAC,IAClD,KAAA;GACN;GACA,cAAc,QAAQ,WAAW;GAQjC,IAAI,cAAc,KAAA,GAChB,IAAI;IACF,kBAAkB,QAAQ;KACxB,GAAG;KACH,OAAO,UAAU;KACjB,WAAW,MAAM,UAAU,SAAS,GAAG,OAAO;IAChD,CAAC;GACH,SAAS,OAAO;IACd,YAAY,QAAQ,MAAM,OAAO,+BAA+B;IAChE,MAAM;GACR;GAEF,OAAO;EACT,CAAC;EAED,MAAM,OAAO;EAIb,MAAM,cAAc,SAAS,EAC3B,UAAU,UAAmB,QAAQ,IAAI,MAAM,KAAK,EACtD,CAAC,CAAC,CAAC,QAAQ,KAAK,MAAM,KAAK,QAAQ,IAAI;CACzC;CAgBA,QAAQ,MAAM;EAAE,QAAQ;EAAQ,KAAK;EAAQ,SAAS;CAAU,CAAC;CACjE,QAAQ,MAAM;EAAE,QAAQ;EAAO,KAAK;EAAQ,SAAS;CAAU,CAAC;CAChE,QAAQ,MAAM;EAAE,QAAQ;EAAU,KAAK;EAAQ,SAAS;CAAU,CAAC;AACrE"}
1
+ {"version":3,"file":"index.mjs","names":["fromJsonSchema"],"sources":["../src/dedupe.ts","../src/limits.ts","../src/describe.ts","../src/schema.ts","../src/results.ts","../src/tools.ts","../src/types.ts","../src/validator.ts","../src/register.ts","../src/routes.ts"],"sourcesContent":["// Hoists structurally identical subschemas of a JSON Schema 2020-12 document\n// into `$defs` and replaces each occurrence with a `$ref`.\n//\n// WHY: the `query` tool advertises the whole KopaiQuery union as its input\n// schema, and the union repeats the same column enums, filter expressions and\n// time-dimension shapes across all six branches. Emitted verbatim the document\n// is ~132k characters, and a host carries it in its `tools:` array on every\n// turn, not once per connection. Deduplication is the only reduction that\n// costs the model nothing: every alternative measured (dropping descriptions,\n// collapsing enums) removes exactly the text a model needs to build a correct\n// query.\n//\n// WHY keyword-aware rather than a blind object walk: in JSON Schema a nested\n// object is not always a schema. `properties` maps property *names* to\n// schemas, so its keys must not be treated as keywords; `const`, `enum`,\n// `examples` and `default` hold data that may look like a schema but is not.\n// Hoisting a value out of one of those would change what the document\n// accepts. The three sets below enumerate the only places a schema may\n// legally appear.\n\ntype SchemaNode = Record<string, unknown>;\n\n/** Keywords whose value is a single schema. */\nconst SCHEMA_VALUE = new Set([\n \"items\",\n \"additionalProperties\",\n \"additionalItems\",\n \"contains\",\n \"propertyNames\",\n \"not\",\n \"if\",\n \"then\",\n \"else\",\n \"unevaluatedItems\",\n \"unevaluatedProperties\",\n]);\n\n/** Keywords whose value is an array of schemas. */\nconst SCHEMA_ARRAY = new Set([\"allOf\", \"anyOf\", \"oneOf\", \"prefixItems\"]);\n\n/** Keywords whose value maps arbitrary names to schemas. */\nconst SCHEMA_MAP = new Set([\n \"properties\",\n \"patternProperties\",\n \"dependentSchemas\",\n \"$defs\",\n \"definitions\",\n]);\n\n/**\n * Rebuilds `node`, invoking `cb` on every descendant that is itself a schema.\n * Returning a value from `cb` replaces that subtree; returning `undefined`\n * descends into it. The root is never offered to `cb` — a document cannot be\n * replaced by a reference to itself.\n */\nfunction eachSchema(\n node: unknown,\n cb: (node: SchemaNode) => SchemaNode | undefined,\n isRoot = false\n): unknown {\n if (!node || typeof node !== \"object\" || Array.isArray(node)) return node;\n const obj = node as SchemaNode;\n\n if (!isRoot) {\n const replacement = cb(obj);\n if (replacement !== undefined) return replacement;\n }\n\n const out: SchemaNode = {};\n for (const [key, value] of Object.entries(obj)) {\n if (\n SCHEMA_VALUE.has(key) &&\n value &&\n typeof value === \"object\" &&\n !Array.isArray(value)\n ) {\n out[key] = eachSchema(value, cb);\n } else if (SCHEMA_ARRAY.has(key) && Array.isArray(value)) {\n out[key] = value.map((s) => eachSchema(s, cb));\n } else if (SCHEMA_MAP.has(key) && value && typeof value === \"object\") {\n out[key] = Object.fromEntries(\n Object.entries(value as SchemaNode).map(([name, s]) => [\n name,\n eachSchema(s, cb),\n ])\n );\n } else {\n out[key] = value;\n }\n }\n return out;\n}\n\n/**\n * Returns `doc` with every subschema that occurs more than once hoisted into\n * `$defs`.\n *\n * `minLen` is the serialized length below which a repeat is not worth a\n * reference — a `$ref` costs about 30 characters, so hoisting anything\n * shorter makes the document bigger. Any existing `$defs` are preserved and\n * deduplicated alongside the body.\n */\nexport function dedupe(doc: SchemaNode, minLen = 60): SchemaNode {\n const existingDefs = (doc.$defs as Record<string, SchemaNode>) ?? {};\n\n // 1. Count structurally identical nodes. The root is excluded, and each\n // existing $defs body is counted from its own root for the same reason.\n const counts = new Map<string, number>();\n const body = { ...doc };\n delete body.$defs;\n\n const count = (n: SchemaNode): undefined => {\n const key = JSON.stringify(n);\n if (key.length >= minLen) counts.set(key, (counts.get(key) ?? 0) + 1);\n return undefined;\n };\n\n eachSchema(body, count, true);\n for (const def of Object.values(existingDefs)) eachSchema(def, count, true);\n\n // 2. Hoist everything seen at least twice. Longest first, so that a large\n // repeated shape becomes one definition rather than being shredded into\n // references to its own parts.\n const refNames = new Map<string, string>();\n const newDefs: Record<string, SchemaNode> = {};\n let next = 0;\n for (const [key, seen] of [...counts.entries()].sort(\n (a, b) => b[0].length - a[0].length\n )) {\n if (seen < 2) continue;\n // Step over any name the document already defines. The write loop below\n // lets an existing definition win, so a collision would drop the hoisted\n // body and leave every `$ref` substituted for it pointing at an\n // unrelated schema — a document that still compiles but accepts\n // different input.\n let name = `s${next++}`;\n while (Object.hasOwn(existingDefs, name)) name = `s${next++}`;\n refNames.set(key, name);\n newDefs[name] = JSON.parse(key) as SchemaNode;\n }\n\n const substitute = (n: SchemaNode): SchemaNode | undefined => {\n const name = refNames.get(JSON.stringify(n));\n return name === undefined ? undefined : { $ref: `#/$defs/${name}` };\n };\n\n // 3. Rewrite the document, then each hoisted body. A body must skip the\n // match against itself, or every definition becomes a reference to\n // itself and the document stops meaning anything.\n const result = eachSchema(doc, substitute, true) as SchemaNode;\n const defs: Record<string, SchemaNode> = {\n ...((result.$defs as Record<string, SchemaNode>) ?? {}),\n };\n\n for (const [name, defBody] of [\n ...Object.entries(newDefs),\n ...Object.entries(existingDefs),\n ]) {\n const self = JSON.stringify(defBody);\n defs[name] = eachSchema(\n defBody,\n (n) => (JSON.stringify(n) === self ? undefined : substitute(n)),\n true\n ) as SchemaNode;\n }\n\n result.$defs = defs;\n return result;\n}\n","import { kopaiQuery } from \"@kopai/core\";\n\n/**\n * Row caps, per mode.\n *\n * WHY per mode rather than one number: measured serialized row sizes differ by\n * an order of magnitude. A raw trace row is ~703 characters, a raw log row\n * ~418, a raw metric row 408-653 (OTel repeats the metric name, description\n * and unit on every data point), against ~96 for an aggregate summary row and\n * ~134 for a `timeSeries` row. Against the character ceiling below, a uniform\n * cap of 500 would let every raw shape overrun — traces by 134%, logs by 39%,\n * metrics by 36-118% — so a raw query that used its own cap would pay for a\n * full round trip and then have the result refused.\n *\n * At 200 they all fit, though traces land at ~94% of budget, which is why the\n * post-serialization check stays load-bearing rather than being a formality.\n * Treat these figures as optimistic: they come from fixtures, and production\n * attribute maps are heavier.\n *\n * The consequence for callers, worth stating in the tool description: the\n * aggregate shape is the efficient one and raw is for inspecting individual\n * records. One hour of one gauge costs roughly 116,400 characters as raw rows\n * against 8,040 as a `timeSeries` aggregate at `1m` — fourteen times less, for\n * the same chart, with the bucketing done in the database.\n */\nexport const LIMITS = {\n raw: {\n /** Applied when the caller sends no `limit`; matches the backend default. */\n fallback: 100,\n max: 200,\n },\n aggregate: {\n /**\n * Applied when the caller sends no `limit`. Unlike raw, this is not a\n * backend default being restated: both backends emit `LIMIT` for an\n * aggregate query only when one is explicitly set, so an aggregate query\n * with no limit runs unbounded.\n */\n fallback: 500,\n max: 500,\n },\n} as const;\n\n/**\n * The serialized size past which a result is refused rather than returned.\n *\n * Measured after serialization, on one copy of the payload — the result\n * carries the same JSON in two channels, but a client forwards one or the\n * other, so the model only ever ingests it once.\n */\nexport const MAX_RESULT_CHARACTERS = 150_000;\n\n/**\n * Remedies for a discovery listing too large even with the attributes gone.\n *\n * WHY its own list: `metrics_discover` takes no arguments, so every line in\n * `SIZE_REMEDIES` names a field the caller cannot set — a `limit`, a window, a\n * `granularity`. Offering those turned an over-size listing into a dead end\n * dressed up as advice. Nothing the caller writes can shrink this result, so\n * the honest answer is what remains possible without it.\n */\nexport const DISCOVERY_SIZE_REMEDIES = [\n \"Query a metric by name with the `query` tool — discovery is not a prerequisite for it.\",\n \"Ask an operator to reduce what this deployment ingests: this workspace holds more metrics than one response can carry.\",\n] as const;\n\n/**\n * ClickHouse error codes for a query stopped at a resource limit: 158\n * TOO_MANY_ROWS, 159 TIMEOUT_EXCEEDED, 160 TOO_SLOW (the estimated time\n * already exceeds `max_execution_time`), 241 MEMORY_LIMIT_EXCEEDED, 307\n * TOO_MANY_BYTES, 396 TOO_MANY_ROWS_OR_BYTES.\n *\n * WHY ClickHouse codes in a package that knows no backend: the datasource\n * rethrows `@clickhouse/client`'s error as it is, so its `code` is the only\n * signal that reaches this layer. The SQLite datasource sets no such limits.\n * Mirrored in `@kopai/api`'s error handler, which cannot import from here.\n *\n * WHY not `@clickhouse/client`'s own \"Timeout error.\": it is a socket timeout,\n * and fires as readily for a server that stopped answering as for a heavy\n * query. A heavy query is expected to meet the server's `max_execution_time`\n * first, set by the host below the client's `request_timeout`, and fail with\n * 159; a client timeout is then an outage, and stays one.\n */\nconst RESOURCE_LIMIT_CODES: ReadonlySet<string> = new Set([\n \"158\",\n \"159\",\n \"160\",\n \"241\",\n \"307\",\n \"396\",\n]);\n\n/**\n * Whether a throw is a query stopped at a resource limit, which the caller\n * can get past by asking for less. Anything else stays an upstream error.\n *\n * A 241 for the server as a whole (\"(total) memory limit exceeded\") is\n * excluded: other queries or ingest used the memory, so asking for less does\n * not help.\n */\nexport function isResourceLimitError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n const { code } = error as { code?: unknown };\n if (typeof code !== \"string\" || !RESOURCE_LIMIT_CODES.has(code)) {\n return false;\n }\n return !(code === \"241\" && error.message.includes(\"(total)\"));\n}\n\n/** Remedies for a query stopped at a resource limit. */\nexport const RESOURCE_LIMIT_REMEDIES = [\n \"Narrow the time window.\",\n \"Add filters so fewer rows are read: `service.name` or another attribute, and for metrics a single `MetricName`.\",\n \"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.\",\n] as const;\n\n/**\n * Remedies for a discovery listing stopped at a resource limit. Its own list\n * for the reason {@link DISCOVERY_SIZE_REMEDIES} is: the tool takes no\n * arguments, so there is no window or filter to offer.\n */\nexport const DISCOVERY_RESOURCE_LIMIT_REMEDIES = [\n \"Query a metric by name with the `query` tool — discovery is not a prerequisite for it.\",\n \"Try again shortly: the listing may have run while this deployment was busy.\",\n] as const;\n\n/** Remedies offered when a result is too large once serialized. */\nexport const SIZE_REMEDIES = [\n \"Lower `limit`.\",\n \"Narrow the time window.\",\n \"Use a coarser `granularity`, or `output: {type: 'summary'}` instead of a time series.\",\n] as const;\n\n/**\n * How many time buckets the window will be cut into, or 1 for a summary.\n *\n * WHY this is worth computing: an aggregate's row count is groups times\n * buckets, and the two need opposite advice. Buckets are exactly derivable\n * from the window and the granularity, which is enough to tell the two causes\n * apart — if the buckets alone exceed the cap then no amount of regrouping\n * will help, and if they do not then the group cardinality is what overran.\n *\n * WHY boundaries rather than whole spans: neither backend cuts the window into\n * granularity-sized pieces starting at its own start. Both snap each timestamp\n * to a fixed boundary measured from the epoch — `(ts / g) * g` in SQLite,\n * `toStartOfInterval(ts, INTERVAL n SECOND)` in ClickHouse — so a window that\n * does not begin on a boundary straddles one more bucket than it has whole\n * granularities. Measured against a real SQLite datasource: an hour at `5m`\n * starting at :02:30 produces thirteen distinct `bucket_start` values, not\n * twelve. Counting whole spans understated every unaligned window by one.\n */\nfunction bucketCount(query: kopaiQuery.KopaiQuery): number {\n if (query.mode !== \"aggregate\" || query.output.type !== \"timeSeries\")\n return 1;\n\n const granularityNs = kopaiQuery.durationStringToNanos(\n query.output.granularity\n );\n if (typeof granularityNs !== \"number\" || granularityNs <= 0) return 1;\n\n const window = query.timeDimension;\n\n if (window.type === \"relative\") {\n const lookbackNs = kopaiQuery.durationStringToNanos(window.lookback);\n if (typeof lookbackNs !== \"number\" || lookbackNs <= 0) return 1;\n // A relative window ends at the clock reading taken when the query runs,\n // so where it falls against the boundaries is not knowable from the query\n // alone. One extra bucket is the bound that holds for every alignment.\n return Math.ceil(lookbackNs / granularityNs) + 1;\n }\n\n // An absolute window is exact. Work in milliseconds: a granularity is a\n // whole number of seconds, and epoch nanoseconds are past the range a\n // double represents exactly.\n const startMs = Date.parse(window.startTime);\n const endMs = Date.parse(window.endTime);\n if (!Number.isFinite(startMs) || !Number.isFinite(endMs) || endMs <= startMs)\n return 1;\n const granularityMs = granularityNs / 1e6;\n\n // The window is half-open (`>= start AND < end` in both backends), so the\n // last bucket is the last boundary strictly below `endTime`.\n const firstBoundary = Math.floor(startMs / granularityMs);\n const lastBoundary = Math.ceil(endMs / granularityMs) - 1;\n return Math.max(1, lastBoundary - firstBoundary + 1);\n}\n\n/**\n * Remedies for an aggregate query that overran its cap, ordered by whichever\n * factor actually caused it.\n *\n * WHY ordered rather than a fixed list: an aggregate returns groups times\n * buckets rows, and advice for one is useless for the other. Telling someone\n * grouping by a high-cardinality column in a `summary` query to use a coarser\n * granularity names a field their query does not have; telling someone whose\n * window is cut into more buckets than the cap allows to group by less will\n * not help them either.\n *\n * WHY there is no \"add an `orderBy`\" line: an ordering does not change the\n * outcome. An overflow is refused whether or not the query is ordered, because\n * a live page cannot act on a remedy — its query was fixed at authoring time\n * and its viewer did not write it — so a truncated result would be drawn as\n * though it were the whole set.\n */\nexport function overflowRemedies(\n query: kopaiQuery.KopaiQuery,\n limit: number,\n max: number\n): string[] {\n // Read off the query rather than inferred from the bucket count: a window\n // that happens to span one bucket is still a time series, and classifying it\n // as a summary dropped the one remedy that always works on it — asking for a\n // summary instead — while offering advice about a `granularity` the caller\n // was told the query does not have. `output.type` is the authoritative\n // discriminator; the bucket count only orders the advice.\n const isTimeSeries =\n query.mode === \"aggregate\" && query.output.type === \"timeSeries\";\n const buckets = bucketCount(query);\n const grouped =\n query.mode === \"aggregate\" && (query.dimensions?.length ?? 0) > 0;\n\n const raiseLimit = limit < max ? [`Raise \\`limit\\`, up to ${max}.`] : [];\n // States what the declared window spans, not how many rows came back: a\n // bucket only materialises where there is data, so this is an upper bound.\n // It is still the useful number, because it is the one the caller chose.\n 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.`;\n const fewerGroups =\n \"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.\";\n const narrower = \"Narrow the time window.\";\n const summarise_ =\n 'Use `output: { type: \"summary\" }` if the trend over time is not what you need.';\n\n // The buckets alone exceed the cap, so this cannot be regrouped out of.\n if (isTimeSeries && buckets > limit) {\n return [...raiseLimit, coarser, narrower, summarise_];\n }\n\n if (isTimeSeries) {\n // Rows are groups times buckets and the buckets fit, so the groups are\n // what overran — but a coarser granularity still divides the total, so it\n // stays on the list, second. Not where the window spans a single bucket,\n // though: there is nothing for a coarser one to merge, and the line would\n // read \"spans up to 1 buckets\".\n const coarserIfItHelps = buckets > 1 ? [coarser] : [];\n return grouped\n ? [...raiseLimit, fewerGroups, ...coarserIfItHelps, narrower, summarise_]\n : [...raiseLimit, ...coarserIfItHelps, narrower, summarise_];\n }\n\n // A summary query has no granularity at all; naming one would be noise.\n return [...raiseLimit, fewerGroups, narrower];\n}\n","// Rewriting the advertised schema's guidance without touching the shared one.\n//\n// WHY this exists: the `KopaiQuery` schema is shared with the REST routes, and\n// some of what it says is true there and false here. Its `limit` field\n// advertises \"Hard cap = 10000\", which is REST's cap; this tool refuses\n// anything above 200 or 500. A model reading the field-level description —\n// the text nearest the decision — writes a limit it will be refused for.\n//\n// The same schema is also silent on cost. It says what `granularity` and\n// `dimensions` mean, but not that together they set the row count, which is\n// the thing that decides whether a query succeeds.\n//\n// Both are fixed in the copy this tool advertises, leaving the shared schema\n// alone. Matching is by description prefix rather than by path, because the\n// same field appears once per signal with slightly different wording, and a\n// path list would rot silently. A test asserts every override still matches\n// something, so a reworded schema fails loudly instead of quietly dropping\n// the guidance.\n\ntype SchemaNode = Record<string, unknown>;\n\nexport interface DescriptionOverride {\n /** Start of the description to match, in the shared schema. */\n readonly prefix: string;\n /** Replaces the description outright, or extends it. */\n readonly mode: \"replace\" | \"append\";\n readonly text: string;\n}\n\nexport function descriptionOverrides(\n rawMax: number,\n aggregateMax: number,\n rawDefault: number,\n aggregateDefault: number\n): DescriptionOverride[] {\n return [\n {\n prefix: \"Maximum rows to return.\",\n mode: \"replace\",\n 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.`,\n },\n {\n prefix: \"Bucket width.\",\n mode: \"append\",\n text: \" A time series returns one row per group per bucket, so halving this doubles the rows returned.\",\n },\n {\n prefix: \"GROUP BY columns.\",\n mode: \"append\",\n 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.\",\n },\n ];\n}\n\n/**\n * Returns `doc` with each override applied wherever its prefix matches, and a\n * count per override so a caller can tell whether any stopped matching.\n */\nexport function applyDescriptions(\n doc: SchemaNode,\n overrides: readonly DescriptionOverride[]\n): { document: SchemaNode; applied: Record<string, number> } {\n const applied: Record<string, number> = Object.fromEntries(\n overrides.map((o) => [o.prefix, 0])\n );\n\n const rewrite = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(rewrite);\n if (!value || typeof value !== \"object\") return value;\n\n const node = { ...(value as SchemaNode) };\n const description = node.description;\n if (typeof description === \"string\") {\n for (const override of overrides) {\n if (!description.startsWith(override.prefix)) continue;\n node.description =\n override.mode === \"replace\"\n ? override.text\n : description + override.text;\n applied[override.prefix] = (applied[override.prefix] ?? 0) + 1;\n break;\n }\n }\n\n for (const [key, child] of Object.entries(node)) {\n if (key === \"description\") continue;\n node[key] = rewrite(child);\n }\n return node;\n };\n\n return { document: rewrite(doc) as SchemaNode, applied };\n}\n","import { kopaiQuery } from \"@kopai/core\";\nimport { z } from \"zod\";\n\nimport { dedupe } from \"./dedupe.js\";\nimport { applyDescriptions, descriptionOverrides } from \"./describe.js\";\nimport { LIMITS } from \"./limits.js\";\n\n/**\n * The `query` tool's input: the KopaiQuery body under a single `query`\n * property, because an MCP tool's input schema must have an object root and\n * KopaiQuery is a union.\n *\n * Strict, so the document says `additionalProperties: false` on the root as\n * well as on every node inside it. In `io: \"input\"` mode zod leaves a plain\n * `z.object` open, which advertised a tool that accepted arguments it would\n * then ignore; `runQueryTool` rejects them, and the schema now agrees.\n */\nconst QueryToolInput = z.strictObject({ query: kopaiQuery.KopaiQuery });\n\n/**\n * The advertised input schema for the `query` tool, deduplicated into `$defs`.\n *\n * WHY generated here, at module scope, rather than inside the per-request\n * server factory: the transport builds a fresh server per request, and\n * generating plus deduplicating this document costs ~11 ms — around a hundred\n * times a request's own work. The document depends on nothing request-scoped,\n * so it is built once per process and shared.\n */\nconst OVERRIDES = descriptionOverrides(\n LIMITS.raw.max,\n LIMITS.aggregate.max,\n LIMITS.raw.fallback,\n LIMITS.aggregate.fallback\n);\n\nconst described = applyDescriptions(\n z.toJSONSchema(QueryToolInput, { io: \"input\" }) as Record<string, unknown>,\n OVERRIDES\n);\n\n/** How many nodes each override matched. Asserted in the tests, not at runtime. */\nexport const DESCRIPTION_OVERRIDES_APPLIED = described.applied;\n\nexport const QUERY_TOOL_INPUT_SCHEMA: Record<string, unknown> = dedupe(\n described.document\n);\n\n/**\n * The `metrics_discover` tool takes no arguments, but MCP still requires an\n * object root.\n */\nexport const METRICS_DISCOVER_TOOL_INPUT_SCHEMA: Record<string, unknown> = {\n type: \"object\",\n properties: {},\n};\n","import type { ToolCallOutcome } from \"./types.js\";\n\n/** An error code a tool can return. `ok` is not one of them. */\nexport type ToolErrorCode = Exclude<ToolCallOutcome, \"ok\">;\n\nexport interface ToolIssue {\n path: string;\n message: string;\n}\n\nexport interface ToolErrorPayload {\n error: ToolErrorCode;\n message: string;\n issues?: ToolIssue[];\n remedies?: string[];\n}\n\n/**\n * The shape every tool on the server returns, built-in or host. Deliberately not the MCP SDK's own result type\n * — this stays a plain object so it can be asserted on in tests without a\n * server.\n */\nexport type ToolResult = {\n structuredContent: unknown;\n content: Array<{ type: \"text\"; text: string }>;\n isError?: true;\n};\n\n/**\n * Builds a result carrying `payload` in BOTH channels — as\n * `structuredContent`, and as a single text block holding exactly\n * `JSON.stringify` of the same object.\n *\n * WHY both, when the specification suggests one: the two consumers read\n * different channels and neither reads both. A live page reads\n * `structuredContent` through the artifact runtime's `payload` convenience. A\n * conversational agent reads `content` — Anthropic's own MCP helper returns\n * `result.content.map(...)` and discards `structuredContent` entirely whenever\n * `content` is non-empty, falling back to the structured value only when\n * `content` is empty. So rows in `structuredContent` plus a prose summary in\n * the text block is the one combination that fails: the fallback never fires,\n * and the agent receives the summary and none of the rows, with no error\n * raised anywhere.\n *\n * Sending both costs wire bytes only, never context: a client forwards one\n * channel or the other, so the model ingests the payload once. The text block\n * stays pure JSON so that the \"first text block parsed as JSON\" path a page\n * may fall back to remains valid.\n */\nexport function okResult(payload: unknown): ToolResult {\n return {\n structuredContent: payload,\n content: [{ type: \"text\", text: JSON.stringify(payload) }],\n };\n}\n\n/**\n * Builds a failed result. Same duplication as {@link okResult}, and more\n * load-bearing here: the empty-content fallback to the structured value sits\n * below the `isError` branch in the agent's helper, so it never fires on a\n * failure. A structured-only success degrades; a structured-only error\n * vanishes, leaving the agent an empty error and nothing to repair from.\n *\n * `error` is written first so the serialized JSON opens with the code.\n */\nexport function errorResult(payload: ToolErrorPayload): ToolResult {\n // Rebuilt key by key rather than spread, because the key order is the\n // contract: `error` must serialize first.\n const ordered: ToolErrorPayload = {\n error: payload.error,\n message: payload.message,\n };\n if (payload.issues !== undefined) ordered.issues = payload.issues;\n if (payload.remedies !== undefined) ordered.remedies = payload.remedies;\n\n return {\n structuredContent: ordered,\n content: [{ type: \"text\", text: JSON.stringify(ordered) }],\n isError: true,\n };\n}\n\n/**\n * Re-points issue paths from `@kopai/core`'s query-relative form onto the\n * tool's input, whose single property is `query`. The empty root path becomes\n * `query` rather than `query.`.\n */\nexport function prefixIssuePaths(issues: ToolIssue[]): ToolIssue[] {\n return issues.map(({ path, message }) => ({\n path: path === \"\" ? \"query\" : `query.${path}`,\n message,\n }));\n}\n","import { kopaiQuery, kopaiQueryCompiler, type datasource } from \"@kopai/core\";\n\nimport {\n DISCOVERY_RESOURCE_LIMIT_REMEDIES,\n DISCOVERY_SIZE_REMEDIES,\n isResourceLimitError,\n LIMITS,\n MAX_RESULT_CHARACTERS,\n overflowRemedies,\n RESOURCE_LIMIT_REMEDIES,\n SIZE_REMEDIES,\n} from \"./limits.js\";\nimport {\n errorResult,\n okResult,\n prefixIssuePaths,\n type ToolResult,\n} from \"./results.js\";\nimport type { ToolCallOutcome, ToolLogger } from \"./types.js\";\n\nexport interface ToolContext {\n readTelemetryDatasource: datasource.ReadTelemetryDatasource;\n /** Whatever the host application attached to the request; passed through. */\n requestContext?: unknown;\n /** Where an upstream failure is written. See {@link fromThrown}. */\n logger?: ToolLogger;\n}\n\n/**\n * A completed tool run. The outcome is returned rather than inferred from the\n * result so that the observer and any counter read the same value the caller\n * sees, with no second classification step to drift.\n */\nexport interface ToolRun {\n result: ToolResult;\n outcome: ToolCallOutcome;\n rowCount?: number;\n}\n\nfunction invalidInput(\n message: string,\n issues?: { path: string; message: string }[]\n): ToolRun {\n return {\n result: errorResult({ error: \"invalid_input\", message, issues }),\n outcome: \"invalid_input\",\n };\n}\n\nfunction tooLarge(message: string, remedies: readonly string[]): ToolRun {\n return {\n result: errorResult({\n error: \"result_too_large\",\n message,\n remedies: [...remedies],\n }),\n outcome: \"result_too_large\",\n };\n}\n\n/**\n * A query the datasource stopped at a resource limit. Exported for the host\n * tools' throw handler in `register.ts`.\n */\nexport function tooExpensive(\n message: string,\n remedies: readonly string[]\n): ToolRun {\n return {\n result: errorResult({\n error: \"query_too_expensive\",\n message,\n remedies: [...remedies],\n }),\n outcome: \"query_too_expensive\",\n };\n}\n\n/**\n * Maps a thrown error onto an outcome, mirroring the REST error handler:\n * a recognised validation error surfaces its own message, a resource limit\n * surfaces what to ask for instead, and anything unrecognised surfaces a\n * generic string with the detail written to the log.\n *\n * WHY a resource limit gets its own outcome: it is the failure a caller can\n * get past, by asking for less, and a generic \"could not be completed\" gave\n * it nothing to change. Directory review fails a connector whose errors carry\n * no detail.\n *\n * WHY the log matters as much as the result: \"The query could not be\n * completed.\" is the whole of what a model can act on, and it is also the\n * whole of what anyone got. A datasource that was refusing connections\n * produced that one string for the caller and not a line for whoever runs the\n * server — in a product whose purpose is making failures visible. The REST\n * side has always logged this class of error (`error-handler.ts`); this is the\n * same thing at the other entry point.\n *\n * A validation error is not logged: it is the caller's mistake, it is reported\n * back in full, and logging every malformed query would bury the outages. A\n * resource limit is logged: it is the caller's query, but which queries the\n * datasource cannot afford is for whoever runs it to know.\n *\n * `limitRemedies` is for `metrics_discover`, which takes no arguments and so\n * cannot narrow a window.\n */\nexport function fromThrown(\n error: unknown,\n logger?: ToolLogger,\n limitRemedies: readonly string[] = RESOURCE_LIMIT_REMEDIES\n): ToolRun {\n if (error instanceof kopaiQueryCompiler.KopaiQueryValidationError) {\n return invalidInput(error.message);\n }\n logger?.error(error, \"MCP tool call failed\");\n if (isResourceLimitError(error)) {\n return tooExpensive(\n \"The query was stopped at this deployment's limit on query time, memory or rows read.\",\n limitRemedies\n );\n }\n return {\n result: errorResult({\n error: \"upstream_error\",\n message: \"The query could not be completed.\",\n }),\n outcome: \"upstream_error\",\n };\n}\n\n/**\n * The branch a query was judged against, when the pair selects one.\n *\n * WHY the message names it: the issues name fields, and the six shapes share\n * field names — `measures` is on three of them, `filters` on all six. A caller\n * told only `query.measures.0.column` does not know which shape its query was\n * read as, and the `signal`/`mode` pair that decides that is the one thing it\n * can get wrong without any issue pointing at it. Where the pair itself is\n * wrong there is no branch to name, and the issues on `signal` and `mode` say\n * so instead.\n */\nfunction branchOf(query: unknown): string | undefined {\n const { signal, mode } = (query ?? {}) as {\n signal?: unknown;\n mode?: unknown;\n };\n return kopaiQuery.isSignal(signal) && kopaiQuery.isQueryMode(mode)\n ? `${signal}/${mode}`\n : undefined;\n}\n\n/** Rows in a payload, for the observer. Aggregate and raw both key on `data`. */\nfunction rowsOf(payload: unknown): number | undefined {\n const data = (payload as { data?: unknown })?.data;\n return Array.isArray(data) ? data.length : undefined;\n}\n\nexport async function runQueryTool(\n input: unknown,\n ctx: ToolContext\n): Promise<ToolRun> {\n if (typeof input !== \"object\" || input === null || Array.isArray(input)) {\n return invalidInput(\"Expected an object with a `query` property.\", [\n { path: \"query\", message: \"Expected a query object.\" },\n ]);\n }\n\n // `query` is the only argument, and the handler reads nothing else, so an\n // extra key would be dropped without a word. The slip that produces one is\n // writing a query field at the top level — `limit` beside `query` rather\n // than inside it — and dropping that ran a different query than the caller\n // described and then answered `ok`. The pass-through validator means no\n // layer above this one will catch it either.\n const extraArgs = Object.keys(input as Record<string, unknown>).filter(\n (key) => key !== \"query\"\n );\n if (extraArgs.length > 0) {\n return invalidInput(\n `${extraArgs.map((key) => `\\`${key}\\``).join(\", \")} ${\n extraArgs.length > 1 ? \"are not arguments\" : \"is not an argument\"\n } of this tool. \\`query\\` is the only one.`,\n extraArgs.map((key) => ({\n path: key,\n message: `Unknown argument. If it is a query field, it belongs at \\`query.${key}\\`.`,\n }))\n );\n }\n\n const query_ = (input as { query?: unknown }).query;\n const parsed = kopaiQueryCompiler.parseKopaiQuery(query_);\n if (!parsed.ok) {\n const branch = branchOf(query_);\n return invalidInput(\n branch ? `The ${branch} query is not valid.` : \"The query is not valid.\",\n prefixIssuePaths(parsed.issues)\n );\n }\n\n const query = parsed.data;\n const { fallback, max } = LIMITS[query.mode];\n\n // Rejected, never clamped: a caller that asked for 500 raw rows and\n // silently received 200 would read the result as complete.\n if (query.limit !== undefined && query.limit > max) {\n return invalidInput(\n `\\`limit\\` must be at most ${max} in ${query.mode} mode.`,\n [\n {\n path: \"query.limit\",\n message: `Expected at most ${max}, received ${query.limit}.`,\n },\n ]\n );\n }\n\n const limit = query.limit ?? fallback;\n\n // Aggregate runs one row over the cap so that an overflow is detectable.\n // Raw does not need this: the backend already fetches limit + 1 and reports\n // the remainder as `nextCursor`, so a truncated raw result is both visible\n // and resumable.\n const isAggregate = query.mode === \"aggregate\";\n const probeLimit = isAggregate ? limit + 1 : limit;\n\n let payload: unknown;\n try {\n payload = await ctx.readTelemetryDatasource.query({\n ...query,\n limit: probeLimit,\n requestContext: ctx.requestContext,\n } as kopaiQuery.KopaiQuery & { requestContext?: unknown });\n } catch (error) {\n return fromThrown(error, ctx.logger);\n }\n\n if (isAggregate) {\n const rows = (payload as { data?: unknown[] }).data ?? [];\n if (rows.length > limit) {\n // An aggregate that overruns its cap is refused outright, with no rows,\n // whether or not it carries an `orderBy`.\n //\n // WHY refuse rather than truncate, even when an ordering makes the\n // truncation well defined: a live page cannot act on a remedy. Its query\n // was fixed when the page was authored and its viewer did not write it,\n // so a partial result would simply be drawn as though it were the whole\n // set — the top N groups rendered as if they were all the groups.\n // ADR-059 requires a page to show an explicit \"outgrew its query\" state\n // and never draw a partial chart, and refusing is what makes that hold\n // without every page having to check a flag it may not know about.\n //\n // Without an ordering it would be worse still: the aggregate compiler\n // emits no ORDER BY when `orderBy` is absent, so a LIMIT drops an\n // arbitrary subset — and for a time series, whose rows are groups times\n // buckets, that is a scatter of (group, bucket) pairs that reads as real\n // data. `bucket_start` cannot rescue it either: it is a computed SELECT\n // alias, neither a dimension nor a measure, so a time series cannot be\n // sorted by time at all.\n return tooLarge(\n `The query returned more than the ${limit} rows it asked for.`,\n overflowRemedies(query, limit, max)\n );\n }\n }\n\n // Measured after serialization, on one copy: the result carries the same\n // JSON twice, but a client forwards one channel or the other.\n const serialized = JSON.stringify(payload);\n if (serialized.length > MAX_RESULT_CHARACTERS) {\n return tooLarge(\n `The result serialized to ${serialized.length.toLocaleString(\"en-US\")} characters, above the ${MAX_RESULT_CHARACTERS.toLocaleString(\"en-US\")} the host will accept.`,\n SIZE_REMEDIES\n );\n }\n\n return {\n result: okResult(payload),\n outcome: \"ok\",\n rowCount: rowsOf(payload),\n };\n}\n\n/** A metric with its attribute values dropped, keys kept. */\ninterface MetricWithAttributeKeys {\n name: string;\n type: string;\n unit?: string;\n description?: string;\n attributeKeys: string[];\n resourceAttributeKeys: string[];\n}\n\n/** A metric stripped to what cannot be guessed or derived. */\ntype MetricIdentityOnly = Omit<\n MetricWithAttributeKeys,\n \"attributeKeys\" | \"resourceAttributeKeys\"\n>;\n\nfunction identityOf(metric: datasource.DiscoveredMetric): MetricIdentityOnly {\n const { name, type, unit, description } = metric;\n return {\n name,\n type,\n ...(unit === undefined ? {} : { unit }),\n ...(description === undefined ? {} : { description }),\n };\n}\n\n/**\n * The discovery listing, given up a piece at a time until it fits.\n *\n * WHY degrade rather than refuse: `metrics_discover` takes no arguments, so a\n * caller handed `result_too_large` has nothing to change and no way to learn a\n * metric name — which the `query` tool's own description tells them to do\n * first. The values seen on each attribute are the bulk of the document and\n * the metric names are the part that cannot be guessed, so they are given up in\n * that order, and the response says which step was taken rather than leaving a\n * thinner answer to pass as the whole one.\n */\nfunction degradations(\n full: datasource.MetricsDiscoveryResult\n): { payload: Record<string, unknown>; omitted?: string }[] {\n return [\n { payload: { ...full } },\n {\n omitted: \"attributeValues\",\n payload: {\n metrics: full.metrics.map((metric): MetricWithAttributeKeys => ({\n ...identityOf(metric),\n attributeKeys: Object.keys(metric.attributes?.values ?? {}),\n resourceAttributeKeys: Object.keys(\n metric.resourceAttributes?.values ?? {}\n ),\n })),\n omitted: \"attributeValues\",\n 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.\",\n },\n },\n {\n omitted: \"attributes\",\n payload: {\n metrics: full.metrics.map(identityOf),\n omitted: \"attributes\",\n 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.\",\n },\n },\n ];\n}\n\nexport async function runMetricsDiscoverTool(\n ctx: ToolContext\n): Promise<ToolRun> {\n let full: datasource.MetricsDiscoveryResult;\n try {\n full = await ctx.readTelemetryDatasource.discoverMetrics({\n requestContext: ctx.requestContext,\n });\n } catch (error) {\n return fromThrown(error, ctx.logger, DISCOVERY_RESOURCE_LIMIT_REMEDIES);\n }\n\n // Serialization is outside the try: a payload this cannot stringify is not an\n // upstream failure, and reporting it as one blamed the datasource for a bug\n // here.\n let serialized = \"\";\n for (const stage of degradations(full)) {\n serialized = JSON.stringify(stage.payload);\n if (serialized.length <= MAX_RESULT_CHARACTERS) {\n return {\n result: okResult(stage.payload),\n outcome: \"ok\",\n rowCount: full.metrics.length,\n };\n }\n }\n\n return tooLarge(\n `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.`,\n DISCOVERY_SIZE_REMEDIES\n );\n}\n","import type { datasource } from \"@kopai/core\";\nimport type { McpServer } from \"@modelcontextprotocol/server\";\nimport type { FastifyRequest } from \"fastify\";\n\n/**\n * How a tool call ended. These labels are the server's whole error\n * vocabulary: they are the `error` code on a failed result, the `outcome` on\n * the observer event, and the values a counter is grouped by.\n *\n * `not_found` and `forbidden` are produced only by host tools (see\n * {@link HostTools}); the built-in tools never return them.\n *\n * `query_too_expensive` is a query the datasource stopped at a time, memory,\n * row or byte limit, recognised from the thrown error; see\n * `isResourceLimitError`.\n */\nexport const TOOL_CALL_OUTCOMES = [\n \"ok\",\n \"invalid_input\",\n \"result_too_large\",\n \"query_too_expensive\",\n \"upstream_error\",\n \"not_found\",\n \"forbidden\",\n] as const;\n\nexport type ToolCallOutcome = (typeof TOOL_CALL_OUTCOMES)[number];\n\n/**\n * The one method this package calls on a logger.\n *\n * Structural rather than Fastify's own type: the tool layer knows nothing\n * about HTTP, and a host that mounts this plugin somewhere else should not\n * have to produce a `FastifyBaseLogger` to get its failures written down.\n * `routes.ts` passes `request.log`, which satisfies it.\n */\nexport interface ToolLogger {\n error(payload: unknown, message?: string): void;\n}\n\n/**\n * One completed tool call, handed to `onToolCall`.\n *\n * WHY the raw request is included: this plugin is open source and mounts in\n * two applications that know different things about a caller. It deliberately\n * does not learn about tenants or credentials; the host application reads\n * whatever it attached to the request and does its own counting and logging.\n */\nexport interface ToolCallEvent {\n tool: string;\n outcome: ToolCallOutcome;\n durationMs: number;\n /** Rows returned, when the tool returned rows. */\n rowCount?: number;\n request: FastifyRequest;\n}\n\n/**\n * Tools the host application adds to the same server as `query` and\n * `metrics_discover`, for data only the host has.\n *\n * Host tools follow the built-ins' conventions:\n *\n * - Results are built with `okResult` and `errorResult`, so the\n * error contract holds for every tool on the server.\n * - The package observes them as it observes the built-ins: a throw becomes\n * a logged `upstream_error` (\"The tool call could not be completed.\"), or\n * `query_too_expensive` when it is a query stopped at a resource limit, the\n * outcome is read from the result's `error` code, and `onToolCall` fires\n * once per call (without `rowCount`).\n * A host tool never calls `onToolCall` itself. An error result without a\n * known code is counted as `upstream_error` and logged.\n * - `inputSchema` is built with `fromJsonSchema(schema, passThroughValidator)`\n * and the handler validates, returning `invalid_input` with `issues`. The\n * SDK's own validator rejects before dispatch, so the rejection would go\n * uncounted and lose its `issues`; see `validator.ts`.\n * - No `outputSchema`; registering one, or adding one through `update`,\n * throws. The SDK checks it after the\n * callback returns, so a mismatch would be counted `ok` while the caller\n * got the SDK's bare error.\n * - `McpServer` and `fromJsonSchema` are imported from `@kopai/mcp`, not from\n * `@modelcontextprotocol/server`. They are the SDK's own, re-exported, at\n * the version this package pins (2.3.1). `McpServer` has private fields, so\n * a second copy of the SDK is a different, incompatible type.\n *\n * `register` is for tools. Prompts and resources registered through it are\n * neither checked nor observed.\n */\nexport interface HostTools {\n /**\n * Every name `register` may register. Checked once, at plugin registration:\n * a name that is not an MCP tool name (`[A-Za-z0-9._-]`, 1 to 128\n * characters), a duplicate, or a built-in name is refused with a\n * `TypeError`. An empty list is allowed.\n */\n names: string[];\n /**\n * Runs on each request's server, after the built-in tools are registered.\n * Registering, or renaming a tool to, a name not in `names` throws, and so\n * does renaming a tool onto a name already registered.\n *\n * Synchronous, because the SDK's server factory is; a returned promise\n * fails the request. Do the I/O that decides\n * which tools this caller gets in an async `preHandler`, attach the result\n * to the request, and read it here. A tool not registered for a request is\n * absent from that caller's `tools/list`.\n *\n * A throw fails the request; the server does not fall back to the built-in\n * tools alone.\n */\n register: (server: McpServer, request: FastifyRequest) => void;\n}\n\nexport interface McpRoutesOptions {\n readTelemetryDatasource: datasource.ReadTelemetryDatasource;\n /**\n * Hostnames the MCP endpoint answers for, compared port-agnostically. A\n * request whose `Host` is not on this list is refused, which is what stops\n * a DNS-rebinding page from reaching a local server.\n */\n allowedHosts: string[];\n /**\n * Hostnames that may appear in a browser's `Origin` header. Omit to mount no\n * origin validation at all, which is the default.\n *\n * An empty list is not the same as omitting it: it mounts a validator that\n * refuses every browser origin, which is a coherent thing to ask for and a\n * surprising thing to arrive at by accident. Non-browser clients send no\n * `Origin` and pass either way, so an accidental `[]` looks like \"works for\n * my MCP client, broken for every page\". Omit the option when the intent is\n * no validation. Any other wrong shape — `null` from a config that had no\n * list, a bare string — is refused at registration rather than mounted.\n *\n * WHY hostnames, and why a separate list from {@link allowedHosts}: the two\n * answer different questions. `allowedHosts` is the hostname this server is\n * reached at; this is the hostname of a page allowed to reach it. On a local\n * app they coincide, both being loopback. On a deployed one they do not —\n * the API and the dashboard live at different names — so conflating them\n * either refuses the dashboard or forces the host list wide enough to weaken\n * the rebinding check.\n *\n * WHY hostnames and not origins: the underlying validator compares\n * hostnames, port-agnostically. Passing a full origin such as\n * `\"https://app.example.com\"` refuses that very origin, and passing `\"*\"`\n * refuses everything — both silently, since either is a valid `string[]`.\n * Anything shaped like a CORS `origin` list belongs in a CORS plugin, not\n * here.\n *\n * A request with no `Origin` header passes by design, so non-browser clients\n * are unaffected; only browsers are constrained.\n */\n allowedOriginHostnames?: string[];\n /**\n * Where an upstream failure is written. Defaults to the Fastify instance's\n * own request logger; pass one only to send these somewhere else.\n */\n logger?: ToolLogger;\n /** Called once per completed tool call. Errors thrown here are swallowed. */\n onToolCall?: (event: ToolCallEvent) => void;\n /** Tools the host adds to the server. See {@link HostTools}. */\n hostTools?: HostTools;\n}\n\n// Mirrors the identical augmentation in `@kopai/api`. Both packages mount into\n// the same Fastify instance and neither depends on the other, so each declares\n// what it reads. The declarations are structurally identical, which is what\n// keeps them compatible when both are present.\ndeclare module \"fastify\" {\n interface FastifyRequest {\n requestContext?: unknown;\n }\n}\n","import type {\n JsonSchemaValidator,\n jsonSchemaValidator,\n} from \"@modelcontextprotocol/server\";\n\n/**\n * A validator provider that accepts everything, so that the tool handler is\n * what validates.\n *\n * Three reasons, and each would be sufficient on its own:\n *\n * 1. Correctness. The `query` schema is a union of six branches. The SDK's\n * default validator rejects before dispatch and answers with one text line\n * listing every branch's failures, which tells a model nothing about which\n * field it got wrong. The handler instead selects the one branch the\n * caller's `signal`/`mode` names and reports issues against it.\n * 2. Cost. The default provider is AJV-backed and compiles the schema it is\n * given. The transport builds a fresh server per request, so that\n * compilation would happen on every call.\n * 3. Observability. A rejection made before dispatch never reaches the\n * handler, so it never reaches `onToolCall` — the counter would undercount\n * exactly the failures most worth seeing.\n *\n * NOTE the shape: `fromJsonSchema`'s second argument is a provider object with\n * a `getValidator` method, not a validator function. Passing a bare function\n * throws `TypeError: validator.getValidator is not a function`, which the SDK\n * swallows into a 500 on `initialize` — presenting as \"the whole server is\n * broken\" rather than as a bad argument.\n */\nexport const passThroughValidator: jsonSchemaValidator = {\n getValidator<T>(): JsonSchemaValidator<T> {\n return (input: unknown) => ({\n valid: true,\n data: input as T,\n errorMessage: undefined,\n });\n },\n};\n","import { fromJsonSchema, type McpServer } from \"@modelcontextprotocol/server\";\n\nimport {\n isResourceLimitError,\n LIMITS,\n MAX_RESULT_CHARACTERS,\n RESOURCE_LIMIT_REMEDIES,\n} from \"./limits.js\";\nimport {\n METRICS_DISCOVER_TOOL_INPUT_SCHEMA,\n QUERY_TOOL_INPUT_SCHEMA,\n} from \"./schema.js\";\nimport { errorResult, type ToolResult } from \"./results.js\";\nimport {\n fromThrown,\n runMetricsDiscoverTool,\n runQueryTool,\n tooExpensive,\n type ToolContext,\n} from \"./tools.js\";\nimport {\n TOOL_CALL_OUTCOMES,\n type ToolCallOutcome,\n type ToolLogger,\n} from \"./types.js\";\nimport { passThroughValidator } from \"./validator.js\";\n\n/**\n * Both tools read and never write, always return the same answer for the same\n * arguments and window, and reach nothing outside this deployment.\n *\n * Each tool repeats its `title` inside `annotations`: the 2025-03-26 spec has\n * no top-level tool `title`, so clients and checks built on it (including the\n * Claude connector directory check) read it only from there.\n *\n * `destructiveHint` is stated even though the spec ignores it when\n * `readOnlyHint` is true: OpenAI's plugin review requires `readOnlyHint`,\n * `destructiveHint` and `openWorldHint` as explicit booleans on every tool.\n */\nconst READ_ONLY = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n} as const;\n\n/**\n * Descriptions are deliberately flat: what the tool does, the shape of its\n * input, and the limits. They carry no instructions aimed at the model —\n * these strings are read by Directory review, and a tool description is not a\n * place to steer behaviour.\n */\nconst QUERY_DESCRIPTION = [\n \"Query this workspace's OpenTelemetry traces, logs and metrics.\",\n \"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.\",\n `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.`,\n \"Aggregate is the compact shape; raw returns whole records and is for inspecting individual spans, logs or data points.\",\n // What decides whether a query fits. Stated here because the cost is a\n // product of two fields, and a field-level description can only speak for\n // one of them.\n \"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.\",\n \"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`.\",\n \"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.\",\n].join(\" \");\n\nconst METRICS_DISCOVER_DESCRIPTION = [\n \"List the metrics present in this workspace, with each metric's type, unit, description and the attribute keys and values seen on it.\",\n \"Takes no arguments.\",\n // Stated because the tool promises attribute values above, and a caller that\n // gets a response without them is owed the reason in the description as well\n // as in the response.\n `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.`,\n].join(\" \");\n\n/** The tools this package registers itself. A host tool may not reuse them. */\nexport const BUILT_IN_TOOL_NAMES = [\"query\", \"metrics_discover\"] as const;\n\nexport interface RegisterToolsOptions extends ToolContext {\n /**\n * Called once per completed tool call, after the result is built and before\n * it is returned.\n */\n onToolCall?: (event: {\n tool: string;\n outcome: ToolCallOutcome;\n durationMs: number;\n rowCount?: number;\n }) => void;\n}\n\n/** A completed run of any tool, built-in or host. */\ninterface Run<R> {\n result: R;\n outcome: ToolCallOutcome;\n rowCount?: number;\n}\n\n/**\n * Returns the function that runs one tool call and reports it, whatever\n * happens. Shared by the built-in and the host tools, so every tool on the\n * server reaches `onToolCall` through this one place.\n *\n * WHY the catch: a throw out of a tool used to skip `observe` altogether, so\n * the host's counter lost exactly the calls most worth seeing — and the SDK\n * turned it into a bare message with no `structuredContent`, which is the\n * one error shape a page cannot read. Nothing in the tools is expected to\n * throw; that is the reason to handle it here rather than to assume it, and\n * converting it gives an unexpected failure the same contract as an expected\n * one: a structured payload, a logged cause, and one observer event.\n */\nfunction observedCall(opts: RegisterToolsOptions) {\n const observe = (\n tool: string,\n startedAt: number,\n outcome: ToolCallOutcome,\n rowCount?: number\n ): void => {\n if (!opts.onToolCall) return;\n // Guarded: an observer that throws is the host application's problem and\n // must not turn a successful query into a failed tool call.\n try {\n opts.onToolCall({\n tool,\n outcome,\n durationMs: Date.now() - startedAt,\n ...(rowCount !== undefined ? { rowCount } : {}),\n });\n } catch {\n // deliberately swallowed\n }\n };\n\n return async <R>(\n tool: string,\n execute: () => Promise<Run<R>>\n ): Promise<R | ToolResult> => {\n const startedAt = Date.now();\n let run: Run<R | ToolResult>;\n try {\n run = await execute();\n } catch (error) {\n run = fromThrown(error, opts.logger);\n }\n observe(tool, startedAt, run.outcome, run.rowCount);\n return run.result;\n };\n}\n\n/**\n * Registers the `query` and `metrics_discover` tools on `server`.\n *\n * Every call reports to `opts.onToolCall` exactly once, including a call whose\n * tool throws, which is returned as a structured error rather than rethrown.\n */\nexport function registerTools(\n server: McpServer,\n opts: RegisterToolsOptions\n): void {\n const call = observedCall(opts);\n\n server.registerTool(\n \"query\",\n {\n title: \"Query telemetry\",\n description: QUERY_DESCRIPTION,\n inputSchema: fromJsonSchema(\n QUERY_TOOL_INPUT_SCHEMA,\n passThroughValidator\n ),\n annotations: { ...READ_ONLY, title: \"Query telemetry\" },\n },\n async (input: unknown) =>\n call<ToolResult>(\"query\", () => runQueryTool(input, opts))\n );\n\n server.registerTool(\n \"metrics_discover\",\n {\n title: \"Discover metrics\",\n description: METRICS_DISCOVER_DESCRIPTION,\n inputSchema: fromJsonSchema(\n METRICS_DISCOVER_TOOL_INPUT_SCHEMA,\n passThroughValidator\n ),\n annotations: { ...READ_ONLY, title: \"Discover metrics\" },\n },\n async () =>\n call<ToolResult>(\"metrics_discover\", () => runMetricsDiscoverTool(opts))\n );\n}\n\nconst ERROR_CODES: ReadonlySet<string> = new Set(\n TOOL_CALL_OUTCOMES.filter((outcome) => outcome !== \"ok\")\n);\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\n/**\n * Reads a host tool's outcome from the result it returned.\n *\n * WHY reading is safe here, when `ToolRun` returns the outcome rather than\n * inferring it: `errorResult` is the one builder of an error result, and it\n * always writes the code. A hand-built error result has no code to read; it\n * is counted as `upstream_error`, the same label an unexpected throw gets, and\n * logged so the tool can be fixed. It is not thrown: the caller already has\n * an answer, and the tool's own text is more use to it than ours.\n */\nfunction hostOutcome(\n tool: string,\n result: unknown,\n logger: ToolLogger | undefined\n): ToolCallOutcome {\n if (!isRecord(result) || result.isError !== true) return \"ok\";\n const code = isRecord(result.structuredContent)\n ? result.structuredContent.error\n : undefined;\n if (typeof code === \"string\" && ERROR_CODES.has(code)) {\n return code as ToolCallOutcome;\n }\n logger?.error(\n { tool },\n \"MCP host tool returned an error result without a known error code\"\n );\n return \"upstream_error\";\n}\n\n/**\n * A host tool's throw, converted as `fromThrown` converts a built-in's, with\n * two differences: the generic message names no query, since a host tool need\n * not run one, and the log line names the tool.\n *\n * A resource limit is classified here too: a host tool that reads telemetry\n * (a backtest, say) lets its query's throw through, and would otherwise\n * report a limit the caller can get past as a generic failure.\n */\nfunction thrownByHostTool(\n tool: string,\n error: unknown,\n logger: ToolLogger | undefined\n): Run<ToolResult> {\n logger?.error(error, `MCP host tool \"${tool}\" failed`);\n if (isResourceLimitError(error)) {\n return tooExpensive(\n \"The query behind this tool call was stopped at this deployment's limit on query time, memory or rows read.\",\n RESOURCE_LIMIT_REMEDIES\n );\n }\n return {\n result: errorResult({\n error: \"upstream_error\",\n message: \"The tool call could not be completed.\",\n }),\n outcome: \"upstream_error\",\n };\n}\n\ntype HostCallback = (...args: unknown[]) => unknown;\n\nexport interface RegisterHostToolsOptions extends RegisterToolsOptions {\n /** Every name `register` may use; checked at plugin registration. */\n names: ReadonlySet<string>;\n register: (server: McpServer) => void;\n}\n\n/**\n * Runs the host's `register` on `server`, with `registerTool` guarded and\n * observed.\n *\n * The guard is installed on this one per-request instance, through the SDK's\n * public API only. It refuses a name not in `names`, so the check made at\n * boot cannot be bypassed through `registerTool` or `update` — a host that\n * reaches past them, by writing `handle.executor` or calling the prototype's\n * `registerTool`, is not guarded, and is not meant to be. It wraps the\n * returned handle's `update` as well: `update({ name })` renames a registered tool, and `update({ callback\n * })` swaps its callback, either of which would otherwise slip past the guard.\n * `remove()` is `update({ name: null })` in the SDK and passes.\n *\n * A refusal throws, and so does anything else `register` throws. Both fail the\n * request; see {@link HostTools}.\n */\nexport function registerHostTools(\n server: McpServer,\n opts: RegisterHostToolsOptions\n): void {\n const call = observedCall(opts);\n const assertDeclared = (name: string): void => {\n if (opts.names.has(name)) return;\n const declared = [...opts.names].map((n) => `\"${n}\"`).join(\", \");\n throw new TypeError(\n `Host tool \"${name}\" is not in hostTools.names (${declared || \"none declared\"}). Declare every name register may use.`\n );\n };\n\n const registerTool = server.registerTool.bind(server) as (\n name: string,\n config: unknown,\n callback: HostCallback\n ) => ReturnType<McpServer[\"registerTool\"]>;\n\n // Every observed wrapper, mapped to the host callback it wraps; read by the\n // `handler` accessor below.\n const wrapped = new WeakMap<HostCallback, HostCallback>();\n\n // Names in use on this server. The SDK refuses to register a name twice,\n // but a rename onto a name in use silently replaces that tool — a tool\n // missing because of a bug, which is what failing the request is for.\n const inUse = new Set<string>();\n\n const guarded = (name: string, config: unknown, callback: HostCallback) => {\n assertDeclared(name);\n // WHY: the SDK checks an output schema after the callback returns, so a\n // mismatch is counted `ok` while the caller receives the SDK's own bare\n // error, which breaks the error contract for that tool.\n const refuseOutputSchema = (value: unknown, tool: string): void => {\n if (value === undefined) return;\n throw new TypeError(\n `Host tool \"${tool}\" declares an outputSchema; host tools may not.`\n );\n };\n refuseOutputSchema(\n isRecord(config) ? config.outputSchema : undefined,\n name\n );\n let current = name;\n const observed = (inner: HostCallback): HostCallback => {\n const outer: HostCallback = (...args) =>\n call(current, async () => {\n let result: unknown;\n try {\n result = await inner(...args);\n } catch (error) {\n return thrownByHostTool(current, error, opts.logger);\n }\n return {\n result,\n outcome: hostOutcome(current, result, opts.logger),\n };\n });\n wrapped.set(outer, inner);\n return outer;\n };\n\n const handle = registerTool(name, config, observed(callback));\n inUse.add(name);\n\n // WHY an accessor: the SDK keeps the callback it was given on the public\n // `handler` field, which here is the wrapper. A host decorating its tool\n // with `update({ callback: withAudit(handle.handler) })` would wrap the\n // wrapper, and every call would be counted twice. The host reads back its\n // own callback instead; the SDK's write in `update` is mapped the same\n // way. The SDK calls through its own closure, never through this field.\n let raw: unknown = callback;\n Object.defineProperty(handle, \"handler\", {\n get: () => raw,\n set: (value: HostCallback) => {\n raw = wrapped.get(value) ?? value;\n },\n enumerable: true,\n configurable: true,\n });\n const update = handle.update;\n handle.update = (updates) => {\n refuseOutputSchema(updates.outputSchema, current);\n const renamed =\n updates.name !== undefined && updates.name !== current\n ? updates.name\n : undefined;\n if (typeof renamed === \"string\") {\n assertDeclared(renamed);\n if (inUse.has(renamed)) {\n throw new TypeError(\n `Host tool \"${current}\" cannot be renamed to \"${renamed}\", which is already registered.`\n );\n }\n }\n update(\n updates.callback === undefined\n ? updates\n : {\n ...updates,\n callback: observed(\n updates.callback as HostCallback\n ) as typeof updates.callback,\n }\n );\n if (renamed !== undefined) {\n inUse.delete(current);\n // `null` is the SDK's `remove()`.\n if (renamed !== null) {\n inUse.add(renamed);\n current = renamed;\n }\n }\n };\n return handle;\n };\n server.registerTool = guarded as McpServer[\"registerTool\"];\n\n // Typed `void`, but an `async` function satisfies that type. Its promise\n // would be dropped: whatever it registers after an `await` is never\n // listed, and a rejection goes unhandled.\n const returned: unknown = opts.register(server);\n if (returned instanceof Promise) {\n returned.catch(() => {});\n throw new TypeError(\n \"hostTools.register returned a promise; it must be synchronous. Do the I/O in a preHandler and read its result from the request.\"\n );\n }\n}\n","import {\n hostHeaderValidation,\n originValidation,\n} from \"@modelcontextprotocol/fastify\";\nimport { toNodeHandler } from \"@modelcontextprotocol/node\";\nimport { createMcpHandler, McpServer } from \"@modelcontextprotocol/server\";\nimport type { FastifyPluginAsync, FastifyReply, FastifyRequest } from \"fastify\";\n\nimport {\n BUILT_IN_TOOL_NAMES,\n registerHostTools,\n registerTools,\n type RegisterToolsOptions,\n} from \"./register.js\";\nimport type { HostTools, McpRoutesOptions } from \"./types.js\";\n\nconst SERVER_NAME = \"kopai\";\nconst SERVER_VERSION = \"0.0.0\";\n\n// The MCP tool-name rule. The SDK checks the same pattern but only warns,\n// once per server, which on a per-request server is once per request.\nconst TOOL_NAME = /^[A-Za-z0-9._-]{1,128}$/;\n\n/**\n * Checks `hostTools` once, at registration, and returns its names as a set.\n *\n * Refused rather than absorbed, for the reason `allowedOriginHostnames` is: a\n * wrong shape would otherwise fail on every request, and a name colliding\n * with a built-in would fail only when a caller who may use it arrives.\n */\nfunction checkedHostToolNames(hostTools: HostTools): ReadonlySet<string> {\n if (\n typeof hostTools !== \"object\" ||\n hostTools === null ||\n typeof hostTools.register !== \"function\" ||\n !Array.isArray(hostTools.names) ||\n hostTools.names.some((name) => typeof name !== \"string\")\n ) {\n throw new TypeError(\n 'hostTools must be { names: string[]; register: (server, request) => void }, e.g. { names: [\"alert_get\"], register }. Omit it to add no tools.'\n );\n }\n const names = new Set<string>();\n const builtIns: readonly string[] = BUILT_IN_TOOL_NAMES;\n for (const name of hostTools.names) {\n if (!TOOL_NAME.test(name)) {\n throw new TypeError(\n `hostTools.names: \"${name}\" is not an MCP tool name (1 to 128 of A-Z, a-z, 0-9, \".\", \"_\", \"-\").`\n );\n }\n if (builtIns.includes(name)) {\n throw new TypeError(\n `hostTools.names: \"${name}\" is the name of a built-in tool.`\n );\n }\n if (names.has(name)) {\n throw new TypeError(`hostTools.names: \"${name}\" appears more than once.`);\n }\n names.add(name);\n }\n return names;\n}\n\n/**\n * Mounts the MCP endpoint at `/mcp`, relative to wherever this plugin is\n * registered.\n *\n * The server is stateless: no session id, no server push, and a fresh\n * `McpServer` per request.\n */\nexport const mcpRoutes: FastifyPluginAsync<McpRoutesOptions> =\n async function mcpRoutes(fastify, opts) {\n // Port-agnostic allow-list on the Host header. This is what stops a page\n // on another origin from resolving a name it controls to 127.0.0.1 and\n // reaching a local server through the browser — the request arrives with\n // the attacker's hostname in `Host`, and that is what is checked.\n fastify.addHook(\"onRequest\", hostHeaderValidation(opts.allowedHosts));\n\n // Origin validation is opt-in, because the two mounts have different\n // threat models. An unauthenticated local app has nothing but these\n // headers between a web page and the data, and there the host and origin\n // lists genuinely coincide — both are loopback. A deployed, authenticated\n // mount has the credential as its boundary and usually already runs a CORS\n // policy; adding a second, independently configured origin list there buys\n // little and strands a future browser client behind a validator nobody\n // remembers configuring.\n //\n // Host validation alone does not close this: a page that simply fetches\n // http://127.0.0.1:<port>/mcp sends a genuinely loopback `Host`, and only\n // `Origin` says who asked. That such a request is blocked today is\n // incidental — it needs a CORS preflight, `OPTIONS` is unrouted, and the\n // local app registers no CORS — and it stops being true the moment any of\n // those three changes.\n if (opts.allowedOriginHostnames !== undefined) {\n // Checked rather than trusted, and refused here rather than absorbed:\n // every wrong shape fails silently at request time, and two of them fail\n // permissively.\n //\n // `null` — what a config read from JSON or an env var yields where a\n // list is missing — counts as \"configured\", and the validator then calls\n // `null.includes(hostname)` inside an `onRequest` hook, so every request\n // to the endpoint 500s with nothing naming the option that did it. A\n // bare string is worse than broken: `String.prototype.includes` matches\n // substrings, so `\"localhost\"` would admit an origin whose hostname is\n // `\"host\"`.\n //\n // WHY a throw and not a no-op: this option exists to restrict, and the\n // caller who passed it believes they are protected. Quietly mounting\n // nothing would leave them unprotected and unaware — the one outcome\n // worse than a startup failure. Registration runs once, at boot, so this\n // cannot fire on live traffic.\n if (\n !Array.isArray(opts.allowedOriginHostnames) ||\n opts.allowedOriginHostnames.some((name) => typeof name !== \"string\")\n ) {\n throw new TypeError(\n 'allowedOriginHostnames must be an array of hostname strings, e.g. [\"localhost\", \"127.0.0.1\"]. Omit it to mount no origin validation.'\n );\n }\n fastify.addHook(\n \"onRequest\",\n originValidation(opts.allowedOriginHostnames)\n );\n }\n\n const hostTools =\n opts.hostTools === undefined\n ? undefined\n : {\n names: checkedHostToolNames(opts.hostTools),\n register: opts.hostTools.register,\n };\n\n const handleMcp = async (\n request: FastifyRequest,\n reply: FastifyReply\n ): Promise<void> => {\n // RFC 9110 makes `Allow` a MUST on a 405, and the SDK sends none.\n //\n // NOTE it must be set on `reply.raw`, not through `reply.header()`.\n // Fastify stages headers on its own reply object and flushes them when\n // it serializes the response — which never happens once the reply is\n // hijacked, so `reply.header()` here is silently dropped. Writing to the\n // Node response directly is what survives.\n //\n // Only for the methods that will 405: a successful POST has no business\n // advertising `Allow`.\n if (request.method !== \"POST\") {\n reply.raw.setHeader(\"Allow\", \"POST\");\n }\n\n // WHY the factory is built here, inside the route handler, rather than\n // once at registration: the tool callbacks close over `request`\n // lexically, so the host application's per-request context reaches the\n // datasource without this package knowing anything about tenants or\n // credentials. That makes the handler per-request too.\n //\n // The alternative, AsyncLocalStorage, was rejected for consistency:\n // this codebase threads `requestContext` explicitly at every existing\n // call site and uses AsyncLocalStorage nowhere.\n //\n // NOTE `responseMode` is deliberately not passed. It is byte-identical\n // to the `auto` default across every combination measured, its only\n // observable effect is a console.warn emitted once per\n // `createMcpHandler` — which here is once per request — and it silently\n // drops mid-call notifications.\n const handler = createMcpHandler(() => {\n const server = new McpServer({\n name: SERVER_NAME,\n version: SERVER_VERSION,\n });\n const toolOptions: RegisterToolsOptions = {\n readTelemetryDatasource: opts.readTelemetryDatasource,\n requestContext: request.requestContext,\n // Per-request, so an upstream failure is logged with the same\n // request id as everything else Fastify wrote about that call.\n logger: opts.logger ?? request.log,\n // The request is attached here rather than inside the tool layer,\n // which knows nothing about HTTP.\n onToolCall: opts.onToolCall\n ? (event) => opts.onToolCall?.({ ...event, request })\n : undefined,\n };\n registerTools(server, toolOptions);\n // After the built-ins, so a host tool can never take their place. A\n // throw here fails this request rather than falling back to the\n // built-ins alone.\n //\n // NOTE logged here because nothing else logs it: the SDK answers a\n // throwing factory with a bare JSON-RPC internal error and passes the\n // error to no `onerror`.\n if (hostTools !== undefined) {\n try {\n registerHostTools(server, {\n ...toolOptions,\n names: hostTools.names,\n register: (s) => hostTools.register(s, request),\n });\n } catch (error) {\n toolOptions.logger?.error(error, \"MCP hostTools.register failed\");\n throw error;\n }\n }\n return server;\n });\n\n reply.hijack();\n // The third argument is the body Fastify has already parsed and\n // drained; passing it means nothing is read from a stream that is\n // already consumed.\n await toNodeHandler(handler, {\n onerror: (error: unknown) => fastify.log.error(error),\n })(request.raw, reply.raw, request.body);\n };\n\n // POST is the endpoint. GET and DELETE are routed only so that the SDK\n // gets to answer them 405 — with just a POST route, Fastify's own 404\n // handler replies first and the SDK is never consulted. The difference is\n // not cosmetic: Streamable HTTP defines GET as \"open an SSE stream\", and\n // requires either an event-stream response or a 405. A client that probes\n // GET and receives 404 reads the endpoint as gone rather than as healthy\n // and non-streaming.\n //\n // OPTIONS is deliberately left unrouted. The SDK would answer it 405 like\n // any other non-POST method, which would intercept CORS preflight — and\n // preflight belongs to whatever CORS plugin the host application\n // registers, which differs between the two mounts. PUT and PATCH stay\n // unrouted too and fall through to Fastify's 404; the spec says nothing\n // about them and no client sends them.\n fastify.route({ method: \"POST\", url: \"/mcp\", handler: handleMcp });\n fastify.route({ method: \"GET\", url: \"/mcp\", handler: handleMcp });\n fastify.route({ method: \"DELETE\", url: \"/mcp\", handler: handleMcp });\n };\n"],"mappings":";;;;;;;AAuBA,MAAM,+BAAe,IAAI,IAAI;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,+BAAe,IAAI,IAAI;CAAC;CAAS;CAAS;CAAS;AAAa,CAAC;;AAGvE,MAAM,6BAAa,IAAI,IAAI;CACzB;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;AAQD,SAAS,WACP,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AChE,MAAM;GACR;GAEF,OAAO;EACT,CAAC;EAED,MAAM,OAAO;EAIb,MAAM,cAAc,SAAS,EAC3B,UAAU,UAAmB,QAAQ,IAAI,MAAM,KAAK,EACtD,CAAC,CAAC,CAAC,QAAQ,KAAK,MAAM,KAAK,QAAQ,IAAI;CACzC;CAgBA,QAAQ,MAAM;EAAE,QAAQ;EAAQ,KAAK;EAAQ,SAAS;CAAU,CAAC;CACjE,QAAQ,MAAM;EAAE,QAAQ;EAAO,KAAK;EAAQ,SAAS;CAAU,CAAC;CAChE,QAAQ,MAAM;EAAE,QAAQ;EAAU,KAAK;EAAQ,SAAS;CAAU,CAAC;AACrE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kopai/mcp",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "license": "Apache-2.0",
5
5
  "author": "Vladimir Adamic",
6
6
  "repository": {
@@ -28,22 +28,22 @@
28
28
  ],
29
29
  "peerDependencies": {
30
30
  "@kopai/core": "^0.14.0",
31
- "fastify": "^5.12.7",
31
+ "fastify": "^5.12.8",
32
32
  "zod": "^4.0.0"
33
33
  },
34
34
  "dependencies": {
35
35
  "@modelcontextprotocol/fastify": "2.0.1",
36
- "@modelcontextprotocol/node": "2.1.1",
37
- "@modelcontextprotocol/server": "2.3.1"
36
+ "@modelcontextprotocol/node": "2.1.2",
37
+ "@modelcontextprotocol/server": "2.4.0"
38
38
  },
39
39
  "devDependencies": {
40
40
  "ajv": "^8.20.0",
41
- "fastify": "^5.12.7",
42
- "tsdown": "^0.23.1",
41
+ "fastify": "^5.12.8",
42
+ "tsdown": "^0.23.7",
43
43
  "zod": "^4.6.7",
44
- "@kopai/sqlite-datasource": "0.15.0",
45
- "@kopai/tsconfig": "0.2.0",
46
- "@kopai/core": "0.14.0"
44
+ "@kopai/core": "0.14.0",
45
+ "@kopai/sqlite-datasource": "0.15.1",
46
+ "@kopai/tsconfig": "0.2.0"
47
47
  },
48
48
  "scripts": {
49
49
  "build": "tsdown",