@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.cjs
CHANGED
|
@@ -156,6 +156,57 @@ const MAX_RESULT_CHARACTERS = 15e4;
|
|
|
156
156
|
* the honest answer is what remains possible without it.
|
|
157
157
|
*/
|
|
158
158
|
const DISCOVERY_SIZE_REMEDIES = ["Query a metric by name with the `query` tool — discovery is not a prerequisite for it.", "Ask an operator to reduce what this deployment ingests: this workspace holds more metrics than one response can carry."];
|
|
159
|
+
/**
|
|
160
|
+
* ClickHouse error codes for a query stopped at a resource limit: 158
|
|
161
|
+
* TOO_MANY_ROWS, 159 TIMEOUT_EXCEEDED, 160 TOO_SLOW (the estimated time
|
|
162
|
+
* already exceeds `max_execution_time`), 241 MEMORY_LIMIT_EXCEEDED, 307
|
|
163
|
+
* TOO_MANY_BYTES, 396 TOO_MANY_ROWS_OR_BYTES.
|
|
164
|
+
*
|
|
165
|
+
* WHY ClickHouse codes in a package that knows no backend: the datasource
|
|
166
|
+
* rethrows `@clickhouse/client`'s error as it is, so its `code` is the only
|
|
167
|
+
* signal that reaches this layer. The SQLite datasource sets no such limits.
|
|
168
|
+
* Mirrored in `@kopai/api`'s error handler, which cannot import from here.
|
|
169
|
+
*
|
|
170
|
+
* WHY not `@clickhouse/client`'s own "Timeout error.": it is a socket timeout,
|
|
171
|
+
* and fires as readily for a server that stopped answering as for a heavy
|
|
172
|
+
* query. A heavy query is expected to meet the server's `max_execution_time`
|
|
173
|
+
* first, set by the host below the client's `request_timeout`, and fail with
|
|
174
|
+
* 159; a client timeout is then an outage, and stays one.
|
|
175
|
+
*/
|
|
176
|
+
const RESOURCE_LIMIT_CODES = /* @__PURE__ */ new Set([
|
|
177
|
+
"158",
|
|
178
|
+
"159",
|
|
179
|
+
"160",
|
|
180
|
+
"241",
|
|
181
|
+
"307",
|
|
182
|
+
"396"
|
|
183
|
+
]);
|
|
184
|
+
/**
|
|
185
|
+
* Whether a throw is a query stopped at a resource limit, which the caller
|
|
186
|
+
* can get past by asking for less. Anything else stays an upstream error.
|
|
187
|
+
*
|
|
188
|
+
* A 241 for the server as a whole ("(total) memory limit exceeded") is
|
|
189
|
+
* excluded: other queries or ingest used the memory, so asking for less does
|
|
190
|
+
* not help.
|
|
191
|
+
*/
|
|
192
|
+
function isResourceLimitError(error) {
|
|
193
|
+
if (!(error instanceof Error)) return false;
|
|
194
|
+
const { code } = error;
|
|
195
|
+
if (typeof code !== "string" || !RESOURCE_LIMIT_CODES.has(code)) return false;
|
|
196
|
+
return !(code === "241" && error.message.includes("(total)"));
|
|
197
|
+
}
|
|
198
|
+
/** Remedies for a query stopped at a resource limit. */
|
|
199
|
+
const RESOURCE_LIMIT_REMEDIES = [
|
|
200
|
+
"Narrow the time window.",
|
|
201
|
+
"Add filters so fewer rows are read: `service.name` or another attribute, and for metrics a single `MetricName`.",
|
|
202
|
+
"For metrics, INCREASE, RATE and HISTOGRAM_QUANTILE read every data point in the window. When an exact increase or quantile is not needed, SUM, COUNT or MAX cost far less: on `Value` for Gauge and Sum metrics, on `Count` or `Sum` for Histogram metrics."
|
|
203
|
+
];
|
|
204
|
+
/**
|
|
205
|
+
* Remedies for a discovery listing stopped at a resource limit. Its own list
|
|
206
|
+
* for the reason {@link DISCOVERY_SIZE_REMEDIES} is: the tool takes no
|
|
207
|
+
* arguments, so there is no window or filter to offer.
|
|
208
|
+
*/
|
|
209
|
+
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."];
|
|
159
210
|
/** Remedies offered when a result is too large once serialized. */
|
|
160
211
|
const SIZE_REMEDIES = [
|
|
161
212
|
"Lower `limit`.",
|
|
@@ -422,9 +473,29 @@ function tooLarge(message, remedies) {
|
|
|
422
473
|
};
|
|
423
474
|
}
|
|
424
475
|
/**
|
|
476
|
+
* A query the datasource stopped at a resource limit. Exported for the host
|
|
477
|
+
* tools' throw handler in `register.ts`.
|
|
478
|
+
*/
|
|
479
|
+
function tooExpensive(message, remedies) {
|
|
480
|
+
return {
|
|
481
|
+
result: errorResult({
|
|
482
|
+
error: "query_too_expensive",
|
|
483
|
+
message,
|
|
484
|
+
remedies: [...remedies]
|
|
485
|
+
}),
|
|
486
|
+
outcome: "query_too_expensive"
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
425
490
|
* Maps a thrown error onto an outcome, mirroring the REST error handler:
|
|
426
|
-
* a recognised validation error surfaces its own message,
|
|
427
|
-
*
|
|
491
|
+
* a recognised validation error surfaces its own message, a resource limit
|
|
492
|
+
* surfaces what to ask for instead, and anything unrecognised surfaces a
|
|
493
|
+
* generic string with the detail written to the log.
|
|
494
|
+
*
|
|
495
|
+
* WHY a resource limit gets its own outcome: it is the failure a caller can
|
|
496
|
+
* get past, by asking for less, and a generic "could not be completed" gave
|
|
497
|
+
* it nothing to change. Directory review fails a connector whose errors carry
|
|
498
|
+
* no detail.
|
|
428
499
|
*
|
|
429
500
|
* WHY the log matters as much as the result: "The query could not be
|
|
430
501
|
* completed." is the whole of what a model can act on, and it is also the
|
|
@@ -435,11 +506,17 @@ function tooLarge(message, remedies) {
|
|
|
435
506
|
* same thing at the other entry point.
|
|
436
507
|
*
|
|
437
508
|
* A validation error is not logged: it is the caller's mistake, it is reported
|
|
438
|
-
* back in full, and logging every malformed query would bury the outages.
|
|
509
|
+
* back in full, and logging every malformed query would bury the outages. A
|
|
510
|
+
* resource limit is logged: it is the caller's query, but which queries the
|
|
511
|
+
* datasource cannot afford is for whoever runs it to know.
|
|
512
|
+
*
|
|
513
|
+
* `limitRemedies` is for `metrics_discover`, which takes no arguments and so
|
|
514
|
+
* cannot narrow a window.
|
|
439
515
|
*/
|
|
440
|
-
function fromThrown(error, logger) {
|
|
516
|
+
function fromThrown(error, logger, limitRemedies = RESOURCE_LIMIT_REMEDIES) {
|
|
441
517
|
if (error instanceof _kopai_core.kopaiQueryCompiler.KopaiQueryValidationError) return invalidInput(error.message);
|
|
442
518
|
logger?.error(error, "MCP tool call failed");
|
|
519
|
+
if (isResourceLimitError(error)) return tooExpensive("The query was stopped at this deployment's limit on query time, memory or rows read.", limitRemedies);
|
|
443
520
|
return {
|
|
444
521
|
result: errorResult({
|
|
445
522
|
error: "upstream_error",
|
|
@@ -564,7 +641,7 @@ async function runMetricsDiscoverTool(ctx) {
|
|
|
564
641
|
try {
|
|
565
642
|
full = await ctx.readTelemetryDatasource.discoverMetrics({ requestContext: ctx.requestContext });
|
|
566
643
|
} catch (error) {
|
|
567
|
-
return fromThrown(error, ctx.logger);
|
|
644
|
+
return fromThrown(error, ctx.logger, DISCOVERY_RESOURCE_LIMIT_REMEDIES);
|
|
568
645
|
}
|
|
569
646
|
let serialized = "";
|
|
570
647
|
for (const stage of degradations(full)) {
|
|
@@ -577,6 +654,28 @@ async function runMetricsDiscoverTool(ctx) {
|
|
|
577
654
|
}
|
|
578
655
|
return tooLarge(`The listing of ${full.metrics.length.toLocaleString("en-US")} metrics serialized to ${serialized.length.toLocaleString("en-US")} characters even without their attributes, above the ${MAX_RESULT_CHARACTERS.toLocaleString("en-US")} the host will accept.`, DISCOVERY_SIZE_REMEDIES);
|
|
579
656
|
}
|
|
657
|
+
// src/types.ts
|
|
658
|
+
/**
|
|
659
|
+
* How a tool call ended. These labels are the server's whole error
|
|
660
|
+
* vocabulary: they are the `error` code on a failed result, the `outcome` on
|
|
661
|
+
* the observer event, and the values a counter is grouped by.
|
|
662
|
+
*
|
|
663
|
+
* `not_found` and `forbidden` are produced only by host tools (see
|
|
664
|
+
* {@link HostTools}); the built-in tools never return them.
|
|
665
|
+
*
|
|
666
|
+
* `query_too_expensive` is a query the datasource stopped at a time, memory,
|
|
667
|
+
* row or byte limit, recognised from the thrown error; see
|
|
668
|
+
* `isResourceLimitError`.
|
|
669
|
+
*/
|
|
670
|
+
const TOOL_CALL_OUTCOMES = [
|
|
671
|
+
"ok",
|
|
672
|
+
"invalid_input",
|
|
673
|
+
"result_too_large",
|
|
674
|
+
"query_too_expensive",
|
|
675
|
+
"upstream_error",
|
|
676
|
+
"not_found",
|
|
677
|
+
"forbidden"
|
|
678
|
+
];
|
|
580
679
|
// src/validator.ts
|
|
581
680
|
/**
|
|
582
681
|
* A validator provider that accepts everything, so that the tool handler is
|
|
@@ -643,13 +742,22 @@ const METRICS_DISCOVER_DESCRIPTION = [
|
|
|
643
742
|
"Takes no arguments.",
|
|
644
743
|
`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.`
|
|
645
744
|
].join(" ");
|
|
745
|
+
/** The tools this package registers itself. A host tool may not reuse them. */
|
|
746
|
+
const BUILT_IN_TOOL_NAMES = ["query", "metrics_discover"];
|
|
646
747
|
/**
|
|
647
|
-
*
|
|
748
|
+
* Returns the function that runs one tool call and reports it, whatever
|
|
749
|
+
* happens. Shared by the built-in and the host tools, so every tool on the
|
|
750
|
+
* server reaches `onToolCall` through this one place.
|
|
648
751
|
*
|
|
649
|
-
*
|
|
650
|
-
*
|
|
752
|
+
* WHY the catch: a throw out of a tool used to skip `observe` altogether, so
|
|
753
|
+
* the host's counter lost exactly the calls most worth seeing — and the SDK
|
|
754
|
+
* turned it into a bare message with no `structuredContent`, which is the
|
|
755
|
+
* one error shape a page cannot read. Nothing in the tools is expected to
|
|
756
|
+
* throw; that is the reason to handle it here rather than to assume it, and
|
|
757
|
+
* converting it gives an unexpected failure the same contract as an expected
|
|
758
|
+
* one: a structured payload, a logged cause, and one observer event.
|
|
651
759
|
*/
|
|
652
|
-
function
|
|
760
|
+
function observedCall(opts) {
|
|
653
761
|
const observe = (tool, startedAt, outcome, rowCount) => {
|
|
654
762
|
if (!opts.onToolCall) return;
|
|
655
763
|
try {
|
|
@@ -657,22 +765,11 @@ function registerTools(server, opts) {
|
|
|
657
765
|
tool,
|
|
658
766
|
outcome,
|
|
659
767
|
durationMs: Date.now() - startedAt,
|
|
660
|
-
rowCount
|
|
768
|
+
...rowCount !== void 0 ? { rowCount } : {}
|
|
661
769
|
});
|
|
662
770
|
} catch {}
|
|
663
771
|
};
|
|
664
|
-
|
|
665
|
-
* Runs one tool call and reports it, whatever happens.
|
|
666
|
-
*
|
|
667
|
-
* WHY the catch: a throw out of a tool used to skip `observe` altogether, so
|
|
668
|
-
* the host's counter lost exactly the calls most worth seeing — and the SDK
|
|
669
|
-
* turned it into a bare message with no `structuredContent`, which is the
|
|
670
|
-
* one error shape a page cannot read. Nothing in the tools is expected to
|
|
671
|
-
* throw; that is the reason to handle it here rather than to assume it, and
|
|
672
|
-
* converting it gives an unexpected failure the same contract as an expected
|
|
673
|
-
* one: a structured payload, a logged cause, and one observer event.
|
|
674
|
-
*/
|
|
675
|
-
const call = async (tool, execute) => {
|
|
772
|
+
return async (tool, execute) => {
|
|
676
773
|
const startedAt = Date.now();
|
|
677
774
|
let run;
|
|
678
775
|
try {
|
|
@@ -683,6 +780,15 @@ function registerTools(server, opts) {
|
|
|
683
780
|
observe(tool, startedAt, run.outcome, run.rowCount);
|
|
684
781
|
return run.result;
|
|
685
782
|
};
|
|
783
|
+
}
|
|
784
|
+
/**
|
|
785
|
+
* Registers the `query` and `metrics_discover` tools on `server`.
|
|
786
|
+
*
|
|
787
|
+
* Every call reports to `opts.onToolCall` exactly once, including a call whose
|
|
788
|
+
* tool throws, which is returned as a structured error rather than rethrown.
|
|
789
|
+
*/
|
|
790
|
+
function registerTools(server, opts) {
|
|
791
|
+
const call = observedCall(opts);
|
|
686
792
|
server.registerTool("query", {
|
|
687
793
|
title: "Query telemetry",
|
|
688
794
|
description: QUERY_DESCRIPTION,
|
|
@@ -702,9 +808,158 @@ function registerTools(server, opts) {
|
|
|
702
808
|
}
|
|
703
809
|
}, async () => call("metrics_discover", () => runMetricsDiscoverTool(opts)));
|
|
704
810
|
}
|
|
811
|
+
const ERROR_CODES = new Set(TOOL_CALL_OUTCOMES.filter((outcome) => outcome !== "ok"));
|
|
812
|
+
const isRecord = (value) => typeof value === "object" && value !== null;
|
|
813
|
+
/**
|
|
814
|
+
* Reads a host tool's outcome from the result it returned.
|
|
815
|
+
*
|
|
816
|
+
* WHY reading is safe here, when `ToolRun` returns the outcome rather than
|
|
817
|
+
* inferring it: `errorResult` is the one builder of an error result, and it
|
|
818
|
+
* always writes the code. A hand-built error result has no code to read; it
|
|
819
|
+
* is counted as `upstream_error`, the same label an unexpected throw gets, and
|
|
820
|
+
* logged so the tool can be fixed. It is not thrown: the caller already has
|
|
821
|
+
* an answer, and the tool's own text is more use to it than ours.
|
|
822
|
+
*/
|
|
823
|
+
function hostOutcome(tool, result, logger) {
|
|
824
|
+
if (!isRecord(result) || result.isError !== true) return "ok";
|
|
825
|
+
const code = isRecord(result.structuredContent) ? result.structuredContent.error : void 0;
|
|
826
|
+
if (typeof code === "string" && ERROR_CODES.has(code)) return code;
|
|
827
|
+
logger?.error({ tool }, "MCP host tool returned an error result without a known error code");
|
|
828
|
+
return "upstream_error";
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* A host tool's throw, converted as `fromThrown` converts a built-in's, with
|
|
832
|
+
* two differences: the generic message names no query, since a host tool need
|
|
833
|
+
* not run one, and the log line names the tool.
|
|
834
|
+
*
|
|
835
|
+
* A resource limit is classified here too: a host tool that reads telemetry
|
|
836
|
+
* (a backtest, say) lets its query's throw through, and would otherwise
|
|
837
|
+
* report a limit the caller can get past as a generic failure.
|
|
838
|
+
*/
|
|
839
|
+
function thrownByHostTool(tool, error, logger) {
|
|
840
|
+
logger?.error(error, `MCP host tool "${tool}" failed`);
|
|
841
|
+
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);
|
|
842
|
+
return {
|
|
843
|
+
result: errorResult({
|
|
844
|
+
error: "upstream_error",
|
|
845
|
+
message: "The tool call could not be completed."
|
|
846
|
+
}),
|
|
847
|
+
outcome: "upstream_error"
|
|
848
|
+
};
|
|
849
|
+
}
|
|
850
|
+
/**
|
|
851
|
+
* Runs the host's `register` on `server`, with `registerTool` guarded and
|
|
852
|
+
* observed.
|
|
853
|
+
*
|
|
854
|
+
* The guard is installed on this one per-request instance, through the SDK's
|
|
855
|
+
* public API only. It refuses a name not in `names`, so the check made at
|
|
856
|
+
* boot cannot be bypassed through `registerTool` or `update` — a host that
|
|
857
|
+
* reaches past them, by writing `handle.executor` or calling the prototype's
|
|
858
|
+
* `registerTool`, is not guarded, and is not meant to be. It wraps the
|
|
859
|
+
* returned handle's `update` as well: `update({ name })` renames a registered tool, and `update({ callback
|
|
860
|
+
* })` swaps its callback, either of which would otherwise slip past the guard.
|
|
861
|
+
* `remove()` is `update({ name: null })` in the SDK and passes.
|
|
862
|
+
*
|
|
863
|
+
* A refusal throws, and so does anything else `register` throws. Both fail the
|
|
864
|
+
* request; see {@link HostTools}.
|
|
865
|
+
*/
|
|
866
|
+
function registerHostTools(server, opts) {
|
|
867
|
+
const call = observedCall(opts);
|
|
868
|
+
const assertDeclared = (name) => {
|
|
869
|
+
if (opts.names.has(name)) return;
|
|
870
|
+
const declared = [...opts.names].map((n) => `"${n}"`).join(", ");
|
|
871
|
+
throw new TypeError(`Host tool "${name}" is not in hostTools.names (${declared || "none declared"}). Declare every name register may use.`);
|
|
872
|
+
};
|
|
873
|
+
const registerTool = server.registerTool.bind(server);
|
|
874
|
+
const wrapped = /* @__PURE__ */ new WeakMap();
|
|
875
|
+
const inUse = /* @__PURE__ */ new Set();
|
|
876
|
+
const guarded = (name, config, callback) => {
|
|
877
|
+
assertDeclared(name);
|
|
878
|
+
const refuseOutputSchema = (value, tool) => {
|
|
879
|
+
if (value === void 0) return;
|
|
880
|
+
throw new TypeError(`Host tool "${tool}" declares an outputSchema; host tools may not.`);
|
|
881
|
+
};
|
|
882
|
+
refuseOutputSchema(isRecord(config) ? config.outputSchema : void 0, name);
|
|
883
|
+
let current = name;
|
|
884
|
+
const observed = (inner) => {
|
|
885
|
+
const outer = (...args) => call(current, async () => {
|
|
886
|
+
let result;
|
|
887
|
+
try {
|
|
888
|
+
result = await inner(...args);
|
|
889
|
+
} catch (error) {
|
|
890
|
+
return thrownByHostTool(current, error, opts.logger);
|
|
891
|
+
}
|
|
892
|
+
return {
|
|
893
|
+
result,
|
|
894
|
+
outcome: hostOutcome(current, result, opts.logger)
|
|
895
|
+
};
|
|
896
|
+
});
|
|
897
|
+
wrapped.set(outer, inner);
|
|
898
|
+
return outer;
|
|
899
|
+
};
|
|
900
|
+
const handle = registerTool(name, config, observed(callback));
|
|
901
|
+
inUse.add(name);
|
|
902
|
+
let raw = callback;
|
|
903
|
+
Object.defineProperty(handle, "handler", {
|
|
904
|
+
get: () => raw,
|
|
905
|
+
set: (value) => {
|
|
906
|
+
raw = wrapped.get(value) ?? value;
|
|
907
|
+
},
|
|
908
|
+
enumerable: true,
|
|
909
|
+
configurable: true
|
|
910
|
+
});
|
|
911
|
+
const update = handle.update;
|
|
912
|
+
handle.update = (updates) => {
|
|
913
|
+
refuseOutputSchema(updates.outputSchema, current);
|
|
914
|
+
const renamed = updates.name !== void 0 && updates.name !== current ? updates.name : void 0;
|
|
915
|
+
if (typeof renamed === "string") {
|
|
916
|
+
assertDeclared(renamed);
|
|
917
|
+
if (inUse.has(renamed)) throw new TypeError(`Host tool "${current}" cannot be renamed to "${renamed}", which is already registered.`);
|
|
918
|
+
}
|
|
919
|
+
update(updates.callback === void 0 ? updates : {
|
|
920
|
+
...updates,
|
|
921
|
+
callback: observed(updates.callback)
|
|
922
|
+
});
|
|
923
|
+
if (renamed !== void 0) {
|
|
924
|
+
inUse.delete(current);
|
|
925
|
+
if (renamed !== null) {
|
|
926
|
+
inUse.add(renamed);
|
|
927
|
+
current = renamed;
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
};
|
|
931
|
+
return handle;
|
|
932
|
+
};
|
|
933
|
+
server.registerTool = guarded;
|
|
934
|
+
const returned = opts.register(server);
|
|
935
|
+
if (returned instanceof Promise) {
|
|
936
|
+
returned.catch(() => {});
|
|
937
|
+
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.");
|
|
938
|
+
}
|
|
939
|
+
}
|
|
705
940
|
// src/routes.ts
|
|
706
941
|
const SERVER_NAME = "kopai";
|
|
707
942
|
const SERVER_VERSION = "0.0.0";
|
|
943
|
+
const TOOL_NAME = /^[A-Za-z0-9._-]{1,128}$/;
|
|
944
|
+
/**
|
|
945
|
+
* Checks `hostTools` once, at registration, and returns its names as a set.
|
|
946
|
+
*
|
|
947
|
+
* Refused rather than absorbed, for the reason `allowedOriginHostnames` is: a
|
|
948
|
+
* wrong shape would otherwise fail on every request, and a name colliding
|
|
949
|
+
* with a built-in would fail only when a caller who may use it arrives.
|
|
950
|
+
*/
|
|
951
|
+
function checkedHostToolNames(hostTools) {
|
|
952
|
+
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.");
|
|
953
|
+
const names = /* @__PURE__ */ new Set();
|
|
954
|
+
const builtIns = BUILT_IN_TOOL_NAMES;
|
|
955
|
+
for (const name of hostTools.names) {
|
|
956
|
+
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, ".", "_", "-").`);
|
|
957
|
+
if (builtIns.includes(name)) throw new TypeError(`hostTools.names: "${name}" is the name of a built-in tool.`);
|
|
958
|
+
if (names.has(name)) throw new TypeError(`hostTools.names: "${name}" appears more than once.`);
|
|
959
|
+
names.add(name);
|
|
960
|
+
}
|
|
961
|
+
return names;
|
|
962
|
+
}
|
|
708
963
|
/**
|
|
709
964
|
* Mounts the MCP endpoint at `/mcp`, relative to wherever this plugin is
|
|
710
965
|
* registered.
|
|
@@ -718,6 +973,10 @@ const mcpRoutes = async function mcpRoutes(fastify, opts) {
|
|
|
718
973
|
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.");
|
|
719
974
|
fastify.addHook("onRequest", (0, _modelcontextprotocol_fastify.originValidation)(opts.allowedOriginHostnames));
|
|
720
975
|
}
|
|
976
|
+
const hostTools = opts.hostTools === void 0 ? void 0 : {
|
|
977
|
+
names: checkedHostToolNames(opts.hostTools),
|
|
978
|
+
register: opts.hostTools.register
|
|
979
|
+
};
|
|
721
980
|
const handleMcp = async (request, reply) => {
|
|
722
981
|
if (request.method !== "POST") reply.raw.setHeader("Allow", "POST");
|
|
723
982
|
const handler = (0, _modelcontextprotocol_server.createMcpHandler)(() => {
|
|
@@ -725,7 +984,7 @@ const mcpRoutes = async function mcpRoutes(fastify, opts) {
|
|
|
725
984
|
name: SERVER_NAME,
|
|
726
985
|
version: SERVER_VERSION
|
|
727
986
|
});
|
|
728
|
-
|
|
987
|
+
const toolOptions = {
|
|
729
988
|
readTelemetryDatasource: opts.readTelemetryDatasource,
|
|
730
989
|
requestContext: request.requestContext,
|
|
731
990
|
logger: opts.logger ?? request.log,
|
|
@@ -733,7 +992,18 @@ const mcpRoutes = async function mcpRoutes(fastify, opts) {
|
|
|
733
992
|
...event,
|
|
734
993
|
request
|
|
735
994
|
}) : void 0
|
|
736
|
-
}
|
|
995
|
+
};
|
|
996
|
+
registerTools(server, toolOptions);
|
|
997
|
+
if (hostTools !== void 0) try {
|
|
998
|
+
registerHostTools(server, {
|
|
999
|
+
...toolOptions,
|
|
1000
|
+
names: hostTools.names,
|
|
1001
|
+
register: (s) => hostTools.register(s, request)
|
|
1002
|
+
});
|
|
1003
|
+
} catch (error) {
|
|
1004
|
+
toolOptions.logger?.error(error, "MCP hostTools.register failed");
|
|
1005
|
+
throw error;
|
|
1006
|
+
}
|
|
737
1007
|
return server;
|
|
738
1008
|
});
|
|
739
1009
|
reply.hijack();
|
|
@@ -755,6 +1025,7 @@ const mcpRoutes = async function mcpRoutes(fastify, opts) {
|
|
|
755
1025
|
handler: handleMcp
|
|
756
1026
|
});
|
|
757
1027
|
};
|
|
1028
|
+
exports.BUILT_IN_TOOL_NAMES = BUILT_IN_TOOL_NAMES;
|
|
758
1029
|
exports.DESCRIPTION_OVERRIDES_APPLIED = DESCRIPTION_OVERRIDES_APPLIED;
|
|
759
1030
|
exports.DISCOVERY_SIZE_REMEDIES = DISCOVERY_SIZE_REMEDIES;
|
|
760
1031
|
exports.LIMITS = LIMITS;
|
|
@@ -762,10 +1033,17 @@ exports.MAX_RESULT_CHARACTERS = MAX_RESULT_CHARACTERS;
|
|
|
762
1033
|
exports.METRICS_DISCOVER_TOOL_INPUT_SCHEMA = METRICS_DISCOVER_TOOL_INPUT_SCHEMA;
|
|
763
1034
|
exports.QUERY_TOOL_INPUT_SCHEMA = QUERY_TOOL_INPUT_SCHEMA;
|
|
764
1035
|
exports.SIZE_REMEDIES = SIZE_REMEDIES;
|
|
1036
|
+
exports.TOOL_CALL_OUTCOMES = TOOL_CALL_OUTCOMES;
|
|
765
1037
|
exports.applyDescriptions = applyDescriptions;
|
|
766
1038
|
exports.dedupe = dedupe;
|
|
767
1039
|
exports.descriptionOverrides = descriptionOverrides;
|
|
768
1040
|
exports.errorResult = errorResult;
|
|
1041
|
+
Object.defineProperty(exports, "fromJsonSchema", {
|
|
1042
|
+
enumerable: true,
|
|
1043
|
+
get: function() {
|
|
1044
|
+
return _modelcontextprotocol_server.fromJsonSchema;
|
|
1045
|
+
}
|
|
1046
|
+
});
|
|
769
1047
|
exports.mcpRoutes = mcpRoutes;
|
|
770
1048
|
exports.okResult = okResult;
|
|
771
1049
|
exports.overflowRemedies = overflowRemedies;
|
package/dist/index.d.cts
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.cts.map
|
package/dist/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;;
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":["SchemaNode","McpServer","McpServer"],"sources":["../src/dedupe.ts","../src/limits.ts","../src/types.ts","../src/results.ts","../src/tools.ts","../src/register.ts","../src/routes.ts","../src/describe.ts","../src/schema.ts","../src/validator.ts"],"mappings":";;;KAoBKA,eAAa;;;;;;;;;;wBAkFF,OAAO,KAAKA,cAAY,kBAAcA;;;;;;;;;;;;;;;;;;;;;;;;qBC7EzC;;;;;;;;;;;;;;;;;;;;;;;;qBAyBA;;;;;;;;;;qBAWA;;qBAkEA;;;;;;;;;;;;;;;;;;wBA6EG,iBACd,OAAO,WAAW,YAClB,eACA;;;;;;;;;;;;;qBC/LW;KAUD,0BAA0B;;;;;;;;;UAUrB;EACf,MAAM,kBAAkB;;;;;;;;;;UAWT;EACf;EACA,SAAS;EACT;;EAEA;EACA,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAkCM;;;;;;;EAOf;;;;;;;;;;;;;;;EAeA,WAAW,QAAQC,aAAW,SAAS;;UAGxB;EACf,yBAAyB,WAAW;;;;;;EAMpC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+BA;;;;;EAKA,SAAS;;EAET,cAAc,OAAO;;EAErB,YAAY;;;YAQF;IACR;;;;KCtKQ,gBAAgB,QAAQ;UAEnB;EACf;EACA;;UAGe;EACf,OAAO;EACP;EACA,SAAS;EACT;;;;;;;KAQU;EACV;EACA,SAAS;IAAQ;IAAc;;EAC/B;;;;;;;;;;;;;;;;;;;;;;;wBAwBc,SAAS,mBAAmB;;;;;;;;;;wBAgB5B,YAAY,SAAS,mBAAmB;;;;;;wBAsBxC,iBAAiB,QAAQ,cAAc;UCnEtC;EACf,yBAAyB,WAAW;;EAEpC;;EAEA,SAAS;;;;;;;UAQM;EACf,QAAQ;EACR,SAAS;EACT;;wBAwHoB,aACpB,gBACA,KAAK,cACJ,QAAQ;wBA4LW,uBACpB,KAAK,cACJ,QAAQ;;qBCvRE;UAEI,6BAA6B;;;;;EAK5C,cAAc;IACZ;IACA,SAAS;IACT;IACA;;;;;;;;;wBAoEY,cACd,QAAQC,aACR,MAAM;;;;;;;;qBCjFK,WAAW,mBAAmB;KCnDtC,aAAa;UAED;;WAEN;;WAEA;WACA;;wBAGK,qBACd,gBACA,sBACA,oBACA,2BACC;;;;;wBAwBa,kBACd,KAAK,YACL,oBAAoB;EACjB,UAAU;EAAY,SAAS;;;qBCpBvB,+BAA6B;qBAE7B,yBAAyB;;;;;qBAQzB,oCAAoC;;;;;;;;;;;;;;;;;;;;;;;;;qBCtBpC,sBAAsB"}
|