@kopai/mcp 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +9 -18
- package/dist/index.d.cts +0 -20
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +0 -20
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +9 -18
- package/dist/index.mjs.map +1 -1
- package/package.json +8 -8
package/dist/index.cjs
CHANGED
|
@@ -4,7 +4,7 @@ let _modelcontextprotocol_server = require("@modelcontextprotocol/server");
|
|
|
4
4
|
let zod = require("zod");
|
|
5
5
|
let _modelcontextprotocol_fastify = require("@modelcontextprotocol/fastify");
|
|
6
6
|
let _modelcontextprotocol_node = require("@modelcontextprotocol/node");
|
|
7
|
-
|
|
7
|
+
// src/dedupe.ts
|
|
8
8
|
/** Keywords whose value is a single schema. */
|
|
9
9
|
const SCHEMA_VALUE = /* @__PURE__ */ new Set([
|
|
10
10
|
"items",
|
|
@@ -97,8 +97,7 @@ function dedupe(doc, minLen = 60) {
|
|
|
97
97
|
result.$defs = defs;
|
|
98
98
|
return result;
|
|
99
99
|
}
|
|
100
|
-
|
|
101
|
-
//#region src/limits.ts
|
|
100
|
+
// src/limits.ts
|
|
102
101
|
/**
|
|
103
102
|
* Row caps, per mode.
|
|
104
103
|
*
|
|
@@ -252,8 +251,7 @@ function overflowRemedies(query, limit, max) {
|
|
|
252
251
|
narrower
|
|
253
252
|
];
|
|
254
253
|
}
|
|
255
|
-
|
|
256
|
-
//#region src/describe.ts
|
|
254
|
+
// src/describe.ts
|
|
257
255
|
function descriptionOverrides(rawMax, aggregateMax, rawDefault, aggregateDefault) {
|
|
258
256
|
return [
|
|
259
257
|
{
|
|
@@ -301,8 +299,7 @@ function applyDescriptions(doc, overrides) {
|
|
|
301
299
|
applied
|
|
302
300
|
};
|
|
303
301
|
}
|
|
304
|
-
|
|
305
|
-
//#region src/schema.ts
|
|
302
|
+
// src/schema.ts
|
|
306
303
|
/**
|
|
307
304
|
* The `query` tool's input: the KopaiQuery body under a single `query`
|
|
308
305
|
* property, because an MCP tool's input schema must have an object root and
|
|
@@ -336,8 +333,7 @@ const METRICS_DISCOVER_TOOL_INPUT_SCHEMA = {
|
|
|
336
333
|
type: "object",
|
|
337
334
|
properties: {}
|
|
338
335
|
};
|
|
339
|
-
|
|
340
|
-
//#region src/results.ts
|
|
336
|
+
// src/results.ts
|
|
341
337
|
/**
|
|
342
338
|
* Builds a result carrying `payload` in BOTH channels — as
|
|
343
339
|
* `structuredContent`, and as a single text block holding exactly
|
|
@@ -404,8 +400,7 @@ function prefixIssuePaths(issues) {
|
|
|
404
400
|
message
|
|
405
401
|
}));
|
|
406
402
|
}
|
|
407
|
-
|
|
408
|
-
//#region src/tools.ts
|
|
403
|
+
// src/tools.ts
|
|
409
404
|
function invalidInput(message, issues) {
|
|
410
405
|
return {
|
|
411
406
|
result: errorResult({
|
|
@@ -582,8 +577,7 @@ async function runMetricsDiscoverTool(ctx) {
|
|
|
582
577
|
}
|
|
583
578
|
return tooLarge(`The listing of ${full.metrics.length.toLocaleString("en-US")} metrics serialized to ${serialized.length.toLocaleString("en-US")} characters even without their attributes, above the ${MAX_RESULT_CHARACTERS.toLocaleString("en-US")} the host will accept.`, DISCOVERY_SIZE_REMEDIES);
|
|
584
579
|
}
|
|
585
|
-
|
|
586
|
-
//#region src/validator.ts
|
|
580
|
+
// src/validator.ts
|
|
587
581
|
/**
|
|
588
582
|
* A validator provider that accepts everything, so that the tool handler is
|
|
589
583
|
* what validates.
|
|
@@ -615,8 +609,7 @@ const passThroughValidator = { getValidator() {
|
|
|
615
609
|
errorMessage: void 0
|
|
616
610
|
});
|
|
617
611
|
} };
|
|
618
|
-
|
|
619
|
-
//#region src/register.ts
|
|
612
|
+
// src/register.ts
|
|
620
613
|
/**
|
|
621
614
|
* Both tools read and never write, always return the same answer for the same
|
|
622
615
|
* arguments and window, and reach nothing outside this deployment.
|
|
@@ -709,8 +702,7 @@ function registerTools(server, opts) {
|
|
|
709
702
|
}
|
|
710
703
|
}, async () => call("metrics_discover", () => runMetricsDiscoverTool(opts)));
|
|
711
704
|
}
|
|
712
|
-
|
|
713
|
-
//#region src/routes.ts
|
|
705
|
+
// src/routes.ts
|
|
714
706
|
const SERVER_NAME = "kopai";
|
|
715
707
|
const SERVER_VERSION = "0.0.0";
|
|
716
708
|
/**
|
|
@@ -763,7 +755,6 @@ const mcpRoutes = async function mcpRoutes(fastify, opts) {
|
|
|
763
755
|
handler: handleMcp
|
|
764
756
|
});
|
|
765
757
|
};
|
|
766
|
-
//#endregion
|
|
767
758
|
exports.DESCRIPTION_OVERRIDES_APPLIED = DESCRIPTION_OVERRIDES_APPLIED;
|
|
768
759
|
exports.DISCOVERY_SIZE_REMEDIES = DISCOVERY_SIZE_REMEDIES;
|
|
769
760
|
exports.LIMITS = LIMITS;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { datasource, kopaiQuery } from "@kopai/core";
|
|
2
2
|
import { McpServer, jsonSchemaValidator } from "@modelcontextprotocol/server";
|
|
3
3
|
import { FastifyPluginAsync, FastifyRequest } from "fastify";
|
|
4
|
-
//#region src/dedupe.d.ts
|
|
5
4
|
type SchemaNode$1 = Record<string, unknown>;
|
|
6
5
|
/**
|
|
7
6
|
* Returns `doc` with every subschema that occurs more than once hoisted into
|
|
@@ -13,8 +12,6 @@ type SchemaNode$1 = Record<string, unknown>;
|
|
|
13
12
|
* deduplicated alongside the body.
|
|
14
13
|
*/
|
|
15
14
|
export declare function dedupe(doc: SchemaNode$1, minLen?: number): SchemaNode$1;
|
|
16
|
-
//#endregion
|
|
17
|
-
//#region src/limits.d.ts
|
|
18
15
|
/**
|
|
19
16
|
* Row caps, per mode.
|
|
20
17
|
*
|
|
@@ -93,8 +90,6 @@ export declare const SIZE_REMEDIES: readonly ["Lower `limit`.", "Narrow the time
|
|
|
93
90
|
* though it were the whole set.
|
|
94
91
|
*/
|
|
95
92
|
export declare function overflowRemedies(query: kopaiQuery.KopaiQuery, limit: number, max: number): string[];
|
|
96
|
-
//#endregion
|
|
97
|
-
//#region src/types.d.ts
|
|
98
93
|
/**
|
|
99
94
|
* How a tool call ended. These four labels are the server's whole error
|
|
100
95
|
* vocabulary: they are the `error` code on a failed result, the `outcome` on
|
|
@@ -180,8 +175,6 @@ declare module "fastify" {
|
|
|
180
175
|
requestContext?: unknown;
|
|
181
176
|
}
|
|
182
177
|
}
|
|
183
|
-
//#endregion
|
|
184
|
-
//#region src/results.d.ts
|
|
185
178
|
/** An error code a tool can return. `ok` is not one of them. */
|
|
186
179
|
type ToolErrorCode = Exclude<ToolCallOutcome, "ok">;
|
|
187
180
|
interface ToolIssue {
|
|
@@ -245,8 +238,6 @@ export declare function errorResult(payload: ToolErrorPayload): ToolResult;
|
|
|
245
238
|
* `query` rather than `query.`.
|
|
246
239
|
*/
|
|
247
240
|
export declare function prefixIssuePaths(issues: ToolIssue[]): ToolIssue[];
|
|
248
|
-
//#endregion
|
|
249
|
-
//#region src/tools.d.ts
|
|
250
241
|
interface ToolContext {
|
|
251
242
|
readTelemetryDatasource: datasource.ReadTelemetryDatasource;
|
|
252
243
|
/** Whatever the host application attached to the request; passed through. */
|
|
@@ -266,8 +257,6 @@ interface ToolRun {
|
|
|
266
257
|
}
|
|
267
258
|
export declare function runQueryTool(input: unknown, ctx: ToolContext): Promise<ToolRun>;
|
|
268
259
|
export declare function runMetricsDiscoverTool(ctx: ToolContext): Promise<ToolRun>;
|
|
269
|
-
//#endregion
|
|
270
|
-
//#region src/register.d.ts
|
|
271
260
|
interface RegisterToolsOptions extends ToolContext {
|
|
272
261
|
/**
|
|
273
262
|
* Called once per completed tool call, after the result is built and before
|
|
@@ -287,8 +276,6 @@ interface RegisterToolsOptions extends ToolContext {
|
|
|
287
276
|
* tool throws, which is returned as a structured error rather than rethrown.
|
|
288
277
|
*/
|
|
289
278
|
export declare function registerTools(server: McpServer, opts: RegisterToolsOptions): void;
|
|
290
|
-
//#endregion
|
|
291
|
-
//#region src/routes.d.ts
|
|
292
279
|
/**
|
|
293
280
|
* Mounts the MCP endpoint at `/mcp`, relative to wherever this plugin is
|
|
294
281
|
* registered.
|
|
@@ -297,8 +284,6 @@ export declare function registerTools(server: McpServer, opts: RegisterToolsOpti
|
|
|
297
284
|
* `McpServer` per request.
|
|
298
285
|
*/
|
|
299
286
|
export declare const mcpRoutes: FastifyPluginAsync<McpRoutesOptions>;
|
|
300
|
-
//#endregion
|
|
301
|
-
//#region src/describe.d.ts
|
|
302
287
|
type SchemaNode = Record<string, unknown>;
|
|
303
288
|
interface DescriptionOverride {
|
|
304
289
|
/** Start of the description to match, in the shared schema. */
|
|
@@ -316,8 +301,6 @@ export declare function applyDescriptions(doc: SchemaNode, overrides: readonly D
|
|
|
316
301
|
document: SchemaNode;
|
|
317
302
|
applied: Record<string, number>;
|
|
318
303
|
};
|
|
319
|
-
//#endregion
|
|
320
|
-
//#region src/schema.d.ts
|
|
321
304
|
/** How many nodes each override matched. Asserted in the tests, not at runtime. */
|
|
322
305
|
export declare const DESCRIPTION_OVERRIDES_APPLIED: Record<string, number>;
|
|
323
306
|
export declare const QUERY_TOOL_INPUT_SCHEMA: Record<string, unknown>;
|
|
@@ -326,8 +309,6 @@ export declare const QUERY_TOOL_INPUT_SCHEMA: Record<string, unknown>;
|
|
|
326
309
|
* object root.
|
|
327
310
|
*/
|
|
328
311
|
export declare const METRICS_DISCOVER_TOOL_INPUT_SCHEMA: Record<string, unknown>;
|
|
329
|
-
//#endregion
|
|
330
|
-
//#region src/validator.d.ts
|
|
331
312
|
/**
|
|
332
313
|
* A validator provider that accepts everything, so that the tool handler is
|
|
333
314
|
* what validates.
|
|
@@ -353,6 +334,5 @@ export declare const METRICS_DISCOVER_TOOL_INPUT_SCHEMA: Record<string, unknown>
|
|
|
353
334
|
* broken" rather than as a bad argument.
|
|
354
335
|
*/
|
|
355
336
|
export declare const passThroughValidator: jsonSchemaValidator;
|
|
356
|
-
//#endregion
|
|
357
337
|
export type { DescriptionOverride, McpRoutesOptions, RegisterToolsOptions, ToolCallEvent, ToolCallOutcome, ToolContext, ToolErrorCode, ToolErrorPayload, ToolIssue, ToolResult, ToolRun };
|
|
358
338
|
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"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":"
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":["SchemaNode"],"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;;qBAMA;;;;;;;;;;;;;;;;;;wBA6EG,iBACd,OAAO,WAAW,YAClB,eACA;;;;;;KC3IU;;;;;;;;;UAWK;EACf,MAAM,kBAAkB;;;;;;;;;;UAWT;EACf;EACA,SAAS;EACT;;EAEA;EACA,SAAS;;UAGM;EACf,yBAAyB,WAAW;;;;;;EAMpC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+BA;;;;;EAKA,SAAS;;EAET,cAAc,OAAO;;;YAQX;IACR;;;;KC3FQ,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;UCtEtC;EACf,yBAAyB,WAAW;;EAEpC;;EAEA,SAAS;;;;;;;UAQM;EACf,QAAQ;EACR,SAAS;EACT;;wBAiFoB,aACpB,gBACA,KAAK,cACJ,QAAQ;wBA4LW,uBACpB,KAAK,cACJ,QAAQ;UCvPM,6BAA6B;;;;;EAK5C,cAAc;IACZ;IACA,SAAS;IACT;IACA;;;;;;;;;wBAUY,cACd,QAAQ,WACR,MAAM;;;;;;;;qBC5DK,WAAW,mBAAmB;KCFtC,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.d.mts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { datasource, kopaiQuery } from "@kopai/core";
|
|
2
2
|
import { McpServer, jsonSchemaValidator } from "@modelcontextprotocol/server";
|
|
3
3
|
import { FastifyPluginAsync, FastifyRequest } from "fastify";
|
|
4
|
-
//#region src/dedupe.d.ts
|
|
5
4
|
type SchemaNode$1 = Record<string, unknown>;
|
|
6
5
|
/**
|
|
7
6
|
* Returns `doc` with every subschema that occurs more than once hoisted into
|
|
@@ -13,8 +12,6 @@ type SchemaNode$1 = Record<string, unknown>;
|
|
|
13
12
|
* deduplicated alongside the body.
|
|
14
13
|
*/
|
|
15
14
|
export declare function dedupe(doc: SchemaNode$1, minLen?: number): SchemaNode$1;
|
|
16
|
-
//#endregion
|
|
17
|
-
//#region src/limits.d.ts
|
|
18
15
|
/**
|
|
19
16
|
* Row caps, per mode.
|
|
20
17
|
*
|
|
@@ -93,8 +90,6 @@ export declare const SIZE_REMEDIES: readonly ["Lower `limit`.", "Narrow the time
|
|
|
93
90
|
* though it were the whole set.
|
|
94
91
|
*/
|
|
95
92
|
export declare function overflowRemedies(query: kopaiQuery.KopaiQuery, limit: number, max: number): string[];
|
|
96
|
-
//#endregion
|
|
97
|
-
//#region src/types.d.ts
|
|
98
93
|
/**
|
|
99
94
|
* How a tool call ended. These four labels are the server's whole error
|
|
100
95
|
* vocabulary: they are the `error` code on a failed result, the `outcome` on
|
|
@@ -180,8 +175,6 @@ declare module "fastify" {
|
|
|
180
175
|
requestContext?: unknown;
|
|
181
176
|
}
|
|
182
177
|
}
|
|
183
|
-
//#endregion
|
|
184
|
-
//#region src/results.d.ts
|
|
185
178
|
/** An error code a tool can return. `ok` is not one of them. */
|
|
186
179
|
type ToolErrorCode = Exclude<ToolCallOutcome, "ok">;
|
|
187
180
|
interface ToolIssue {
|
|
@@ -245,8 +238,6 @@ export declare function errorResult(payload: ToolErrorPayload): ToolResult;
|
|
|
245
238
|
* `query` rather than `query.`.
|
|
246
239
|
*/
|
|
247
240
|
export declare function prefixIssuePaths(issues: ToolIssue[]): ToolIssue[];
|
|
248
|
-
//#endregion
|
|
249
|
-
//#region src/tools.d.ts
|
|
250
241
|
interface ToolContext {
|
|
251
242
|
readTelemetryDatasource: datasource.ReadTelemetryDatasource;
|
|
252
243
|
/** Whatever the host application attached to the request; passed through. */
|
|
@@ -266,8 +257,6 @@ interface ToolRun {
|
|
|
266
257
|
}
|
|
267
258
|
export declare function runQueryTool(input: unknown, ctx: ToolContext): Promise<ToolRun>;
|
|
268
259
|
export declare function runMetricsDiscoverTool(ctx: ToolContext): Promise<ToolRun>;
|
|
269
|
-
//#endregion
|
|
270
|
-
//#region src/register.d.ts
|
|
271
260
|
interface RegisterToolsOptions extends ToolContext {
|
|
272
261
|
/**
|
|
273
262
|
* Called once per completed tool call, after the result is built and before
|
|
@@ -287,8 +276,6 @@ interface RegisterToolsOptions extends ToolContext {
|
|
|
287
276
|
* tool throws, which is returned as a structured error rather than rethrown.
|
|
288
277
|
*/
|
|
289
278
|
export declare function registerTools(server: McpServer, opts: RegisterToolsOptions): void;
|
|
290
|
-
//#endregion
|
|
291
|
-
//#region src/routes.d.ts
|
|
292
279
|
/**
|
|
293
280
|
* Mounts the MCP endpoint at `/mcp`, relative to wherever this plugin is
|
|
294
281
|
* registered.
|
|
@@ -297,8 +284,6 @@ export declare function registerTools(server: McpServer, opts: RegisterToolsOpti
|
|
|
297
284
|
* `McpServer` per request.
|
|
298
285
|
*/
|
|
299
286
|
export declare const mcpRoutes: FastifyPluginAsync<McpRoutesOptions>;
|
|
300
|
-
//#endregion
|
|
301
|
-
//#region src/describe.d.ts
|
|
302
287
|
type SchemaNode = Record<string, unknown>;
|
|
303
288
|
interface DescriptionOverride {
|
|
304
289
|
/** Start of the description to match, in the shared schema. */
|
|
@@ -316,8 +301,6 @@ export declare function applyDescriptions(doc: SchemaNode, overrides: readonly D
|
|
|
316
301
|
document: SchemaNode;
|
|
317
302
|
applied: Record<string, number>;
|
|
318
303
|
};
|
|
319
|
-
//#endregion
|
|
320
|
-
//#region src/schema.d.ts
|
|
321
304
|
/** How many nodes each override matched. Asserted in the tests, not at runtime. */
|
|
322
305
|
export declare const DESCRIPTION_OVERRIDES_APPLIED: Record<string, number>;
|
|
323
306
|
export declare const QUERY_TOOL_INPUT_SCHEMA: Record<string, unknown>;
|
|
@@ -326,8 +309,6 @@ export declare const QUERY_TOOL_INPUT_SCHEMA: Record<string, unknown>;
|
|
|
326
309
|
* object root.
|
|
327
310
|
*/
|
|
328
311
|
export declare const METRICS_DISCOVER_TOOL_INPUT_SCHEMA: Record<string, unknown>;
|
|
329
|
-
//#endregion
|
|
330
|
-
//#region src/validator.d.ts
|
|
331
312
|
/**
|
|
332
313
|
* A validator provider that accepts everything, so that the tool handler is
|
|
333
314
|
* what validates.
|
|
@@ -353,6 +334,5 @@ export declare const METRICS_DISCOVER_TOOL_INPUT_SCHEMA: Record<string, unknown>
|
|
|
353
334
|
* broken" rather than as a bad argument.
|
|
354
335
|
*/
|
|
355
336
|
export declare const passThroughValidator: jsonSchemaValidator;
|
|
356
|
-
//#endregion
|
|
357
337
|
export type { DescriptionOverride, McpRoutesOptions, RegisterToolsOptions, ToolCallEvent, ToolCallOutcome, ToolContext, ToolErrorCode, ToolErrorPayload, ToolIssue, ToolResult, ToolRun };
|
|
358
338
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"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":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":["SchemaNode"],"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;;qBAMA;;;;;;;;;;;;;;;;;;wBA6EG,iBACd,OAAO,WAAW,YAClB,eACA;;;;;;KC3IU;;;;;;;;;UAWK;EACf,MAAM,kBAAkB;;;;;;;;;;UAWT;EACf;EACA,SAAS;EACT;;EAEA;EACA,SAAS;;UAGM;EACf,yBAAyB,WAAW;;;;;;EAMpC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+BA;;;;;EAKA,SAAS;;EAET,cAAc,OAAO;;;YAQX;IACR;;;;KC3FQ,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;UCtEtC;EACf,yBAAyB,WAAW;;EAEpC;;EAEA,SAAS;;;;;;;UAQM;EACf,QAAQ;EACR,SAAS;EACT;;wBAiFoB,aACpB,gBACA,KAAK,cACJ,QAAQ;wBA4LW,uBACpB,KAAK,cACJ,QAAQ;UCvPM,6BAA6B;;;;;EAK5C,cAAc;IACZ;IACA,SAAS;IACT;IACA;;;;;;;;;wBAUY,cACd,QAAQ,WACR,MAAM;;;;;;;;qBC5DK,WAAW,mBAAmB;KCFtC,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
|
@@ -3,7 +3,7 @@ import { McpServer, createMcpHandler, fromJsonSchema } from "@modelcontextprotoc
|
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
import { hostHeaderValidation, originValidation } from "@modelcontextprotocol/fastify";
|
|
5
5
|
import { toNodeHandler } from "@modelcontextprotocol/node";
|
|
6
|
-
|
|
6
|
+
// src/dedupe.ts
|
|
7
7
|
/** Keywords whose value is a single schema. */
|
|
8
8
|
const SCHEMA_VALUE = /* @__PURE__ */ new Set([
|
|
9
9
|
"items",
|
|
@@ -96,8 +96,7 @@ function dedupe(doc, minLen = 60) {
|
|
|
96
96
|
result.$defs = defs;
|
|
97
97
|
return result;
|
|
98
98
|
}
|
|
99
|
-
|
|
100
|
-
//#region src/limits.ts
|
|
99
|
+
// src/limits.ts
|
|
101
100
|
/**
|
|
102
101
|
* Row caps, per mode.
|
|
103
102
|
*
|
|
@@ -251,8 +250,7 @@ function overflowRemedies(query, limit, max) {
|
|
|
251
250
|
narrower
|
|
252
251
|
];
|
|
253
252
|
}
|
|
254
|
-
|
|
255
|
-
//#region src/describe.ts
|
|
253
|
+
// src/describe.ts
|
|
256
254
|
function descriptionOverrides(rawMax, aggregateMax, rawDefault, aggregateDefault) {
|
|
257
255
|
return [
|
|
258
256
|
{
|
|
@@ -300,8 +298,7 @@ function applyDescriptions(doc, overrides) {
|
|
|
300
298
|
applied
|
|
301
299
|
};
|
|
302
300
|
}
|
|
303
|
-
|
|
304
|
-
//#region src/schema.ts
|
|
301
|
+
// src/schema.ts
|
|
305
302
|
/**
|
|
306
303
|
* The `query` tool's input: the KopaiQuery body under a single `query`
|
|
307
304
|
* property, because an MCP tool's input schema must have an object root and
|
|
@@ -335,8 +332,7 @@ const METRICS_DISCOVER_TOOL_INPUT_SCHEMA = {
|
|
|
335
332
|
type: "object",
|
|
336
333
|
properties: {}
|
|
337
334
|
};
|
|
338
|
-
|
|
339
|
-
//#region src/results.ts
|
|
335
|
+
// src/results.ts
|
|
340
336
|
/**
|
|
341
337
|
* Builds a result carrying `payload` in BOTH channels — as
|
|
342
338
|
* `structuredContent`, and as a single text block holding exactly
|
|
@@ -403,8 +399,7 @@ function prefixIssuePaths(issues) {
|
|
|
403
399
|
message
|
|
404
400
|
}));
|
|
405
401
|
}
|
|
406
|
-
|
|
407
|
-
//#region src/tools.ts
|
|
402
|
+
// src/tools.ts
|
|
408
403
|
function invalidInput(message, issues) {
|
|
409
404
|
return {
|
|
410
405
|
result: errorResult({
|
|
@@ -581,8 +576,7 @@ async function runMetricsDiscoverTool(ctx) {
|
|
|
581
576
|
}
|
|
582
577
|
return tooLarge(`The listing of ${full.metrics.length.toLocaleString("en-US")} metrics serialized to ${serialized.length.toLocaleString("en-US")} characters even without their attributes, above the ${MAX_RESULT_CHARACTERS.toLocaleString("en-US")} the host will accept.`, DISCOVERY_SIZE_REMEDIES);
|
|
583
578
|
}
|
|
584
|
-
|
|
585
|
-
//#region src/validator.ts
|
|
579
|
+
// src/validator.ts
|
|
586
580
|
/**
|
|
587
581
|
* A validator provider that accepts everything, so that the tool handler is
|
|
588
582
|
* what validates.
|
|
@@ -614,8 +608,7 @@ const passThroughValidator = { getValidator() {
|
|
|
614
608
|
errorMessage: void 0
|
|
615
609
|
});
|
|
616
610
|
} };
|
|
617
|
-
|
|
618
|
-
//#region src/register.ts
|
|
611
|
+
// src/register.ts
|
|
619
612
|
/**
|
|
620
613
|
* Both tools read and never write, always return the same answer for the same
|
|
621
614
|
* arguments and window, and reach nothing outside this deployment.
|
|
@@ -708,8 +701,7 @@ function registerTools(server, opts) {
|
|
|
708
701
|
}
|
|
709
702
|
}, async () => call("metrics_discover", () => runMetricsDiscoverTool(opts)));
|
|
710
703
|
}
|
|
711
|
-
|
|
712
|
-
//#region src/routes.ts
|
|
704
|
+
// src/routes.ts
|
|
713
705
|
const SERVER_NAME = "kopai";
|
|
714
706
|
const SERVER_VERSION = "0.0.0";
|
|
715
707
|
/**
|
|
@@ -762,7 +754,6 @@ const mcpRoutes = async function mcpRoutes(fastify, opts) {
|
|
|
762
754
|
handler: handleMcp
|
|
763
755
|
});
|
|
764
756
|
};
|
|
765
|
-
//#endregion
|
|
766
757
|
export { DESCRIPTION_OVERRIDES_APPLIED, DISCOVERY_SIZE_REMEDIES, LIMITS, MAX_RESULT_CHARACTERS, METRICS_DISCOVER_TOOL_INPUT_SCHEMA, QUERY_TOOL_INPUT_SCHEMA, SIZE_REMEDIES, applyDescriptions, dedupe, descriptionOverrides, errorResult, mcpRoutes, okResult, overflowRemedies, passThroughValidator, prefixIssuePaths, registerTools, runMetricsDiscoverTool, runQueryTool };
|
|
767
758
|
|
|
768
759
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/dedupe.ts","../src/limits.ts","../src/describe.ts","../src/schema.ts","../src/results.ts","../src/tools.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/** 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 both tools return. 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_SIZE_REMEDIES,\n LIMITS,\n MAX_RESULT_CHARACTERS,\n overflowRemedies,\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 * Maps a thrown error onto an outcome, mirroring the REST error handler:\n * a recognised validation error surfaces its own message, and anything\n * unrecognised surfaces a generic string with the detail written to the log.\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.\n */\nexport function fromThrown(error: unknown, logger?: ToolLogger): ToolRun {\n if (error instanceof kopaiQueryCompiler.KopaiQueryValidationError) {\n return invalidInput(error.message);\n }\n logger?.error(error, \"MCP tool call failed\");\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);\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 {\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 { LIMITS, MAX_RESULT_CHARACTERS } from \"./limits.js\";\nimport {\n METRICS_DISCOVER_TOOL_INPUT_SCHEMA,\n QUERY_TOOL_INPUT_SCHEMA,\n} from \"./schema.js\";\nimport type { ToolResult } from \"./results.js\";\nimport {\n fromThrown,\n runMetricsDiscoverTool,\n runQueryTool,\n type ToolContext,\n type ToolRun,\n} from \"./tools.js\";\nimport type { ToolCallOutcome } 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\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/**\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 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,\n });\n } catch {\n // deliberately swallowed\n }\n };\n\n /**\n * Runs one tool call and reports it, whatever happens.\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 */\n const call = async (\n tool: string,\n execute: () => Promise<ToolRun>\n ): Promise<ToolResult> => {\n const startedAt = Date.now();\n let run: ToolRun;\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 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) => call(\"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 () => call(\"metrics_discover\", () => runMetricsDiscoverTool(opts))\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 { registerTools } from \"./register.js\";\nimport type { McpRoutesOptions } from \"./types.js\";\n\nconst SERVER_NAME = \"kopai\";\nconst SERVER_VERSION = \"0.0.0\";\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 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 registerTools(server, {\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 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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
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/dedupe.ts","../src/limits.ts","../src/describe.ts","../src/schema.ts","../src/results.ts","../src/tools.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/** 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 both tools return. 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_SIZE_REMEDIES,\n LIMITS,\n MAX_RESULT_CHARACTERS,\n overflowRemedies,\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 * Maps a thrown error onto an outcome, mirroring the REST error handler:\n * a recognised validation error surfaces its own message, and anything\n * unrecognised surfaces a generic string with the detail written to the log.\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.\n */\nexport function fromThrown(error: unknown, logger?: ToolLogger): ToolRun {\n if (error instanceof kopaiQueryCompiler.KopaiQueryValidationError) {\n return invalidInput(error.message);\n }\n logger?.error(error, \"MCP tool call failed\");\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);\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 {\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 { LIMITS, MAX_RESULT_CHARACTERS } from \"./limits.js\";\nimport {\n METRICS_DISCOVER_TOOL_INPUT_SCHEMA,\n QUERY_TOOL_INPUT_SCHEMA,\n} from \"./schema.js\";\nimport type { ToolResult } from \"./results.js\";\nimport {\n fromThrown,\n runMetricsDiscoverTool,\n runQueryTool,\n type ToolContext,\n type ToolRun,\n} from \"./tools.js\";\nimport type { ToolCallOutcome } 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\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/**\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 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,\n });\n } catch {\n // deliberately swallowed\n }\n };\n\n /**\n * Runs one tool call and reports it, whatever happens.\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 */\n const call = async (\n tool: string,\n execute: () => Promise<ToolRun>\n ): Promise<ToolResult> => {\n const startedAt = Date.now();\n let run: ToolRun;\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 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) => call(\"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 () => call(\"metrics_discover\", () => runMetricsDiscoverTool(opts))\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 { registerTools } from \"./register.js\";\nimport type { McpRoutesOptions } from \"./types.js\";\n\nconst SERVER_NAME = \"kopai\";\nconst SERVER_VERSION = \"0.0.0\";\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 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 registerTools(server, {\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 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,MACA,IACA,SAAS,OACA;CACT,IAAI,CAAC,QAAQ,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GAAG,OAAO;CACrE,MAAM,MAAM;CAEZ,IAAI,CAAC,QAAQ;EACX,MAAM,cAAc,GAAG,GAAG;EAC1B,IAAI,gBAAgB,KAAA,GAAW,OAAO;CACxC;CAEA,MAAM,MAAkB,CAAC;CACzB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,GAAG,GAC3C,IACE,aAAa,IAAI,GAAG,KACpB,SACA,OAAO,UAAU,YACjB,CAAC,MAAM,QAAQ,KAAK,GAEpB,IAAI,OAAO,WAAW,OAAO,EAAE;MAC1B,IAAI,aAAa,IAAI,GAAG,KAAK,MAAM,QAAQ,KAAK,GACrD,IAAI,OAAO,MAAM,KAAK,MAAM,WAAW,GAAG,EAAE,CAAC;MACxC,IAAI,WAAW,IAAI,GAAG,KAAK,SAAS,OAAO,UAAU,UAC1D,IAAI,OAAO,OAAO,YAChB,OAAO,QAAQ,KAAmB,CAAC,CAAC,KAAK,CAAC,MAAM,OAAO,CACrD,MACA,WAAW,GAAG,EAAE,CAClB,CAAC,CACH;MAEA,IAAI,OAAO;CAGf,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,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Q;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.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"author": "Vladimir Adamic",
|
|
6
6
|
"repository": {
|
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
"dist"
|
|
28
28
|
],
|
|
29
29
|
"peerDependencies": {
|
|
30
|
-
"@kopai/core": "^0.
|
|
31
|
-
"fastify": "^5.12.
|
|
30
|
+
"@kopai/core": "^0.13.0",
|
|
31
|
+
"fastify": "^5.12.7",
|
|
32
32
|
"zod": "^4.0.0"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
@@ -38,11 +38,11 @@
|
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
40
|
"ajv": "^8.20.0",
|
|
41
|
-
"fastify": "^5.12.
|
|
42
|
-
"tsdown": "^0.23.
|
|
43
|
-
"zod": "^4.6.
|
|
44
|
-
"@kopai/core": "0.
|
|
45
|
-
"@kopai/sqlite-datasource": "0.
|
|
41
|
+
"fastify": "^5.12.7",
|
|
42
|
+
"tsdown": "^0.23.1",
|
|
43
|
+
"zod": "^4.6.7",
|
|
44
|
+
"@kopai/core": "0.13.0",
|
|
45
|
+
"@kopai/sqlite-datasource": "0.14.0",
|
|
46
46
|
"@kopai/tsconfig": "0.2.0"
|
|
47
47
|
},
|
|
48
48
|
"scripts": {
|