@kopai/mcp 0.2.0 → 0.4.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 +302 -24
- package/dist/index.d.cts +73 -6
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +73 -6
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +298 -28
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { datasource, kopaiQuery } from "@kopai/core";
|
|
2
|
-
import { McpServer, jsonSchemaValidator } from "@modelcontextprotocol/server";
|
|
2
|
+
import { McpServer, McpServer as McpServer$1, fromJsonSchema, jsonSchemaValidator } from "@modelcontextprotocol/server";
|
|
3
3
|
import { FastifyPluginAsync, FastifyRequest } from "fastify";
|
|
4
4
|
type SchemaNode$1 = Record<string, unknown>;
|
|
5
5
|
/**
|
|
@@ -91,11 +91,19 @@ export declare const SIZE_REMEDIES: readonly ["Lower `limit`.", "Narrow the time
|
|
|
91
91
|
*/
|
|
92
92
|
export declare function overflowRemedies(query: kopaiQuery.KopaiQuery, limit: number, max: number): string[];
|
|
93
93
|
/**
|
|
94
|
-
* How a tool call ended. These
|
|
94
|
+
* How a tool call ended. These labels are the server's whole error
|
|
95
95
|
* vocabulary: they are the `error` code on a failed result, the `outcome` on
|
|
96
96
|
* the observer event, and the values a counter is grouped by.
|
|
97
|
+
*
|
|
98
|
+
* `not_found` and `forbidden` are produced only by host tools (see
|
|
99
|
+
* {@link HostTools}); the built-in tools never return them.
|
|
100
|
+
*
|
|
101
|
+
* `query_too_expensive` is a query the datasource stopped at a time, memory,
|
|
102
|
+
* row or byte limit, recognised from the thrown error; see
|
|
103
|
+
* `isResourceLimitError`.
|
|
97
104
|
*/
|
|
98
|
-
|
|
105
|
+
export declare const TOOL_CALL_OUTCOMES: readonly ["ok", "invalid_input", "result_too_large", "query_too_expensive", "upstream_error", "not_found", "forbidden"];
|
|
106
|
+
type ToolCallOutcome = (typeof TOOL_CALL_OUTCOMES)[number];
|
|
99
107
|
/**
|
|
100
108
|
* The one method this package calls on a logger.
|
|
101
109
|
*
|
|
@@ -123,6 +131,61 @@ interface ToolCallEvent {
|
|
|
123
131
|
rowCount?: number;
|
|
124
132
|
request: FastifyRequest;
|
|
125
133
|
}
|
|
134
|
+
/**
|
|
135
|
+
* Tools the host application adds to the same server as `query` and
|
|
136
|
+
* `metrics_discover`, for data only the host has.
|
|
137
|
+
*
|
|
138
|
+
* Host tools follow the built-ins' conventions:
|
|
139
|
+
*
|
|
140
|
+
* - Results are built with `okResult` and `errorResult`, so the
|
|
141
|
+
* error contract holds for every tool on the server.
|
|
142
|
+
* - The package observes them as it observes the built-ins: a throw becomes
|
|
143
|
+
* a logged `upstream_error` ("The tool call could not be completed."), or
|
|
144
|
+
* `query_too_expensive` when it is a query stopped at a resource limit, the
|
|
145
|
+
* outcome is read from the result's `error` code, and `onToolCall` fires
|
|
146
|
+
* once per call (without `rowCount`).
|
|
147
|
+
* A host tool never calls `onToolCall` itself. An error result without a
|
|
148
|
+
* known code is counted as `upstream_error` and logged.
|
|
149
|
+
* - `inputSchema` is built with `fromJsonSchema(schema, passThroughValidator)`
|
|
150
|
+
* and the handler validates, returning `invalid_input` with `issues`. The
|
|
151
|
+
* SDK's own validator rejects before dispatch, so the rejection would go
|
|
152
|
+
* uncounted and lose its `issues`; see `validator.ts`.
|
|
153
|
+
* - No `outputSchema`; registering one, or adding one through `update`,
|
|
154
|
+
* throws. The SDK checks it after the
|
|
155
|
+
* callback returns, so a mismatch would be counted `ok` while the caller
|
|
156
|
+
* got the SDK's bare error.
|
|
157
|
+
* - `McpServer` and `fromJsonSchema` are imported from `@kopai/mcp`, not from
|
|
158
|
+
* `@modelcontextprotocol/server`. They are the SDK's own, re-exported, at
|
|
159
|
+
* the version this package pins (2.3.1). `McpServer` has private fields, so
|
|
160
|
+
* a second copy of the SDK is a different, incompatible type.
|
|
161
|
+
*
|
|
162
|
+
* `register` is for tools. Prompts and resources registered through it are
|
|
163
|
+
* neither checked nor observed.
|
|
164
|
+
*/
|
|
165
|
+
interface HostTools {
|
|
166
|
+
/**
|
|
167
|
+
* Every name `register` may register. Checked once, at plugin registration:
|
|
168
|
+
* a name that is not an MCP tool name (`[A-Za-z0-9._-]`, 1 to 128
|
|
169
|
+
* characters), a duplicate, or a built-in name is refused with a
|
|
170
|
+
* `TypeError`. An empty list is allowed.
|
|
171
|
+
*/
|
|
172
|
+
names: string[];
|
|
173
|
+
/**
|
|
174
|
+
* Runs on each request's server, after the built-in tools are registered.
|
|
175
|
+
* Registering, or renaming a tool to, a name not in `names` throws, and so
|
|
176
|
+
* does renaming a tool onto a name already registered.
|
|
177
|
+
*
|
|
178
|
+
* Synchronous, because the SDK's server factory is; a returned promise
|
|
179
|
+
* fails the request. Do the I/O that decides
|
|
180
|
+
* which tools this caller gets in an async `preHandler`, attach the result
|
|
181
|
+
* to the request, and read it here. A tool not registered for a request is
|
|
182
|
+
* absent from that caller's `tools/list`.
|
|
183
|
+
*
|
|
184
|
+
* A throw fails the request; the server does not fall back to the built-in
|
|
185
|
+
* tools alone.
|
|
186
|
+
*/
|
|
187
|
+
register: (server: McpServer$1, request: FastifyRequest) => void;
|
|
188
|
+
}
|
|
126
189
|
interface McpRoutesOptions {
|
|
127
190
|
readTelemetryDatasource: datasource.ReadTelemetryDatasource;
|
|
128
191
|
/**
|
|
@@ -169,6 +232,8 @@ interface McpRoutesOptions {
|
|
|
169
232
|
logger?: ToolLogger;
|
|
170
233
|
/** Called once per completed tool call. Errors thrown here are swallowed. */
|
|
171
234
|
onToolCall?: (event: ToolCallEvent) => void;
|
|
235
|
+
/** Tools the host adds to the server. See {@link HostTools}. */
|
|
236
|
+
hostTools?: HostTools;
|
|
172
237
|
}
|
|
173
238
|
declare module "fastify" {
|
|
174
239
|
interface FastifyRequest {
|
|
@@ -188,7 +253,7 @@ interface ToolErrorPayload {
|
|
|
188
253
|
remedies?: string[];
|
|
189
254
|
}
|
|
190
255
|
/**
|
|
191
|
-
* The shape
|
|
256
|
+
* The shape every tool on the server returns, built-in or host. Deliberately not the MCP SDK's own result type
|
|
192
257
|
* — this stays a plain object so it can be asserted on in tests without a
|
|
193
258
|
* server.
|
|
194
259
|
*/
|
|
@@ -257,6 +322,8 @@ interface ToolRun {
|
|
|
257
322
|
}
|
|
258
323
|
export declare function runQueryTool(input: unknown, ctx: ToolContext): Promise<ToolRun>;
|
|
259
324
|
export declare function runMetricsDiscoverTool(ctx: ToolContext): Promise<ToolRun>;
|
|
325
|
+
/** The tools this package registers itself. A host tool may not reuse them. */
|
|
326
|
+
export declare const BUILT_IN_TOOL_NAMES: readonly ["query", "metrics_discover"];
|
|
260
327
|
interface RegisterToolsOptions extends ToolContext {
|
|
261
328
|
/**
|
|
262
329
|
* Called once per completed tool call, after the result is built and before
|
|
@@ -275,7 +342,7 @@ interface RegisterToolsOptions extends ToolContext {
|
|
|
275
342
|
* Every call reports to `opts.onToolCall` exactly once, including a call whose
|
|
276
343
|
* tool throws, which is returned as a structured error rather than rethrown.
|
|
277
344
|
*/
|
|
278
|
-
export declare function registerTools(server: McpServer, opts: RegisterToolsOptions): void;
|
|
345
|
+
export declare function registerTools(server: McpServer$1, opts: RegisterToolsOptions): void;
|
|
279
346
|
/**
|
|
280
347
|
* Mounts the MCP endpoint at `/mcp`, relative to wherever this plugin is
|
|
281
348
|
* registered.
|
|
@@ -334,5 +401,5 @@ export declare const METRICS_DISCOVER_TOOL_INPUT_SCHEMA: Record<string, unknown>
|
|
|
334
401
|
* broken" rather than as a bad argument.
|
|
335
402
|
*/
|
|
336
403
|
export declare const passThroughValidator: jsonSchemaValidator;
|
|
337
|
-
export type
|
|
404
|
+
export { type DescriptionOverride, type HostTools, type McpRoutesOptions, type McpServer, type RegisterToolsOptions, type ToolCallEvent, type ToolCallOutcome, type ToolContext, type ToolErrorCode, type ToolErrorPayload, type ToolIssue, type ToolResult, type ToolRun, fromJsonSchema };
|
|
338
405
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":["SchemaNode","McpServer","McpServer"],"sources":["../src/dedupe.ts","../src/limits.ts","../src/types.ts","../src/results.ts","../src/tools.ts","../src/register.ts","../src/routes.ts","../src/describe.ts","../src/schema.ts","../src/validator.ts"],"mappings":";;;KAoBKA,eAAa;;;;;;;;;;wBAkFF,OAAO,KAAKA,cAAY,kBAAcA;;;;;;;;;;;;;;;;;;;;;;;;qBC7EzC;;;;;;;;;;;;;;;;;;;;;;;;qBAyBA;;;;;;;;;;qBAWA;;qBAkEA;;;;;;;;;;;;;;;;;;wBA6EG,iBACd,OAAO,WAAW,YAClB,eACA;;;;;;;;;;;;;qBC/LW;KAUD,0BAA0B;;;;;;;;;UAUrB;EACf,MAAM,kBAAkB;;;;;;;;;;UAWT;EACf;EACA,SAAS;EACT;;EAEA;EACA,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAkCM;;;;;;;EAOf;;;;;;;;;;;;;;;EAeA,WAAW,QAAQC,aAAW,SAAS;;UAGxB;EACf,yBAAyB,WAAW;;;;;;EAMpC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+BA;;;;;EAKA,SAAS;;EAET,cAAc,OAAO;;EAErB,YAAY;;;YAQF;IACR;;;;KCtKQ,gBAAgB,QAAQ;UAEnB;EACf;EACA;;UAGe;EACf,OAAO;EACP;EACA,SAAS;EACT;;;;;;;KAQU;EACV;EACA,SAAS;IAAQ;IAAc;;EAC/B;;;;;;;;;;;;;;;;;;;;;;;wBAwBc,SAAS,mBAAmB;;;;;;;;;;wBAgB5B,YAAY,SAAS,mBAAmB;;;;;;wBAsBxC,iBAAiB,QAAQ,cAAc;UCnEtC;EACf,yBAAyB,WAAW;;EAEpC;;EAEA,SAAS;;;;;;;UAQM;EACf,QAAQ;EACR,SAAS;EACT;;wBAwHoB,aACpB,gBACA,KAAK,cACJ,QAAQ;wBA4LW,uBACpB,KAAK,cACJ,QAAQ;;qBCvRE;UAEI,6BAA6B;;;;;EAK5C,cAAc;IACZ;IACA,SAAS;IACT;IACA;;;;;;;;;wBAoEY,cACd,QAAQC,aACR,MAAM;;;;;;;;qBCjFK,WAAW,mBAAmB;KCnDtC,aAAa;UAED;;WAEN;;WAEA;WACA;;wBAGK,qBACd,gBACA,sBACA,oBACA,2BACC;;;;;wBAwBa,kBACd,KAAK,YACL,oBAAoB;EACjB,UAAU;EAAY,SAAS;;;qBCpBvB,+BAA6B;qBAE7B,yBAAyB;;;;;qBAQzB,oCAAoC;;;;;;;;;;;;;;;;;;;;;;;;;qBCtBpC,sBAAsB"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { kopaiQuery, kopaiQueryCompiler } from "@kopai/core";
|
|
2
|
-
import { McpServer, createMcpHandler, fromJsonSchema } from "@modelcontextprotocol/server";
|
|
2
|
+
import { McpServer, createMcpHandler, fromJsonSchema, fromJsonSchema as fromJsonSchema$1 } from "@modelcontextprotocol/server";
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
import { hostHeaderValidation, originValidation } from "@modelcontextprotocol/fastify";
|
|
5
5
|
import { toNodeHandler } from "@modelcontextprotocol/node";
|
|
@@ -155,6 +155,57 @@ const MAX_RESULT_CHARACTERS = 15e4;
|
|
|
155
155
|
* the honest answer is what remains possible without it.
|
|
156
156
|
*/
|
|
157
157
|
const DISCOVERY_SIZE_REMEDIES = ["Query a metric by name with the `query` tool — discovery is not a prerequisite for it.", "Ask an operator to reduce what this deployment ingests: this workspace holds more metrics than one response can carry."];
|
|
158
|
+
/**
|
|
159
|
+
* ClickHouse error codes for a query stopped at a resource limit: 158
|
|
160
|
+
* TOO_MANY_ROWS, 159 TIMEOUT_EXCEEDED, 160 TOO_SLOW (the estimated time
|
|
161
|
+
* already exceeds `max_execution_time`), 241 MEMORY_LIMIT_EXCEEDED, 307
|
|
162
|
+
* TOO_MANY_BYTES, 396 TOO_MANY_ROWS_OR_BYTES.
|
|
163
|
+
*
|
|
164
|
+
* WHY ClickHouse codes in a package that knows no backend: the datasource
|
|
165
|
+
* rethrows `@clickhouse/client`'s error as it is, so its `code` is the only
|
|
166
|
+
* signal that reaches this layer. The SQLite datasource sets no such limits.
|
|
167
|
+
* Mirrored in `@kopai/api`'s error handler, which cannot import from here.
|
|
168
|
+
*
|
|
169
|
+
* WHY not `@clickhouse/client`'s own "Timeout error.": it is a socket timeout,
|
|
170
|
+
* and fires as readily for a server that stopped answering as for a heavy
|
|
171
|
+
* query. A heavy query is expected to meet the server's `max_execution_time`
|
|
172
|
+
* first, set by the host below the client's `request_timeout`, and fail with
|
|
173
|
+
* 159; a client timeout is then an outage, and stays one.
|
|
174
|
+
*/
|
|
175
|
+
const RESOURCE_LIMIT_CODES = /* @__PURE__ */ new Set([
|
|
176
|
+
"158",
|
|
177
|
+
"159",
|
|
178
|
+
"160",
|
|
179
|
+
"241",
|
|
180
|
+
"307",
|
|
181
|
+
"396"
|
|
182
|
+
]);
|
|
183
|
+
/**
|
|
184
|
+
* Whether a throw is a query stopped at a resource limit, which the caller
|
|
185
|
+
* can get past by asking for less. Anything else stays an upstream error.
|
|
186
|
+
*
|
|
187
|
+
* A 241 for the server as a whole ("(total) memory limit exceeded") is
|
|
188
|
+
* excluded: other queries or ingest used the memory, so asking for less does
|
|
189
|
+
* not help.
|
|
190
|
+
*/
|
|
191
|
+
function isResourceLimitError(error) {
|
|
192
|
+
if (!(error instanceof Error)) return false;
|
|
193
|
+
const { code } = error;
|
|
194
|
+
if (typeof code !== "string" || !RESOURCE_LIMIT_CODES.has(code)) return false;
|
|
195
|
+
return !(code === "241" && error.message.includes("(total)"));
|
|
196
|
+
}
|
|
197
|
+
/** Remedies for a query stopped at a resource limit. */
|
|
198
|
+
const RESOURCE_LIMIT_REMEDIES = [
|
|
199
|
+
"Narrow the time window.",
|
|
200
|
+
"Add filters so fewer rows are read: `service.name` or another attribute, and for metrics a single `MetricName`.",
|
|
201
|
+
"For metrics, INCREASE, RATE and HISTOGRAM_QUANTILE read every data point in the window. When an exact increase or quantile is not needed, SUM, COUNT or MAX cost far less: on `Value` for Gauge and Sum metrics, on `Count` or `Sum` for Histogram metrics."
|
|
202
|
+
];
|
|
203
|
+
/**
|
|
204
|
+
* Remedies for a discovery listing stopped at a resource limit. Its own list
|
|
205
|
+
* for the reason {@link DISCOVERY_SIZE_REMEDIES} is: the tool takes no
|
|
206
|
+
* arguments, so there is no window or filter to offer.
|
|
207
|
+
*/
|
|
208
|
+
const DISCOVERY_RESOURCE_LIMIT_REMEDIES = ["Query a metric by name with the `query` tool — discovery is not a prerequisite for it.", "Try again shortly: the listing may have run while this deployment was busy."];
|
|
158
209
|
/** Remedies offered when a result is too large once serialized. */
|
|
159
210
|
const SIZE_REMEDIES = [
|
|
160
211
|
"Lower `limit`.",
|
|
@@ -421,9 +472,29 @@ function tooLarge(message, remedies) {
|
|
|
421
472
|
};
|
|
422
473
|
}
|
|
423
474
|
/**
|
|
475
|
+
* A query the datasource stopped at a resource limit. Exported for the host
|
|
476
|
+
* tools' throw handler in `register.ts`.
|
|
477
|
+
*/
|
|
478
|
+
function tooExpensive(message, remedies) {
|
|
479
|
+
return {
|
|
480
|
+
result: errorResult({
|
|
481
|
+
error: "query_too_expensive",
|
|
482
|
+
message,
|
|
483
|
+
remedies: [...remedies]
|
|
484
|
+
}),
|
|
485
|
+
outcome: "query_too_expensive"
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
424
489
|
* Maps a thrown error onto an outcome, mirroring the REST error handler:
|
|
425
|
-
* a recognised validation error surfaces its own message,
|
|
426
|
-
*
|
|
490
|
+
* a recognised validation error surfaces its own message, a resource limit
|
|
491
|
+
* surfaces what to ask for instead, and anything unrecognised surfaces a
|
|
492
|
+
* generic string with the detail written to the log.
|
|
493
|
+
*
|
|
494
|
+
* WHY a resource limit gets its own outcome: it is the failure a caller can
|
|
495
|
+
* get past, by asking for less, and a generic "could not be completed" gave
|
|
496
|
+
* it nothing to change. Directory review fails a connector whose errors carry
|
|
497
|
+
* no detail.
|
|
427
498
|
*
|
|
428
499
|
* WHY the log matters as much as the result: "The query could not be
|
|
429
500
|
* completed." is the whole of what a model can act on, and it is also the
|
|
@@ -434,11 +505,17 @@ function tooLarge(message, remedies) {
|
|
|
434
505
|
* same thing at the other entry point.
|
|
435
506
|
*
|
|
436
507
|
* A validation error is not logged: it is the caller's mistake, it is reported
|
|
437
|
-
* back in full, and logging every malformed query would bury the outages.
|
|
508
|
+
* back in full, and logging every malformed query would bury the outages. A
|
|
509
|
+
* resource limit is logged: it is the caller's query, but which queries the
|
|
510
|
+
* datasource cannot afford is for whoever runs it to know.
|
|
511
|
+
*
|
|
512
|
+
* `limitRemedies` is for `metrics_discover`, which takes no arguments and so
|
|
513
|
+
* cannot narrow a window.
|
|
438
514
|
*/
|
|
439
|
-
function fromThrown(error, logger) {
|
|
515
|
+
function fromThrown(error, logger, limitRemedies = RESOURCE_LIMIT_REMEDIES) {
|
|
440
516
|
if (error instanceof kopaiQueryCompiler.KopaiQueryValidationError) return invalidInput(error.message);
|
|
441
517
|
logger?.error(error, "MCP tool call failed");
|
|
518
|
+
if (isResourceLimitError(error)) return tooExpensive("The query was stopped at this deployment's limit on query time, memory or rows read.", limitRemedies);
|
|
442
519
|
return {
|
|
443
520
|
result: errorResult({
|
|
444
521
|
error: "upstream_error",
|
|
@@ -563,7 +640,7 @@ async function runMetricsDiscoverTool(ctx) {
|
|
|
563
640
|
try {
|
|
564
641
|
full = await ctx.readTelemetryDatasource.discoverMetrics({ requestContext: ctx.requestContext });
|
|
565
642
|
} catch (error) {
|
|
566
|
-
return fromThrown(error, ctx.logger);
|
|
643
|
+
return fromThrown(error, ctx.logger, DISCOVERY_RESOURCE_LIMIT_REMEDIES);
|
|
567
644
|
}
|
|
568
645
|
let serialized = "";
|
|
569
646
|
for (const stage of degradations(full)) {
|
|
@@ -576,6 +653,28 @@ async function runMetricsDiscoverTool(ctx) {
|
|
|
576
653
|
}
|
|
577
654
|
return tooLarge(`The listing of ${full.metrics.length.toLocaleString("en-US")} metrics serialized to ${serialized.length.toLocaleString("en-US")} characters even without their attributes, above the ${MAX_RESULT_CHARACTERS.toLocaleString("en-US")} the host will accept.`, DISCOVERY_SIZE_REMEDIES);
|
|
578
655
|
}
|
|
656
|
+
// src/types.ts
|
|
657
|
+
/**
|
|
658
|
+
* How a tool call ended. These labels are the server's whole error
|
|
659
|
+
* vocabulary: they are the `error` code on a failed result, the `outcome` on
|
|
660
|
+
* the observer event, and the values a counter is grouped by.
|
|
661
|
+
*
|
|
662
|
+
* `not_found` and `forbidden` are produced only by host tools (see
|
|
663
|
+
* {@link HostTools}); the built-in tools never return them.
|
|
664
|
+
*
|
|
665
|
+
* `query_too_expensive` is a query the datasource stopped at a time, memory,
|
|
666
|
+
* row or byte limit, recognised from the thrown error; see
|
|
667
|
+
* `isResourceLimitError`.
|
|
668
|
+
*/
|
|
669
|
+
const TOOL_CALL_OUTCOMES = [
|
|
670
|
+
"ok",
|
|
671
|
+
"invalid_input",
|
|
672
|
+
"result_too_large",
|
|
673
|
+
"query_too_expensive",
|
|
674
|
+
"upstream_error",
|
|
675
|
+
"not_found",
|
|
676
|
+
"forbidden"
|
|
677
|
+
];
|
|
579
678
|
// src/validator.ts
|
|
580
679
|
/**
|
|
581
680
|
* A validator provider that accepts everything, so that the tool handler is
|
|
@@ -642,13 +741,22 @@ const METRICS_DISCOVER_DESCRIPTION = [
|
|
|
642
741
|
"Takes no arguments.",
|
|
643
742
|
`A listing above ${MAX_RESULT_CHARACTERS.toLocaleString("en-US")} characters is returned without its attribute values, or without its attributes, and the response names what was omitted.`
|
|
644
743
|
].join(" ");
|
|
744
|
+
/** The tools this package registers itself. A host tool may not reuse them. */
|
|
745
|
+
const BUILT_IN_TOOL_NAMES = ["query", "metrics_discover"];
|
|
645
746
|
/**
|
|
646
|
-
*
|
|
747
|
+
* Returns the function that runs one tool call and reports it, whatever
|
|
748
|
+
* happens. Shared by the built-in and the host tools, so every tool on the
|
|
749
|
+
* server reaches `onToolCall` through this one place.
|
|
647
750
|
*
|
|
648
|
-
*
|
|
649
|
-
*
|
|
751
|
+
* WHY the catch: a throw out of a tool used to skip `observe` altogether, so
|
|
752
|
+
* the host's counter lost exactly the calls most worth seeing — and the SDK
|
|
753
|
+
* turned it into a bare message with no `structuredContent`, which is the
|
|
754
|
+
* one error shape a page cannot read. Nothing in the tools is expected to
|
|
755
|
+
* throw; that is the reason to handle it here rather than to assume it, and
|
|
756
|
+
* converting it gives an unexpected failure the same contract as an expected
|
|
757
|
+
* one: a structured payload, a logged cause, and one observer event.
|
|
650
758
|
*/
|
|
651
|
-
function
|
|
759
|
+
function observedCall(opts) {
|
|
652
760
|
const observe = (tool, startedAt, outcome, rowCount) => {
|
|
653
761
|
if (!opts.onToolCall) return;
|
|
654
762
|
try {
|
|
@@ -656,22 +764,11 @@ function registerTools(server, opts) {
|
|
|
656
764
|
tool,
|
|
657
765
|
outcome,
|
|
658
766
|
durationMs: Date.now() - startedAt,
|
|
659
|
-
rowCount
|
|
767
|
+
...rowCount !== void 0 ? { rowCount } : {}
|
|
660
768
|
});
|
|
661
769
|
} catch {}
|
|
662
770
|
};
|
|
663
|
-
|
|
664
|
-
* Runs one tool call and reports it, whatever happens.
|
|
665
|
-
*
|
|
666
|
-
* WHY the catch: a throw out of a tool used to skip `observe` altogether, so
|
|
667
|
-
* the host's counter lost exactly the calls most worth seeing — and the SDK
|
|
668
|
-
* turned it into a bare message with no `structuredContent`, which is the
|
|
669
|
-
* one error shape a page cannot read. Nothing in the tools is expected to
|
|
670
|
-
* throw; that is the reason to handle it here rather than to assume it, and
|
|
671
|
-
* converting it gives an unexpected failure the same contract as an expected
|
|
672
|
-
* one: a structured payload, a logged cause, and one observer event.
|
|
673
|
-
*/
|
|
674
|
-
const call = async (tool, execute) => {
|
|
771
|
+
return async (tool, execute) => {
|
|
675
772
|
const startedAt = Date.now();
|
|
676
773
|
let run;
|
|
677
774
|
try {
|
|
@@ -682,10 +779,19 @@ function registerTools(server, opts) {
|
|
|
682
779
|
observe(tool, startedAt, run.outcome, run.rowCount);
|
|
683
780
|
return run.result;
|
|
684
781
|
};
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* Registers the `query` and `metrics_discover` tools on `server`.
|
|
785
|
+
*
|
|
786
|
+
* Every call reports to `opts.onToolCall` exactly once, including a call whose
|
|
787
|
+
* tool throws, which is returned as a structured error rather than rethrown.
|
|
788
|
+
*/
|
|
789
|
+
function registerTools(server, opts) {
|
|
790
|
+
const call = observedCall(opts);
|
|
685
791
|
server.registerTool("query", {
|
|
686
792
|
title: "Query telemetry",
|
|
687
793
|
description: QUERY_DESCRIPTION,
|
|
688
|
-
inputSchema: fromJsonSchema(QUERY_TOOL_INPUT_SCHEMA, passThroughValidator),
|
|
794
|
+
inputSchema: fromJsonSchema$1(QUERY_TOOL_INPUT_SCHEMA, passThroughValidator),
|
|
689
795
|
annotations: {
|
|
690
796
|
...READ_ONLY,
|
|
691
797
|
title: "Query telemetry"
|
|
@@ -694,16 +800,165 @@ function registerTools(server, opts) {
|
|
|
694
800
|
server.registerTool("metrics_discover", {
|
|
695
801
|
title: "Discover metrics",
|
|
696
802
|
description: METRICS_DISCOVER_DESCRIPTION,
|
|
697
|
-
inputSchema: fromJsonSchema(METRICS_DISCOVER_TOOL_INPUT_SCHEMA, passThroughValidator),
|
|
803
|
+
inputSchema: fromJsonSchema$1(METRICS_DISCOVER_TOOL_INPUT_SCHEMA, passThroughValidator),
|
|
698
804
|
annotations: {
|
|
699
805
|
...READ_ONLY,
|
|
700
806
|
title: "Discover metrics"
|
|
701
807
|
}
|
|
702
808
|
}, async () => call("metrics_discover", () => runMetricsDiscoverTool(opts)));
|
|
703
809
|
}
|
|
810
|
+
const ERROR_CODES = new Set(TOOL_CALL_OUTCOMES.filter((outcome) => outcome !== "ok"));
|
|
811
|
+
const isRecord = (value) => typeof value === "object" && value !== null;
|
|
812
|
+
/**
|
|
813
|
+
* Reads a host tool's outcome from the result it returned.
|
|
814
|
+
*
|
|
815
|
+
* WHY reading is safe here, when `ToolRun` returns the outcome rather than
|
|
816
|
+
* inferring it: `errorResult` is the one builder of an error result, and it
|
|
817
|
+
* always writes the code. A hand-built error result has no code to read; it
|
|
818
|
+
* is counted as `upstream_error`, the same label an unexpected throw gets, and
|
|
819
|
+
* logged so the tool can be fixed. It is not thrown: the caller already has
|
|
820
|
+
* an answer, and the tool's own text is more use to it than ours.
|
|
821
|
+
*/
|
|
822
|
+
function hostOutcome(tool, result, logger) {
|
|
823
|
+
if (!isRecord(result) || result.isError !== true) return "ok";
|
|
824
|
+
const code = isRecord(result.structuredContent) ? result.structuredContent.error : void 0;
|
|
825
|
+
if (typeof code === "string" && ERROR_CODES.has(code)) return code;
|
|
826
|
+
logger?.error({ tool }, "MCP host tool returned an error result without a known error code");
|
|
827
|
+
return "upstream_error";
|
|
828
|
+
}
|
|
829
|
+
/**
|
|
830
|
+
* A host tool's throw, converted as `fromThrown` converts a built-in's, with
|
|
831
|
+
* two differences: the generic message names no query, since a host tool need
|
|
832
|
+
* not run one, and the log line names the tool.
|
|
833
|
+
*
|
|
834
|
+
* A resource limit is classified here too: a host tool that reads telemetry
|
|
835
|
+
* (a backtest, say) lets its query's throw through, and would otherwise
|
|
836
|
+
* report a limit the caller can get past as a generic failure.
|
|
837
|
+
*/
|
|
838
|
+
function thrownByHostTool(tool, error, logger) {
|
|
839
|
+
logger?.error(error, `MCP host tool "${tool}" failed`);
|
|
840
|
+
if (isResourceLimitError(error)) return tooExpensive("The query behind this tool call was stopped at this deployment's limit on query time, memory or rows read.", RESOURCE_LIMIT_REMEDIES);
|
|
841
|
+
return {
|
|
842
|
+
result: errorResult({
|
|
843
|
+
error: "upstream_error",
|
|
844
|
+
message: "The tool call could not be completed."
|
|
845
|
+
}),
|
|
846
|
+
outcome: "upstream_error"
|
|
847
|
+
};
|
|
848
|
+
}
|
|
849
|
+
/**
|
|
850
|
+
* Runs the host's `register` on `server`, with `registerTool` guarded and
|
|
851
|
+
* observed.
|
|
852
|
+
*
|
|
853
|
+
* The guard is installed on this one per-request instance, through the SDK's
|
|
854
|
+
* public API only. It refuses a name not in `names`, so the check made at
|
|
855
|
+
* boot cannot be bypassed through `registerTool` or `update` — a host that
|
|
856
|
+
* reaches past them, by writing `handle.executor` or calling the prototype's
|
|
857
|
+
* `registerTool`, is not guarded, and is not meant to be. It wraps the
|
|
858
|
+
* returned handle's `update` as well: `update({ name })` renames a registered tool, and `update({ callback
|
|
859
|
+
* })` swaps its callback, either of which would otherwise slip past the guard.
|
|
860
|
+
* `remove()` is `update({ name: null })` in the SDK and passes.
|
|
861
|
+
*
|
|
862
|
+
* A refusal throws, and so does anything else `register` throws. Both fail the
|
|
863
|
+
* request; see {@link HostTools}.
|
|
864
|
+
*/
|
|
865
|
+
function registerHostTools(server, opts) {
|
|
866
|
+
const call = observedCall(opts);
|
|
867
|
+
const assertDeclared = (name) => {
|
|
868
|
+
if (opts.names.has(name)) return;
|
|
869
|
+
const declared = [...opts.names].map((n) => `"${n}"`).join(", ");
|
|
870
|
+
throw new TypeError(`Host tool "${name}" is not in hostTools.names (${declared || "none declared"}). Declare every name register may use.`);
|
|
871
|
+
};
|
|
872
|
+
const registerTool = server.registerTool.bind(server);
|
|
873
|
+
const wrapped = /* @__PURE__ */ new WeakMap();
|
|
874
|
+
const inUse = /* @__PURE__ */ new Set();
|
|
875
|
+
const guarded = (name, config, callback) => {
|
|
876
|
+
assertDeclared(name);
|
|
877
|
+
const refuseOutputSchema = (value, tool) => {
|
|
878
|
+
if (value === void 0) return;
|
|
879
|
+
throw new TypeError(`Host tool "${tool}" declares an outputSchema; host tools may not.`);
|
|
880
|
+
};
|
|
881
|
+
refuseOutputSchema(isRecord(config) ? config.outputSchema : void 0, name);
|
|
882
|
+
let current = name;
|
|
883
|
+
const observed = (inner) => {
|
|
884
|
+
const outer = (...args) => call(current, async () => {
|
|
885
|
+
let result;
|
|
886
|
+
try {
|
|
887
|
+
result = await inner(...args);
|
|
888
|
+
} catch (error) {
|
|
889
|
+
return thrownByHostTool(current, error, opts.logger);
|
|
890
|
+
}
|
|
891
|
+
return {
|
|
892
|
+
result,
|
|
893
|
+
outcome: hostOutcome(current, result, opts.logger)
|
|
894
|
+
};
|
|
895
|
+
});
|
|
896
|
+
wrapped.set(outer, inner);
|
|
897
|
+
return outer;
|
|
898
|
+
};
|
|
899
|
+
const handle = registerTool(name, config, observed(callback));
|
|
900
|
+
inUse.add(name);
|
|
901
|
+
let raw = callback;
|
|
902
|
+
Object.defineProperty(handle, "handler", {
|
|
903
|
+
get: () => raw,
|
|
904
|
+
set: (value) => {
|
|
905
|
+
raw = wrapped.get(value) ?? value;
|
|
906
|
+
},
|
|
907
|
+
enumerable: true,
|
|
908
|
+
configurable: true
|
|
909
|
+
});
|
|
910
|
+
const update = handle.update;
|
|
911
|
+
handle.update = (updates) => {
|
|
912
|
+
refuseOutputSchema(updates.outputSchema, current);
|
|
913
|
+
const renamed = updates.name !== void 0 && updates.name !== current ? updates.name : void 0;
|
|
914
|
+
if (typeof renamed === "string") {
|
|
915
|
+
assertDeclared(renamed);
|
|
916
|
+
if (inUse.has(renamed)) throw new TypeError(`Host tool "${current}" cannot be renamed to "${renamed}", which is already registered.`);
|
|
917
|
+
}
|
|
918
|
+
update(updates.callback === void 0 ? updates : {
|
|
919
|
+
...updates,
|
|
920
|
+
callback: observed(updates.callback)
|
|
921
|
+
});
|
|
922
|
+
if (renamed !== void 0) {
|
|
923
|
+
inUse.delete(current);
|
|
924
|
+
if (renamed !== null) {
|
|
925
|
+
inUse.add(renamed);
|
|
926
|
+
current = renamed;
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
};
|
|
930
|
+
return handle;
|
|
931
|
+
};
|
|
932
|
+
server.registerTool = guarded;
|
|
933
|
+
const returned = opts.register(server);
|
|
934
|
+
if (returned instanceof Promise) {
|
|
935
|
+
returned.catch(() => {});
|
|
936
|
+
throw new TypeError("hostTools.register returned a promise; it must be synchronous. Do the I/O in a preHandler and read its result from the request.");
|
|
937
|
+
}
|
|
938
|
+
}
|
|
704
939
|
// src/routes.ts
|
|
705
940
|
const SERVER_NAME = "kopai";
|
|
706
941
|
const SERVER_VERSION = "0.0.0";
|
|
942
|
+
const TOOL_NAME = /^[A-Za-z0-9._-]{1,128}$/;
|
|
943
|
+
/**
|
|
944
|
+
* Checks `hostTools` once, at registration, and returns its names as a set.
|
|
945
|
+
*
|
|
946
|
+
* Refused rather than absorbed, for the reason `allowedOriginHostnames` is: a
|
|
947
|
+
* wrong shape would otherwise fail on every request, and a name colliding
|
|
948
|
+
* with a built-in would fail only when a caller who may use it arrives.
|
|
949
|
+
*/
|
|
950
|
+
function checkedHostToolNames(hostTools) {
|
|
951
|
+
if (typeof hostTools !== "object" || hostTools === null || typeof hostTools.register !== "function" || !Array.isArray(hostTools.names) || hostTools.names.some((name) => typeof name !== "string")) throw new TypeError("hostTools must be { names: string[]; register: (server, request) => void }, e.g. { names: [\"alert_get\"], register }. Omit it to add no tools.");
|
|
952
|
+
const names = /* @__PURE__ */ new Set();
|
|
953
|
+
const builtIns = BUILT_IN_TOOL_NAMES;
|
|
954
|
+
for (const name of hostTools.names) {
|
|
955
|
+
if (!TOOL_NAME.test(name)) throw new TypeError(`hostTools.names: "${name}" is not an MCP tool name (1 to 128 of A-Z, a-z, 0-9, ".", "_", "-").`);
|
|
956
|
+
if (builtIns.includes(name)) throw new TypeError(`hostTools.names: "${name}" is the name of a built-in tool.`);
|
|
957
|
+
if (names.has(name)) throw new TypeError(`hostTools.names: "${name}" appears more than once.`);
|
|
958
|
+
names.add(name);
|
|
959
|
+
}
|
|
960
|
+
return names;
|
|
961
|
+
}
|
|
707
962
|
/**
|
|
708
963
|
* Mounts the MCP endpoint at `/mcp`, relative to wherever this plugin is
|
|
709
964
|
* registered.
|
|
@@ -717,6 +972,10 @@ const mcpRoutes = async function mcpRoutes(fastify, opts) {
|
|
|
717
972
|
if (!Array.isArray(opts.allowedOriginHostnames) || opts.allowedOriginHostnames.some((name) => typeof name !== "string")) throw new TypeError("allowedOriginHostnames must be an array of hostname strings, e.g. [\"localhost\", \"127.0.0.1\"]. Omit it to mount no origin validation.");
|
|
718
973
|
fastify.addHook("onRequest", originValidation(opts.allowedOriginHostnames));
|
|
719
974
|
}
|
|
975
|
+
const hostTools = opts.hostTools === void 0 ? void 0 : {
|
|
976
|
+
names: checkedHostToolNames(opts.hostTools),
|
|
977
|
+
register: opts.hostTools.register
|
|
978
|
+
};
|
|
720
979
|
const handleMcp = async (request, reply) => {
|
|
721
980
|
if (request.method !== "POST") reply.raw.setHeader("Allow", "POST");
|
|
722
981
|
const handler = createMcpHandler(() => {
|
|
@@ -724,7 +983,7 @@ const mcpRoutes = async function mcpRoutes(fastify, opts) {
|
|
|
724
983
|
name: SERVER_NAME,
|
|
725
984
|
version: SERVER_VERSION
|
|
726
985
|
});
|
|
727
|
-
|
|
986
|
+
const toolOptions = {
|
|
728
987
|
readTelemetryDatasource: opts.readTelemetryDatasource,
|
|
729
988
|
requestContext: request.requestContext,
|
|
730
989
|
logger: opts.logger ?? request.log,
|
|
@@ -732,7 +991,18 @@ const mcpRoutes = async function mcpRoutes(fastify, opts) {
|
|
|
732
991
|
...event,
|
|
733
992
|
request
|
|
734
993
|
}) : void 0
|
|
735
|
-
}
|
|
994
|
+
};
|
|
995
|
+
registerTools(server, toolOptions);
|
|
996
|
+
if (hostTools !== void 0) try {
|
|
997
|
+
registerHostTools(server, {
|
|
998
|
+
...toolOptions,
|
|
999
|
+
names: hostTools.names,
|
|
1000
|
+
register: (s) => hostTools.register(s, request)
|
|
1001
|
+
});
|
|
1002
|
+
} catch (error) {
|
|
1003
|
+
toolOptions.logger?.error(error, "MCP hostTools.register failed");
|
|
1004
|
+
throw error;
|
|
1005
|
+
}
|
|
736
1006
|
return server;
|
|
737
1007
|
});
|
|
738
1008
|
reply.hijack();
|
|
@@ -754,6 +1024,6 @@ const mcpRoutes = async function mcpRoutes(fastify, opts) {
|
|
|
754
1024
|
handler: handleMcp
|
|
755
1025
|
});
|
|
756
1026
|
};
|
|
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 };
|
|
1027
|
+
export { BUILT_IN_TOOL_NAMES, DESCRIPTION_OVERRIDES_APPLIED, DISCOVERY_SIZE_REMEDIES, LIMITS, MAX_RESULT_CHARACTERS, METRICS_DISCOVER_TOOL_INPUT_SCHEMA, QUERY_TOOL_INPUT_SCHEMA, SIZE_REMEDIES, TOOL_CALL_OUTCOMES, applyDescriptions, dedupe, descriptionOverrides, errorResult, fromJsonSchema, mcpRoutes, okResult, overflowRemedies, passThroughValidator, prefixIssuePaths, registerTools, runMetricsDiscoverTool, runQueryTool };
|
|
758
1028
|
|
|
759
1029
|
//# sourceMappingURL=index.mjs.map
|