@kopai/mcp 0.0.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.
@@ -0,0 +1,352 @@
1
+ import { datasource, kopaiQuery } from "@kopai/core";
2
+ import { McpServer, jsonSchemaValidator } from "@modelcontextprotocol/server";
3
+ import { FastifyPluginAsync, FastifyRequest } from "fastify";
4
+ //#region src/dedupe.d.ts
5
+ type SchemaNode$1 = Record<string, unknown>;
6
+ /**
7
+ * Returns `doc` with every subschema that occurs more than once hoisted into
8
+ * `$defs`.
9
+ *
10
+ * `minLen` is the serialized length below which a repeat is not worth a
11
+ * reference — a `$ref` costs about 30 characters, so hoisting anything
12
+ * shorter makes the document bigger. Any existing `$defs` are preserved and
13
+ * deduplicated alongside the body.
14
+ */
15
+ export declare function dedupe(doc: SchemaNode$1, minLen?: number): SchemaNode$1;
16
+ //#endregion
17
+ //#region src/limits.d.ts
18
+ /**
19
+ * Row caps, per mode.
20
+ *
21
+ * WHY per mode rather than one number: measured serialized row sizes differ by
22
+ * an order of magnitude. A raw trace row is ~703 characters, a raw log row
23
+ * ~418, a raw metric row 408-653 (OTel repeats the metric name, description
24
+ * and unit on every data point), against ~96 for an aggregate summary row and
25
+ * ~134 for a `timeSeries` row. Against the character ceiling below, a uniform
26
+ * cap of 500 would let every raw shape overrun — traces by 134%, logs by 39%,
27
+ * metrics by 36-118% — so a raw query that used its own cap would pay for a
28
+ * full round trip and then have the result refused.
29
+ *
30
+ * At 200 they all fit, though traces land at ~94% of budget, which is why the
31
+ * post-serialization check stays load-bearing rather than being a formality.
32
+ * Treat these figures as optimistic: they come from fixtures, and production
33
+ * attribute maps are heavier.
34
+ *
35
+ * The consequence for callers, worth stating in the tool description: the
36
+ * aggregate shape is the efficient one and raw is for inspecting individual
37
+ * records. One hour of one gauge costs roughly 116,400 characters as raw rows
38
+ * against 8,040 as a `timeSeries` aggregate at `1m` — fourteen times less, for
39
+ * the same chart, with the bucketing done in the database.
40
+ */
41
+ export declare const LIMITS: {
42
+ readonly raw: {
43
+ /** Applied when the caller sends no `limit`; matches the backend default. */
44
+ readonly fallback: 100;
45
+ readonly max: 200;
46
+ };
47
+ readonly aggregate: {
48
+ /**
49
+ * Applied when the caller sends no `limit`. Unlike raw, this is not a
50
+ * backend default being restated: both backends emit `LIMIT` for an
51
+ * aggregate query only when one is explicitly set, so an aggregate query
52
+ * with no limit runs unbounded.
53
+ */
54
+ readonly fallback: 500;
55
+ readonly max: 500;
56
+ };
57
+ };
58
+ /**
59
+ * The serialized size past which a result is refused rather than returned.
60
+ *
61
+ * Measured after serialization, on one copy of the payload — the result
62
+ * carries the same JSON in two channels, but a client forwards one or the
63
+ * other, so the model only ever ingests it once.
64
+ */
65
+ export declare const MAX_RESULT_CHARACTERS = 150000;
66
+ /**
67
+ * Remedies for a discovery listing too large even with the attributes gone.
68
+ *
69
+ * WHY its own list: `metrics_discover` takes no arguments, so every line in
70
+ * `SIZE_REMEDIES` names a field the caller cannot set — a `limit`, a window, a
71
+ * `granularity`. Offering those turned an over-size listing into a dead end
72
+ * dressed up as advice. Nothing the caller writes can shrink this result, so
73
+ * the honest answer is what remains possible without it.
74
+ */
75
+ export declare const DISCOVERY_SIZE_REMEDIES: readonly ["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."];
76
+ /** Remedies offered when a result is too large once serialized. */
77
+ export declare const SIZE_REMEDIES: readonly ["Lower `limit`.", "Narrow the time window.", "Use a coarser `granularity`, or `output: {type: 'summary'}` instead of a time series."];
78
+ /**
79
+ * Remedies for an aggregate query that overran its cap, ordered by whichever
80
+ * factor actually caused it.
81
+ *
82
+ * WHY ordered rather than a fixed list: an aggregate returns groups times
83
+ * buckets rows, and advice for one is useless for the other. Telling someone
84
+ * grouping by a high-cardinality column in a `summary` query to use a coarser
85
+ * granularity names a field their query does not have; telling someone whose
86
+ * window is cut into more buckets than the cap allows to group by less will
87
+ * not help them either.
88
+ *
89
+ * WHY there is no "add an `orderBy`" line: an ordering does not change the
90
+ * outcome. An overflow is refused whether or not the query is ordered, because
91
+ * a live page cannot act on a remedy — its query was fixed at authoring time
92
+ * and its viewer did not write it — so a truncated result would be drawn as
93
+ * though it were the whole set.
94
+ */
95
+ export declare function overflowRemedies(query: kopaiQuery.KopaiQuery, limit: number, max: number): string[];
96
+ //#endregion
97
+ //#region src/types.d.ts
98
+ /**
99
+ * How a tool call ended. These four labels are the server's whole error
100
+ * vocabulary: they are the `error` code on a failed result, the `outcome` on
101
+ * the observer event, and the values a counter is grouped by.
102
+ */
103
+ type ToolCallOutcome = "ok" | "invalid_input" | "result_too_large" | "upstream_error";
104
+ /**
105
+ * The one method this package calls on a logger.
106
+ *
107
+ * Structural rather than Fastify's own type: the tool layer knows nothing
108
+ * about HTTP, and a host that mounts this plugin somewhere else should not
109
+ * have to produce a `FastifyBaseLogger` to get its failures written down.
110
+ * `routes.ts` passes `request.log`, which satisfies it.
111
+ */
112
+ interface ToolLogger {
113
+ error(payload: unknown, message?: string): void;
114
+ }
115
+ /**
116
+ * One completed tool call, handed to `onToolCall`.
117
+ *
118
+ * WHY the raw request is included: this plugin is open source and mounts in
119
+ * two applications that know different things about a caller. It deliberately
120
+ * does not learn about tenants or credentials; the host application reads
121
+ * whatever it attached to the request and does its own counting and logging.
122
+ */
123
+ interface ToolCallEvent {
124
+ tool: string;
125
+ outcome: ToolCallOutcome;
126
+ durationMs: number;
127
+ /** Rows returned, when the tool returned rows. */
128
+ rowCount?: number;
129
+ request: FastifyRequest;
130
+ }
131
+ interface McpRoutesOptions {
132
+ readTelemetryDatasource: datasource.ReadTelemetryDatasource;
133
+ /**
134
+ * Hostnames the MCP endpoint answers for, compared port-agnostically. A
135
+ * request whose `Host` is not on this list is refused, which is what stops
136
+ * a DNS-rebinding page from reaching a local server.
137
+ */
138
+ allowedHosts: string[];
139
+ /**
140
+ * Hostnames that may appear in a browser's `Origin` header. Omit to mount no
141
+ * origin validation at all, which is the default.
142
+ *
143
+ * An empty list is not the same as omitting it: it mounts a validator that
144
+ * refuses every browser origin, which is a coherent thing to ask for and a
145
+ * surprising thing to arrive at by accident. Non-browser clients send no
146
+ * `Origin` and pass either way, so an accidental `[]` looks like "works for
147
+ * my MCP client, broken for every page". Omit the option when the intent is
148
+ * no validation. Any other wrong shape — `null` from a config that had no
149
+ * list, a bare string — is refused at registration rather than mounted.
150
+ *
151
+ * WHY hostnames, and why a separate list from {@link allowedHosts}: the two
152
+ * answer different questions. `allowedHosts` is the hostname this server is
153
+ * reached at; this is the hostname of a page allowed to reach it. On a local
154
+ * app they coincide, both being loopback. On a deployed one they do not —
155
+ * the API and the dashboard live at different names — so conflating them
156
+ * either refuses the dashboard or forces the host list wide enough to weaken
157
+ * the rebinding check.
158
+ *
159
+ * WHY hostnames and not origins: the underlying validator compares
160
+ * hostnames, port-agnostically. Passing a full origin such as
161
+ * `"https://app.example.com"` refuses that very origin, and passing `"*"`
162
+ * refuses everything — both silently, since either is a valid `string[]`.
163
+ * Anything shaped like a CORS `origin` list belongs in a CORS plugin, not
164
+ * here.
165
+ *
166
+ * A request with no `Origin` header passes by design, so non-browser clients
167
+ * are unaffected; only browsers are constrained.
168
+ */
169
+ allowedOriginHostnames?: string[];
170
+ /**
171
+ * Where an upstream failure is written. Defaults to the Fastify instance's
172
+ * own request logger; pass one only to send these somewhere else.
173
+ */
174
+ logger?: ToolLogger;
175
+ /** Called once per completed tool call. Errors thrown here are swallowed. */
176
+ onToolCall?: (event: ToolCallEvent) => void;
177
+ }
178
+ declare module "fastify" {
179
+ interface FastifyRequest {
180
+ requestContext?: unknown;
181
+ }
182
+ }
183
+ //#endregion
184
+ //#region src/results.d.ts
185
+ /** An error code a tool can return. `ok` is not one of them. */
186
+ type ToolErrorCode = Exclude<ToolCallOutcome, "ok">;
187
+ interface ToolIssue {
188
+ path: string;
189
+ message: string;
190
+ }
191
+ interface ToolErrorPayload {
192
+ error: ToolErrorCode;
193
+ message: string;
194
+ issues?: ToolIssue[];
195
+ remedies?: string[];
196
+ }
197
+ /**
198
+ * The shape both tools return. Deliberately not the MCP SDK's own result type
199
+ * — this stays a plain object so it can be asserted on in tests without a
200
+ * server.
201
+ */
202
+ type ToolResult = {
203
+ structuredContent: unknown;
204
+ content: Array<{
205
+ type: "text";
206
+ text: string;
207
+ }>;
208
+ isError?: true;
209
+ };
210
+ /**
211
+ * Builds a result carrying `payload` in BOTH channels — as
212
+ * `structuredContent`, and as a single text block holding exactly
213
+ * `JSON.stringify` of the same object.
214
+ *
215
+ * WHY both, when the specification suggests one: the two consumers read
216
+ * different channels and neither reads both. A live page reads
217
+ * `structuredContent` through the artifact runtime's `payload` convenience. A
218
+ * conversational agent reads `content` — Anthropic's own MCP helper returns
219
+ * `result.content.map(...)` and discards `structuredContent` entirely whenever
220
+ * `content` is non-empty, falling back to the structured value only when
221
+ * `content` is empty. So rows in `structuredContent` plus a prose summary in
222
+ * the text block is the one combination that fails: the fallback never fires,
223
+ * and the agent receives the summary and none of the rows, with no error
224
+ * raised anywhere.
225
+ *
226
+ * Sending both costs wire bytes only, never context: a client forwards one
227
+ * channel or the other, so the model ingests the payload once. The text block
228
+ * stays pure JSON so that the "first text block parsed as JSON" path a page
229
+ * may fall back to remains valid.
230
+ */
231
+ export declare function okResult(payload: unknown): ToolResult;
232
+ /**
233
+ * Builds a failed result. Same duplication as {@link okResult}, and more
234
+ * load-bearing here: the empty-content fallback to the structured value sits
235
+ * below the `isError` branch in the agent's helper, so it never fires on a
236
+ * failure. A structured-only success degrades; a structured-only error
237
+ * vanishes, leaving the agent an empty error and nothing to repair from.
238
+ *
239
+ * `error` is written first so the serialized JSON opens with the code.
240
+ */
241
+ export declare function errorResult(payload: ToolErrorPayload): ToolResult;
242
+ /**
243
+ * Re-points issue paths from `@kopai/core`'s query-relative form onto the
244
+ * tool's input, whose single property is `query`. The empty root path becomes
245
+ * `query` rather than `query.`.
246
+ */
247
+ export declare function prefixIssuePaths(issues: ToolIssue[]): ToolIssue[];
248
+ //#endregion
249
+ //#region src/tools.d.ts
250
+ interface ToolContext {
251
+ readTelemetryDatasource: datasource.ReadTelemetryDatasource;
252
+ /** Whatever the host application attached to the request; passed through. */
253
+ requestContext?: unknown;
254
+ /** Where an upstream failure is written. See {@link fromThrown}. */
255
+ logger?: ToolLogger;
256
+ }
257
+ /**
258
+ * A completed tool run. The outcome is returned rather than inferred from the
259
+ * result so that the observer and any counter read the same value the caller
260
+ * sees, with no second classification step to drift.
261
+ */
262
+ interface ToolRun {
263
+ result: ToolResult;
264
+ outcome: ToolCallOutcome;
265
+ rowCount?: number;
266
+ }
267
+ export declare function runQueryTool(input: unknown, ctx: ToolContext): Promise<ToolRun>;
268
+ export declare function runMetricsDiscoverTool(ctx: ToolContext): Promise<ToolRun>;
269
+ //#endregion
270
+ //#region src/register.d.ts
271
+ interface RegisterToolsOptions extends ToolContext {
272
+ /**
273
+ * Called once per completed tool call, after the result is built and before
274
+ * it is returned.
275
+ */
276
+ onToolCall?: (event: {
277
+ tool: string;
278
+ outcome: ToolCallOutcome;
279
+ durationMs: number;
280
+ rowCount?: number;
281
+ }) => void;
282
+ }
283
+ export declare function registerTools(server: McpServer, opts: RegisterToolsOptions): void;
284
+ //#endregion
285
+ //#region src/routes.d.ts
286
+ /**
287
+ * Mounts the MCP endpoint at `/mcp`, relative to wherever this plugin is
288
+ * registered.
289
+ *
290
+ * The server is stateless: no session id, no server push, and a fresh
291
+ * `McpServer` per request.
292
+ */
293
+ export declare const mcpRoutes: FastifyPluginAsync<McpRoutesOptions>;
294
+ //#endregion
295
+ //#region src/describe.d.ts
296
+ type SchemaNode = Record<string, unknown>;
297
+ interface DescriptionOverride {
298
+ /** Start of the description to match, in the shared schema. */
299
+ readonly prefix: string;
300
+ /** Replaces the description outright, or extends it. */
301
+ readonly mode: "replace" | "append";
302
+ readonly text: string;
303
+ }
304
+ export declare function descriptionOverrides(rawMax: number, aggregateMax: number, rawDefault: number, aggregateDefault: number): DescriptionOverride[];
305
+ /**
306
+ * Returns `doc` with each override applied wherever its prefix matches, and a
307
+ * count per override so a caller can tell whether any stopped matching.
308
+ */
309
+ export declare function applyDescriptions(doc: SchemaNode, overrides: readonly DescriptionOverride[]): {
310
+ document: SchemaNode;
311
+ applied: Record<string, number>;
312
+ };
313
+ //#endregion
314
+ //#region src/schema.d.ts
315
+ /** How many nodes each override matched. Asserted in the tests, not at runtime. */
316
+ export declare const DESCRIPTION_OVERRIDES_APPLIED: Record<string, number>;
317
+ export declare const QUERY_TOOL_INPUT_SCHEMA: Record<string, unknown>;
318
+ /**
319
+ * The `metrics_discover` tool takes no arguments, but MCP still requires an
320
+ * object root.
321
+ */
322
+ export declare const METRICS_DISCOVER_TOOL_INPUT_SCHEMA: Record<string, unknown>;
323
+ //#endregion
324
+ //#region src/validator.d.ts
325
+ /**
326
+ * A validator provider that accepts everything, so that the tool handler is
327
+ * what validates.
328
+ *
329
+ * Three reasons, and each would be sufficient on its own:
330
+ *
331
+ * 1. Correctness. The `query` schema is a union of six branches. The SDK's
332
+ * default validator rejects before dispatch and answers with one text line
333
+ * listing every branch's failures, which tells a model nothing about which
334
+ * field it got wrong. The handler instead selects the one branch the
335
+ * caller's `signal`/`mode` names and reports issues against it.
336
+ * 2. Cost. The default provider is AJV-backed and compiles the schema it is
337
+ * given. The transport builds a fresh server per request, so that
338
+ * compilation would happen on every call.
339
+ * 3. Observability. A rejection made before dispatch never reaches the
340
+ * handler, so it never reaches `onToolCall` — the counter would undercount
341
+ * exactly the failures most worth seeing.
342
+ *
343
+ * NOTE the shape: `fromJsonSchema`'s second argument is a provider object with
344
+ * a `getValidator` method, not a validator function. Passing a bare function
345
+ * throws `TypeError: validator.getValidator is not a function`, which the SDK
346
+ * swallows into a 500 on `initialize` — presenting as "the whole server is
347
+ * broken" rather than as a bad argument.
348
+ */
349
+ export declare const passThroughValidator: jsonSchemaValidator;
350
+ //#endregion
351
+ export type { DescriptionOverride, McpRoutesOptions, RegisterToolsOptions, ToolCallEvent, ToolCallOutcome, ToolContext, ToolErrorCode, ToolErrorPayload, ToolIssue, ToolResult, ToolRun };
352
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +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":";;;;KAoBK,eAAa;;;;;;;;;;wBAkFF,OAAO,KAAK,cAAY,kBAAc;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;UC3PM,6BAA6B;;;;;EAK5C,cAAc;IACZ;IACA,SAAS;IACT;IACA;;;wBAIY,cACd,QAAQ,WACR,MAAM;;;;;;;;;;qBClDK,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"}