@selvajs/mcp 0.0.0-stage → 0.1.0-beta.1
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/LICENSE +21 -0
- package/README.md +64 -2
- package/dist/client.d.ts +74 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +127 -0
- package/dist/client.js.map +1 -0
- package/dist/errors.d.ts +24 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +76 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/output.d.ts +20 -0
- package/dist/output.d.ts.map +1 -0
- package/dist/output.js +26 -0
- package/dist/output.js.map +1 -0
- package/dist/server.d.ts +56 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +228 -0
- package/dist/server.js.map +1 -0
- package/dist/spec.d.ts +31 -0
- package/dist/spec.d.ts.map +1 -0
- package/dist/spec.js +42 -0
- package/dist/spec.js.map +1 -0
- package/dist/tool.d.ts +77 -0
- package/dist/tool.d.ts.map +1 -0
- package/dist/tool.js +131 -0
- package/dist/tool.js.map +1 -0
- package/package.json +59 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Selva VektorNode AG
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,65 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @selvajs/mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
MCP server machinery for apps built on Selva. The host writes the tools; this package serves
|
|
4
|
+
them over stdio or streamable HTTP, calls the host's `/api/v1` with an API key, and derives
|
|
5
|
+
each tool's annotations from the host's OpenAPI document.
|
|
6
|
+
|
|
7
|
+
The server is a client of `/api/v1`: no store access, no second auth path. The spec must come
|
|
8
|
+
from `buildOpenApiDocument` in `@selvajs/server/api`, which emits the `x-scope` every operation
|
|
9
|
+
needs.
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { createMcpServer, fromOperation, inputFrom, tool } from '@selvajs/mcp';
|
|
13
|
+
import openapi from './openapi.json'; // the host's own spec, bundled at build time
|
|
14
|
+
|
|
15
|
+
const server = createMcpServer({
|
|
16
|
+
name: 'acme',
|
|
17
|
+
version: '1.0.0',
|
|
18
|
+
baseUrl: process.env.ACME_URL!,
|
|
19
|
+
apiKey: process.env.ACME_API_KEY!, // stdio only; `handle` uses each request's own
|
|
20
|
+
openapi,
|
|
21
|
+
tools: [
|
|
22
|
+
fromOperation('getOrdersById', { name: 'acme_get_order', description, shape }),
|
|
23
|
+
tool({
|
|
24
|
+
name: 'acme_create_job',
|
|
25
|
+
description,
|
|
26
|
+
input: inputFrom('postJobs', { extend: { angleMode: { enum: ['turn', 'corner'] } } }),
|
|
27
|
+
calls: ['postJobs'],
|
|
28
|
+
run: (api, args) => api.call('postJobs', { body: toTurnAngles(args) })
|
|
29
|
+
})
|
|
30
|
+
]
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
await server.listen({ transport: 'stdio' }); // checks the live spec first
|
|
34
|
+
// or, in a route: return server.handle(request);
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## What it enforces
|
|
38
|
+
|
|
39
|
+
- **`calls` is the contract.** A tool lists every operationId it may hit. Annotations come from
|
|
40
|
+
those operations (all `read` → read-only, any DELETE → destructive, any `solve` → open-world),
|
|
41
|
+
and `api.call` refuses anything not listed. Internal and multipart operations are refused at
|
|
42
|
+
startup.
|
|
43
|
+
- **Errors are tool results**, with the next step for the model. A 403 names the missing scope.
|
|
44
|
+
- **429**: a `Retry-After` up to 10 s is waited out (twice at most, same `Idempotency-Key`);
|
|
45
|
+
longer goes back to the model with the wait.
|
|
46
|
+
- **Idempotent operations get a generated `Idempotency-Key`**, reused across retries, so a
|
|
47
|
+
timed-out solve replays instead of running twice. The host's idempotency store is in memory:
|
|
48
|
+
a restart mid-solve can still run it twice.
|
|
49
|
+
- **Over HTTP, each request brings its own key.** `handle` sends the request's
|
|
50
|
+
`Authorization: Bearer` key to `/api/v1` and never the configured `apiKey`; a request without
|
|
51
|
+
one gets 401. `apiKey` is only for `listen` and `verify`.
|
|
52
|
+
- **The key is redacted** from every tool output.
|
|
53
|
+
- **`listen` checks the live spec** at `/api/v1/openapi.json`: every declared call must exist
|
|
54
|
+
with the same scope, or the server refuses to start.
|
|
55
|
+
|
|
56
|
+
## Output
|
|
57
|
+
|
|
58
|
+
A tool returns a string, or `{ text, structured?, images? }`. `images` (`{ data, mimeType }`,
|
|
59
|
+
base64) follow the text as MCP image content, for a model that can see. Clients render PNG, JPEG,
|
|
60
|
+
GIF and WebP, not SVG.
|
|
61
|
+
|
|
62
|
+
## Typed calls
|
|
63
|
+
|
|
64
|
+
Pass the `operations` type `openapi-typescript` generates from the spec, and `api.call` checks
|
|
65
|
+
params, query and body: `const { tool, fromOperation } = toolkit<operations>()`.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { OperationIndex } from './spec.js';
|
|
2
|
+
type Params<O> = O extends {
|
|
3
|
+
parameters: infer P;
|
|
4
|
+
} ? P : object;
|
|
5
|
+
type PathOf<O> = Params<O> extends {
|
|
6
|
+
path?: infer X;
|
|
7
|
+
} ? X : never;
|
|
8
|
+
type QueryOf<O> = Params<O> extends {
|
|
9
|
+
query?: infer X;
|
|
10
|
+
} ? X : never;
|
|
11
|
+
type BodyOf<O> = O extends {
|
|
12
|
+
requestBody?: {
|
|
13
|
+
content: {
|
|
14
|
+
'application/json': infer B;
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
} ? B : never;
|
|
18
|
+
type JsonOf<R> = R extends {
|
|
19
|
+
content: {
|
|
20
|
+
'application/json': infer B;
|
|
21
|
+
};
|
|
22
|
+
} ? B : undefined;
|
|
23
|
+
type SuccessOf<O> = O extends {
|
|
24
|
+
responses: infer R;
|
|
25
|
+
} ? R extends {
|
|
26
|
+
200: infer S;
|
|
27
|
+
} ? JsonOf<S> : R extends {
|
|
28
|
+
201: infer S;
|
|
29
|
+
} ? JsonOf<S> : undefined : unknown;
|
|
30
|
+
interface CallOptions {
|
|
31
|
+
signal?: AbortSignal;
|
|
32
|
+
/** Overrides the client's default for this call. */
|
|
33
|
+
timeoutMs?: number;
|
|
34
|
+
}
|
|
35
|
+
export type TypedCallArgs<O> = CallOptions & {
|
|
36
|
+
params?: PathOf<O>;
|
|
37
|
+
query?: QueryOf<O>;
|
|
38
|
+
body?: BodyOf<O>;
|
|
39
|
+
};
|
|
40
|
+
export interface UntypedCallArgs extends CallOptions {
|
|
41
|
+
params?: Record<string, string | number>;
|
|
42
|
+
query?: Record<string, unknown>;
|
|
43
|
+
body?: unknown;
|
|
44
|
+
}
|
|
45
|
+
export interface TypedApi<Ops> {
|
|
46
|
+
call<K extends Extract<keyof Ops, string>>(operationId: K, args?: TypedCallArgs<Ops[K]>): Promise<SuccessOf<Ops[K]>>;
|
|
47
|
+
}
|
|
48
|
+
export interface UntypedApi {
|
|
49
|
+
call(operationId: string, args?: UntypedCallArgs): Promise<unknown>;
|
|
50
|
+
}
|
|
51
|
+
export type Api<Ops = never> = [Ops] extends [never] ? UntypedApi : TypedApi<Ops>;
|
|
52
|
+
/** A binary success body. Tools describe it; the bytes are no use to a model. */
|
|
53
|
+
export interface BinaryBody {
|
|
54
|
+
binary: true;
|
|
55
|
+
contentType: string;
|
|
56
|
+
bytes: number;
|
|
57
|
+
}
|
|
58
|
+
export interface ApiClientOptions {
|
|
59
|
+
/** The host's origin, e.g. `https://selva.example.com`. Spec paths carry the `/api/v1` prefix. */
|
|
60
|
+
baseUrl: string;
|
|
61
|
+
apiKey: string;
|
|
62
|
+
fetch?: typeof fetch;
|
|
63
|
+
/** Default 30 s. */
|
|
64
|
+
timeoutMs?: number;
|
|
65
|
+
/** For `solve` operations, which run a whole Compute solve. Default 5 min. */
|
|
66
|
+
solveTimeoutMs?: number;
|
|
67
|
+
/** A 429 with a longer `Retry-After` goes back to the model instead of waiting. Default 10 s. */
|
|
68
|
+
maxRetryWaitSeconds?: number;
|
|
69
|
+
}
|
|
70
|
+
export declare function createApiClient(index: OperationIndex, options: ApiClientOptions,
|
|
71
|
+
/** Operations this client may call; anything else throws before reaching the network. */
|
|
72
|
+
allowed?: ReadonlySet<string>): UntypedApi;
|
|
73
|
+
export {};
|
|
74
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAa,cAAc,EAAE,MAAM,WA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;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,8EAA8E;IAC9E,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,iGAAiG;IACjG,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAKD,wBAAgB,eAAe,CAC9B,KAAK,EAAE,cAAc,EACrB,OAAO,EAAE,gBAAgB;AACzB,yFAAyF;AACzF,OAAO,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,GAC3B,UAAU,CAqEZ"}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { ApiCallError } from './errors.js';
|
|
2
|
+
const RATE_RETRIES = 2;
|
|
3
|
+
const NETWORK_RETRIES = 1;
|
|
4
|
+
export function createApiClient(index, options,
|
|
5
|
+
/** Operations this client may call; anything else throws before reaching the network. */
|
|
6
|
+
allowed) {
|
|
7
|
+
const doFetch = options.fetch ?? fetch;
|
|
8
|
+
const base = options.baseUrl.replace(/\/$/, '');
|
|
9
|
+
const maxWait = options.maxRetryWaitSeconds ?? 10;
|
|
10
|
+
async function call(operationId, args = {}) {
|
|
11
|
+
const op = index.get(operationId);
|
|
12
|
+
if (!op)
|
|
13
|
+
throw new Error(`Unknown operation ${operationId}: not in the host's OpenAPI document`);
|
|
14
|
+
if (allowed && !allowed.has(operationId)) {
|
|
15
|
+
throw new Error(`${operationId} is not in this tool's \`calls\`, so its annotations do not cover it`);
|
|
16
|
+
}
|
|
17
|
+
const url = base + fillPath(op, args.params) + queryString(args.query);
|
|
18
|
+
const headers = {
|
|
19
|
+
Authorization: `Bearer ${options.apiKey}`,
|
|
20
|
+
Accept: 'application/json'
|
|
21
|
+
};
|
|
22
|
+
if (args.body !== undefined)
|
|
23
|
+
headers['Content-Type'] = 'application/json';
|
|
24
|
+
// One key for every attempt: a retry after a timeout replays instead of running twice.
|
|
25
|
+
if (op.idempotent)
|
|
26
|
+
headers['Idempotency-Key'] = crypto.randomUUID();
|
|
27
|
+
const timeoutMs = args.timeoutMs ??
|
|
28
|
+
(op.scope === 'solve' ? (options.solveTimeoutMs ?? 300_000) : (options.timeoutMs ?? 30_000));
|
|
29
|
+
const canRetryNetwork = op.idempotent || op.method === 'GET';
|
|
30
|
+
let rateRetries = 0;
|
|
31
|
+
let networkRetries = 0;
|
|
32
|
+
for (;;) {
|
|
33
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
34
|
+
const signal = args.signal ? AbortSignal.any([args.signal, timeout]) : timeout;
|
|
35
|
+
let res;
|
|
36
|
+
try {
|
|
37
|
+
res = await doFetch(url, {
|
|
38
|
+
method: op.method,
|
|
39
|
+
headers,
|
|
40
|
+
body: args.body === undefined ? undefined : JSON.stringify(args.body),
|
|
41
|
+
signal
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
if (args.signal?.aborted)
|
|
46
|
+
throw err;
|
|
47
|
+
if (canRetryNetwork && networkRetries++ < NETWORK_RETRIES)
|
|
48
|
+
continue;
|
|
49
|
+
const timedOut = timeout.aborted;
|
|
50
|
+
throw new ApiCallError(operationId, 0, timedOut ? 'TIMEOUT' : 'UNREACHABLE', timedOut ? `No response within ${Math.round(timeoutMs / 1000)}s` : errorText(err));
|
|
51
|
+
}
|
|
52
|
+
if (res.status === 429) {
|
|
53
|
+
const wait = retryAfterSeconds(res.headers.get('Retry-After'));
|
|
54
|
+
if (wait !== undefined && wait <= maxWait && rateRetries++ < RATE_RETRIES) {
|
|
55
|
+
await res.body?.cancel();
|
|
56
|
+
await sleep(wait * 1000, args.signal);
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
throw await toError(operationId, res, wait);
|
|
60
|
+
}
|
|
61
|
+
if (!res.ok)
|
|
62
|
+
throw await toError(operationId, res);
|
|
63
|
+
return readBody(res);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return { call };
|
|
67
|
+
}
|
|
68
|
+
function fillPath(op, params = {}) {
|
|
69
|
+
return op.path.replace(/\{(\w+)\}/g, (_, name) => {
|
|
70
|
+
const value = params[name];
|
|
71
|
+
if (value === undefined || value === '')
|
|
72
|
+
throw new Error(`${op.operationId} needs \`${name}\``);
|
|
73
|
+
return encodeURIComponent(String(value));
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
function queryString(query) {
|
|
77
|
+
const search = new URLSearchParams();
|
|
78
|
+
for (const [key, value] of Object.entries(query ?? {})) {
|
|
79
|
+
if (value === undefined || value === null)
|
|
80
|
+
continue;
|
|
81
|
+
for (const v of Array.isArray(value) ? value : [value])
|
|
82
|
+
search.append(key, String(v));
|
|
83
|
+
}
|
|
84
|
+
const s = search.toString();
|
|
85
|
+
return s ? `?${s}` : '';
|
|
86
|
+
}
|
|
87
|
+
async function readBody(res) {
|
|
88
|
+
if (res.status === 204)
|
|
89
|
+
return undefined;
|
|
90
|
+
const type = res.headers.get('Content-Type') ?? '';
|
|
91
|
+
if (type.includes('json'))
|
|
92
|
+
return res.json();
|
|
93
|
+
const bytes = (await res.arrayBuffer()).byteLength;
|
|
94
|
+
return { binary: true, contentType: type, bytes };
|
|
95
|
+
}
|
|
96
|
+
async function toError(operationId, res, retryAfter) {
|
|
97
|
+
let body = {};
|
|
98
|
+
try {
|
|
99
|
+
body = (await res.json());
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
// Not the envelope: a proxy's HTML page or an empty body. The status still says enough.
|
|
103
|
+
}
|
|
104
|
+
return new ApiCallError(operationId, res.status, body.code ?? `HTTP_${res.status}`, body.message ?? res.statusText, body.fields, body.details, retryAfter);
|
|
105
|
+
}
|
|
106
|
+
function retryAfterSeconds(header) {
|
|
107
|
+
if (!header)
|
|
108
|
+
return undefined;
|
|
109
|
+
const seconds = Number(header);
|
|
110
|
+
if (Number.isFinite(seconds))
|
|
111
|
+
return Math.max(0, seconds);
|
|
112
|
+
const date = Date.parse(header);
|
|
113
|
+
return Number.isNaN(date) ? undefined : Math.max(0, (date - Date.now()) / 1000);
|
|
114
|
+
}
|
|
115
|
+
function sleep(ms, signal) {
|
|
116
|
+
return new Promise((resolve, reject) => {
|
|
117
|
+
const timer = setTimeout(resolve, ms);
|
|
118
|
+
signal?.addEventListener('abort', () => {
|
|
119
|
+
clearTimeout(timer);
|
|
120
|
+
reject(signal.reason);
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
function errorText(err) {
|
|
125
|
+
return err instanceof Error ? err.message : String(err);
|
|
126
|
+
}
|
|
127
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAgF3C,MAAM,YAAY,GAAG,CAAC,CAAC;AACvB,MAAM,eAAe,GAAG,CAAC,CAAC;AAE1B,MAAM,UAAU,eAAe,CAC9B,KAAqB,EACrB,OAAyB;AACzB,yFAAyF;AACzF,OAA6B;IAE7B,MAAM,OAAO,GAAG,OAAO,CAAC,KAAK,IAAI,KAAK,CAAC;IACvC,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IAChD,MAAM,OAAO,GAAG,OAAO,CAAC,mBAAmB,IAAI,EAAE,CAAC;IAElD,KAAK,UAAU,IAAI,CAAC,WAAmB,EAAE,OAAwB,EAAE;QAClE,MAAM,EAAE,GAAG,KAAK,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;QAClC,IAAI,CAAC,EAAE;YACN,MAAM,IAAI,KAAK,CAAC,qBAAqB,WAAW,sCAAsC,CAAC,CAAC;QACzF,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;YAC1C,MAAM,IAAI,KAAK,CACd,GAAG,WAAW,sEAAsE,CACpF,CAAC;QACH,CAAC;QAED,MAAM,GAAG,GAAG,IAAI,GAAG,QAAQ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C,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,IAAI,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;AACjF,CAAC;AAED,SAAS,KAAK,CAAC,EAAU,EAAE,MAAoB;IAC9C,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACtC,MAAM,KAAK,GAAG,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;QACtC,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE;YACtC,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QACvB,CAAC,CAAC,CAAC;IACJ,CAAC,CAAC,CAAC;AACJ,CAAC;AAED,SAAS,SAAS,CAAC,GAAY;IAC9B,OAAO,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACzD,CAAC"}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** A failed `/api/v1` call, with the host's error envelope when it sent one. */
|
|
2
|
+
export declare class ApiCallError extends Error {
|
|
3
|
+
readonly operationId: string;
|
|
4
|
+
/** HTTP status; `0` when no response arrived. */
|
|
5
|
+
readonly status: number;
|
|
6
|
+
/** The envelope's `code`, or `TIMEOUT` / `UNREACHABLE` without a response. */
|
|
7
|
+
readonly code: string;
|
|
8
|
+
readonly fields?: Record<string, string> | undefined;
|
|
9
|
+
readonly details?: Record<string, string> | undefined;
|
|
10
|
+
readonly retryAfterSeconds?: number | undefined;
|
|
11
|
+
constructor(operationId: string,
|
|
12
|
+
/** HTTP status; `0` when no response arrived. */
|
|
13
|
+
status: number,
|
|
14
|
+
/** The envelope's `code`, or `TIMEOUT` / `UNREACHABLE` without a response. */
|
|
15
|
+
code: string, message: string, fields?: Record<string, string> | undefined, details?: Record<string, string> | undefined, retryAfterSeconds?: number | undefined);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Turns an error into a hint for the model: what to do next, given a status.
|
|
19
|
+
* Return `undefined` to fall through to the default.
|
|
20
|
+
*/
|
|
21
|
+
export type ErrorHint = (err: ApiCallError) => string | undefined;
|
|
22
|
+
/** The text a model reads for a failed call: what failed, the field errors, what to do next. */
|
|
23
|
+
export declare function describeError(err: ApiCallError, hint?: ErrorHint): string;
|
|
24
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,qBAAa,YAAa,SAAQ,KAAK;IAErC,QAAQ,CAAC,WAAW,EAAE,MAAM;IAC5B,iDAAiD;IACjD,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,8EAA8E;IAC9E,QAAQ,CAAC,IAAI,EAAE,MAAM;IAErB,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IACxC,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IACzC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM;gBAR1B,WAAW,EAAE,MAAM;IAC5B,iDAAiD;IACxC,MAAM,EAAE,MAAM;IACvB,8EAA8E;IACrE,IAAI,EAAE,MAAM,EACrB,OAAO,EAAE,MAAM,EACN,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,YAAA,EAC/B,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,YAAA,EAChC,iBAAiB,CAAC,EAAE,MAAM,YAAA;CAKpC;AAED;;;GAGG;AACH,MAAM,MAAM,SAAS,GAAG,CAAC,GAAG,EAAE,YAAY,KAAK,MAAM,GAAG,SAAS,CAAC;AA0ClE,gGAAgG;AAChG,wBAAgB,aAAa,CAAC,GAAG,EAAE,YAAY,EAAE,IAAI,CAAC,EAAE,SAAS,GAAG,MAAM,CASzE"}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/** A failed `/api/v1` call, with the host's error envelope when it sent one. */
|
|
2
|
+
export class ApiCallError extends Error {
|
|
3
|
+
operationId;
|
|
4
|
+
status;
|
|
5
|
+
code;
|
|
6
|
+
fields;
|
|
7
|
+
details;
|
|
8
|
+
retryAfterSeconds;
|
|
9
|
+
constructor(operationId,
|
|
10
|
+
/** HTTP status; `0` when no response arrived. */
|
|
11
|
+
status,
|
|
12
|
+
/** The envelope's `code`, or `TIMEOUT` / `UNREACHABLE` without a response. */
|
|
13
|
+
code, message, fields, details, retryAfterSeconds) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.operationId = operationId;
|
|
16
|
+
this.status = status;
|
|
17
|
+
this.code = code;
|
|
18
|
+
this.fields = fields;
|
|
19
|
+
this.details = details;
|
|
20
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
21
|
+
this.name = 'ApiCallError';
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function defaultHint(err) {
|
|
25
|
+
switch (err.status) {
|
|
26
|
+
case 0:
|
|
27
|
+
return err.code === 'TIMEOUT'
|
|
28
|
+
? 'The call timed out. It may still have run; check its result before calling again.'
|
|
29
|
+
: 'The server could not be reached. Tell the user; do not retry right away.';
|
|
30
|
+
case 400:
|
|
31
|
+
return 'Fix the fields named above and call again.';
|
|
32
|
+
case 401:
|
|
33
|
+
return 'The API key is missing, invalid, expired or revoked. Tell the user; retrying will not help.';
|
|
34
|
+
case 403: {
|
|
35
|
+
const scope = err.details?.requiredScope;
|
|
36
|
+
return scope
|
|
37
|
+
? `The API key lacks the \`${scope}\` scope. Tell the user to grant it; retrying will not help.`
|
|
38
|
+
: 'The caller may not do this. Tell the user; retrying will not help.';
|
|
39
|
+
}
|
|
40
|
+
case 404:
|
|
41
|
+
return 'No such resource, or the key cannot see it. Look the id up with a list tool.';
|
|
42
|
+
case 409:
|
|
43
|
+
return 'This conflicts with the current state. Read the resource again before deciding.';
|
|
44
|
+
case 422:
|
|
45
|
+
return 'The request is well-formed but refused. Read the reason above; do not resend it unchanged.';
|
|
46
|
+
case 429:
|
|
47
|
+
return err.retryAfterSeconds !== undefined
|
|
48
|
+
? `Rate limited for ${formatWait(err.retryAfterSeconds)}. Tell the user; do not retry before then.`
|
|
49
|
+
: 'Rate limited. Tell the user; do not retry right away.';
|
|
50
|
+
case 503:
|
|
51
|
+
return 'A server dependency is unavailable. Tell the user and try again later.';
|
|
52
|
+
default:
|
|
53
|
+
return err.status >= 500 ? 'The server failed. Tell the user; retrying may not help.' : '';
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function formatWait(seconds) {
|
|
57
|
+
if (seconds < 120)
|
|
58
|
+
return `${Math.ceil(seconds)}s`;
|
|
59
|
+
const minutes = Math.ceil(seconds / 60);
|
|
60
|
+
if (minutes < 120)
|
|
61
|
+
return `${minutes} min`;
|
|
62
|
+
return `${Math.floor(minutes / 60)}h ${minutes % 60}min`;
|
|
63
|
+
}
|
|
64
|
+
/** The text a model reads for a failed call: what failed, the field errors, what to do next. */
|
|
65
|
+
export function describeError(err, hint) {
|
|
66
|
+
const status = err.status ? `${err.status} ${err.code}` : err.code;
|
|
67
|
+
const lines = [`${err.operationId} failed: ${status}: ${err.message}`];
|
|
68
|
+
for (const [field, message] of Object.entries(err.fields ?? {})) {
|
|
69
|
+
lines.push(` ${field}: ${message}`);
|
|
70
|
+
}
|
|
71
|
+
const next = hint?.(err) ?? defaultHint(err);
|
|
72
|
+
if (next)
|
|
73
|
+
lines.push(next);
|
|
74
|
+
return lines.join('\n');
|
|
75
|
+
}
|
|
76
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3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IAAI,EAAE,CAAC,GAAG,CAAC,IAAI,WAAW,CAAC,GAAG,CAAC,CAAC;IAC7C,IAAI,IAAI;QAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC3B,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { createMcpServer } from './server.js';
|
|
2
|
+
export type { McpServerOptions, PromptDefinition, ResourceDefinition, SelvaMcpServer } from './server.js';
|
|
3
|
+
export { tool, toolkit, fromOperation, inputFrom } from './tool.js';
|
|
4
|
+
export type { Annotations, DerivedInput, FromOperationOptions, ToolContext, ToolDefinition } from './tool.js';
|
|
5
|
+
export type { Api, ApiClientOptions, BinaryBody, TypedApi, TypedCallArgs, UntypedApi, UntypedCallArgs } from './client.js';
|
|
6
|
+
export { ApiCallError, describeError, type ErrorHint } from './errors.js';
|
|
7
|
+
export { jsonOutput, listOutput, truncate, type ToolImage, type ToolOutput } from './output.js';
|
|
8
|
+
export type { JsonSchema, Operation, ScopeAction } from './spec.js';
|
|
9
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,YAAY,EACX,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,EAClB,cAAc,EACd,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACpE,YAAY,EACX,WAAW,EACX,YAAY,EACZ,oBAAoB,EACpB,WAAW,EACX,cAAc,EACd,MAAM,WAAW,CAAC;AACnB,YAAY,EACX,GAAG,EACH,gBAAgB,EAChB,UAAU,EACV,QAAQ,EACR,aAAa,EACb,UAAU,EACV,eAAe,EACf,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,KAAK,SAAS,EAAE,MAAM,aAAa,CAAC;AAC1E,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,QAAQ,EAAE,KAAK,SAAS,EAAE,KAAK,UAAU,EAAE,MAAM,aAAa,CAAC;AAChG,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { createMcpServer } from './server.js';
|
|
2
|
+
export { tool, toolkit, fromOperation, inputFrom } from './tool.js';
|
|
3
|
+
export { ApiCallError, describeError } from './errors.js';
|
|
4
|
+
export { jsonOutput, listOutput, truncate } from './output.js';
|
|
5
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAO9C,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAiBpE,OAAO,EAAE,YAAY,EAAE,aAAa,EAAkB,MAAM,aAAa,CAAC;AAC1E,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,QAAQ,EAAmC,MAAM,aAAa,CAAC"}
|
package/dist/output.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** What a tool hands back: text for the model, and optionally the same data structured. */
|
|
2
|
+
export interface ToolOutput {
|
|
3
|
+
text: string;
|
|
4
|
+
structured?: Record<string, unknown>;
|
|
5
|
+
/** Pictures for a model that can see, after the text. Clients render PNG, JPEG, GIF and WebP; not SVG. */
|
|
6
|
+
images?: ToolImage[];
|
|
7
|
+
}
|
|
8
|
+
export interface ToolImage {
|
|
9
|
+
/** Base64, no `data:` prefix. */
|
|
10
|
+
data: string;
|
|
11
|
+
mimeType: string;
|
|
12
|
+
}
|
|
13
|
+
/** Roughly 5k tokens: enough for a page of records, small enough to leave room to think. */
|
|
14
|
+
export declare const DEFAULT_MAX_CHARS = 20000;
|
|
15
|
+
export declare function truncate(text: string, maxChars?: number, hint?: string): string;
|
|
16
|
+
/** A JSON body as output: pretty text, bounded, plus the object itself when it is one. */
|
|
17
|
+
export declare function jsonOutput(value: unknown, maxChars?: number): ToolOutput;
|
|
18
|
+
/** One line per item, for list tools that shouldn't spend tokens on whole records. */
|
|
19
|
+
export declare function listOutput<T>(items: T[], line: (item: T) => string, nextCursor?: string): ToolOutput;
|
|
20
|
+
//# sourceMappingURL=output.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"output.d.ts","sourceRoot":"","sources":["../src/output.ts"],"names":[],"mappings":"AAAA,2FAA2F;AAC3F,MAAM,WAAW,UAAU;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,0GAA0G;IAC1G,MAAM,CAAC,EAAE,SAAS,EAAE,CAAC;CACrB;AAED,MAAM,WAAW,SAAS;IACzB,iCAAiC;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;CACjB;AAED,4FAA4F;AAC5F,eAAO,MAAM,iBAAiB,QAAS,CAAC;AAExC,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,SAAoB,EAAE,IAAI,SAAK,GAAG,MAAM,CAItF;AAED,0FAA0F;AAC1F,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,SAAoB,GAAG,UAAU,CAYnF;AAED,sFAAsF;AACtF,wBAAgB,UAAU,CAAC,CAAC,EAC3B,KAAK,EAAE,CAAC,EAAE,EACV,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,MAAM,EACzB,UAAU,CAAC,EAAE,MAAM,GACjB,UAAU,CAIZ"}
|
package/dist/output.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Roughly 5k tokens: enough for a page of records, small enough to leave room to think. */
|
|
2
|
+
export const DEFAULT_MAX_CHARS = 20_000;
|
|
3
|
+
export function truncate(text, maxChars = DEFAULT_MAX_CHARS, hint = '') {
|
|
4
|
+
if (text.length <= maxChars)
|
|
5
|
+
return text;
|
|
6
|
+
const note = `\n… truncated ${text.length - maxChars} characters.${hint ? ` ${hint}` : ''}`;
|
|
7
|
+
return text.slice(0, maxChars) + note;
|
|
8
|
+
}
|
|
9
|
+
/** A JSON body as output: pretty text, bounded, plus the object itself when it is one. */
|
|
10
|
+
export function jsonOutput(value, maxChars = DEFAULT_MAX_CHARS) {
|
|
11
|
+
if (value === undefined)
|
|
12
|
+
return { text: 'Done.' };
|
|
13
|
+
const text = truncate(JSON.stringify(value, null, 2), maxChars, 'Narrow the request, or page with `cursor`.');
|
|
14
|
+
const structured = value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
15
|
+
? value
|
|
16
|
+
: undefined;
|
|
17
|
+
return { text, structured };
|
|
18
|
+
}
|
|
19
|
+
/** One line per item, for list tools that shouldn't spend tokens on whole records. */
|
|
20
|
+
export function listOutput(items, line, nextCursor) {
|
|
21
|
+
const lines = items.length ? items.map(line) : ['Nothing found.'];
|
|
22
|
+
if (nextCursor)
|
|
23
|
+
lines.push(`More results: call again with cursor "${nextCursor}".`);
|
|
24
|
+
return { text: lines.join('\n'), structured: { items, ...(nextCursor && { nextCursor }) } };
|
|
25
|
+
}
|
|
26
|
+
//# sourceMappingURL=output.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"output.js","sourceRoot":"","sources":["../src/output.ts"],"names":[],"mappings":"AAcA,4FAA4F;AAC5F,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC;AAExC,MAAM,UAAU,QAAQ,CAAC,IAAY,EAA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CAAC,IAAI,CAAC,EAAE,UAAU,EAAE,EAAE,KAAK,EAAE,GAAG,CAAC,UAAU,IAAI,EAAE,UAAU,EAAE,CAAC,EAAE,EAAE,CAAC;AAC7F,CAAC"}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { type Api, type ApiClientOptions } from './client.js';
|
|
2
|
+
import { type ErrorHint } from './errors.js';
|
|
3
|
+
import { type ToolDefinition } from './tool.js';
|
|
4
|
+
export interface ResourceDefinition {
|
|
5
|
+
uri: string;
|
|
6
|
+
name: string;
|
|
7
|
+
description?: string;
|
|
8
|
+
mimeType?: string;
|
|
9
|
+
calls: string[];
|
|
10
|
+
read(api: Api): Promise<string>;
|
|
11
|
+
}
|
|
12
|
+
export interface PromptDefinition {
|
|
13
|
+
name: string;
|
|
14
|
+
description?: string;
|
|
15
|
+
arguments?: {
|
|
16
|
+
name: string;
|
|
17
|
+
description?: string;
|
|
18
|
+
required?: boolean;
|
|
19
|
+
}[];
|
|
20
|
+
render(args: Record<string, string>): string;
|
|
21
|
+
}
|
|
22
|
+
export interface McpServerOptions extends Omit<ApiClientOptions, 'apiKey'> {
|
|
23
|
+
/**
|
|
24
|
+
* The key `listen` and `verify` send. `handle` never uses it: each HTTP request brings
|
|
25
|
+
* its own, so a remote caller can't borrow the server's.
|
|
26
|
+
*/
|
|
27
|
+
apiKey?: string;
|
|
28
|
+
name: string;
|
|
29
|
+
version: string;
|
|
30
|
+
/** Read by clients as the server's system prompt: conventions every tool shares. */
|
|
31
|
+
instructions?: string;
|
|
32
|
+
/** The host's own spec, imported at build time. */
|
|
33
|
+
openapi: unknown;
|
|
34
|
+
tools: ToolDefinition<any, any>[];
|
|
35
|
+
resources?: ResourceDefinition[];
|
|
36
|
+
prompts?: PromptDefinition[];
|
|
37
|
+
errorHint?: ErrorHint;
|
|
38
|
+
/** Where the live spec is served, for `verify`. Default `/api/v1/openapi.json`. */
|
|
39
|
+
specPath?: string;
|
|
40
|
+
}
|
|
41
|
+
export interface SelvaMcpServer {
|
|
42
|
+
/** Checks every tool's calls against the live spec: same operations, same scopes. */
|
|
43
|
+
verify(): Promise<void>;
|
|
44
|
+
/** Serves over stdio after `verify` passes. */
|
|
45
|
+
listen(options: {
|
|
46
|
+
transport: 'stdio';
|
|
47
|
+
verify?: boolean;
|
|
48
|
+
}): Promise<void>;
|
|
49
|
+
/**
|
|
50
|
+
* Answers one streamable-HTTP request, stateless, with the request's own bearer key.
|
|
51
|
+
* Without one it answers 401. Mount it at `/mcp`.
|
|
52
|
+
*/
|
|
53
|
+
handle(request: Request): Promise<Response>;
|
|
54
|
+
}
|
|
55
|
+
export declare function createMcpServer(options: McpServerOptions): SelvaMcpServer;
|
|
56
|
+
//# sourceMappingURL=server.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAaA,OAAO,EAAmB,KAAK,GAAG,EAAE,KAAK,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/E,OAAO,EAA+B,KAAK,SAAS,EAAE,MAAM,aAAa,CAAC;AAG1E,OAAO,EAKN,KAAK,cAAc,EACnB,MAAM,WAAW,CAAC;AAEnB,MAAM,WAAW,kBAAkB;IAClC,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,IAAI,CAAC,GAAG,EAAE,GAAG,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CAChC;AAED,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;KAAE,EAAE,CAAC;IACzE,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,CAAC;CAC7C;AAED,MAAM,WAAW,gBAAiB,SAAQ,IAAI,CAAC,gBAAgB,EAAE,QAAQ,CAAC;IACzE;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,oFAAoF;IACpF,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,mDAAmD;IACnD,OAAO,EAAE,OAAO,CAAC;IAGjB,KAAK,EAAE,cAAc,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,CAAC;IAClC,SAAS,CAAC,EAAE,kBAAkB,EAAE,CAAC;IACjC,OAAO,CAAC,EAAE,gBAAgB,EAAE,CAAC;IAC7B,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,mFAAmF;IACnF,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAWD,MAAM,WAAW,cAAc;IAC9B,qFAAqF;IACrF,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACxB,+CAA+C;IAC/C,MAAM,CAAC,OAAO,EAAE;QAAE,SAAS,EAAE,OAAO,CAAC;QAAC,MAAM,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACzE;;;OAGG;IACH,MAAM,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CAC5C;AAED,wBAAgB,eAAe,CAAC,OAAO,EAAE,gBAAgB,GAAG,cAAc,CAyLzE"}
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
2
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
3
|
+
import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
|
|
4
|
+
import { CallToolRequestSchema, GetPromptRequestSchema, ListPromptsRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { createApiClient } from './client.js';
|
|
7
|
+
import { ApiCallError, describeError } from './errors.js';
|
|
8
|
+
import { indexOperations } from './spec.js';
|
|
9
|
+
import { annotationsFor, resolveInput } from './tool.js';
|
|
10
|
+
const HEARTBEAT_MS = 15_000;
|
|
11
|
+
export function createMcpServer(options) {
|
|
12
|
+
const spec = indexOperations(options.openapi);
|
|
13
|
+
const tools = resolveTools(options.tools, spec);
|
|
14
|
+
for (const r of options.resources ?? [])
|
|
15
|
+
checkCalls(`resource ${r.uri}`, r.calls, spec);
|
|
16
|
+
function build(apiKey) {
|
|
17
|
+
const clientOptions = { ...options, apiKey };
|
|
18
|
+
// No key may reach the model, even echoed back inside an upstream message.
|
|
19
|
+
const keys = [apiKey, ...(options.apiKey ? [options.apiKey] : [])];
|
|
20
|
+
const redact = (text) => keys.reduce((out, key) => out.split(key).join('[redacted]'), text);
|
|
21
|
+
function toResult(out) {
|
|
22
|
+
return {
|
|
23
|
+
content: [
|
|
24
|
+
{ type: 'text', text: redact(out.text) },
|
|
25
|
+
...(out.images ?? []).map(({ data, mimeType }) => ({
|
|
26
|
+
type: 'image',
|
|
27
|
+
data,
|
|
28
|
+
mimeType
|
|
29
|
+
}))
|
|
30
|
+
],
|
|
31
|
+
...(out.structured && {
|
|
32
|
+
structuredContent: JSON.parse(redact(JSON.stringify(out.structured)))
|
|
33
|
+
})
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
function errorResult(text) {
|
|
37
|
+
return { isError: true, content: [{ type: 'text', text: redact(text) }] };
|
|
38
|
+
}
|
|
39
|
+
const server = new Server({ name: options.name, version: options.version }, {
|
|
40
|
+
capabilities: {
|
|
41
|
+
tools: {},
|
|
42
|
+
...(options.resources?.length && { resources: {} }),
|
|
43
|
+
...(options.prompts?.length && { prompts: {} })
|
|
44
|
+
},
|
|
45
|
+
instructions: options.instructions
|
|
46
|
+
});
|
|
47
|
+
server.setRequestHandler(ListToolsRequestSchema, () => ({
|
|
48
|
+
tools: [...tools.values()].map(({ def, input, annotations }) => ({
|
|
49
|
+
name: def.name,
|
|
50
|
+
title: def.title,
|
|
51
|
+
description: def.description,
|
|
52
|
+
inputSchema: input.schema,
|
|
53
|
+
annotations: { title: def.title, ...annotations }
|
|
54
|
+
}))
|
|
55
|
+
}));
|
|
56
|
+
server.setRequestHandler(CallToolRequestSchema, async (req, extra) => {
|
|
57
|
+
const resolved = tools.get(req.params.name);
|
|
58
|
+
if (!resolved)
|
|
59
|
+
return errorResult(`Unknown tool ${req.params.name}.`);
|
|
60
|
+
const token = extra._meta?.progressToken;
|
|
61
|
+
const started = Date.now();
|
|
62
|
+
let tick = 0;
|
|
63
|
+
// Solves hold the request open for minutes; without a heartbeat some clients give up.
|
|
64
|
+
const heartbeat = token === undefined
|
|
65
|
+
? undefined
|
|
66
|
+
: setInterval(() => {
|
|
67
|
+
void extra
|
|
68
|
+
.sendNotification({
|
|
69
|
+
method: 'notifications/progress',
|
|
70
|
+
params: {
|
|
71
|
+
progressToken: token,
|
|
72
|
+
progress: ++tick,
|
|
73
|
+
message: `Still working (${Math.round((Date.now() - started) / 1000)}s)`
|
|
74
|
+
}
|
|
75
|
+
})
|
|
76
|
+
.catch(() => { });
|
|
77
|
+
}, HEARTBEAT_MS);
|
|
78
|
+
try {
|
|
79
|
+
const api = createApiClient(spec, clientOptions, new Set(resolved.def.calls));
|
|
80
|
+
const args = resolved.input.parse(req.params.arguments ?? {});
|
|
81
|
+
const out = await resolved.def.run(api, args, { signal: extra.signal, spec });
|
|
82
|
+
return toResult(typeof out === 'string' ? { text: out } : out);
|
|
83
|
+
}
|
|
84
|
+
catch (err) {
|
|
85
|
+
return errorResult(describe(err, resolved.def.errorHint ?? options.errorHint));
|
|
86
|
+
}
|
|
87
|
+
finally {
|
|
88
|
+
clearInterval(heartbeat);
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
if (options.resources?.length) {
|
|
92
|
+
const resources = options.resources;
|
|
93
|
+
server.setRequestHandler(ListResourcesRequestSchema, () => ({
|
|
94
|
+
resources: resources.map(({ uri, name, description, mimeType }) => ({
|
|
95
|
+
uri,
|
|
96
|
+
name,
|
|
97
|
+
description,
|
|
98
|
+
mimeType
|
|
99
|
+
}))
|
|
100
|
+
}));
|
|
101
|
+
server.setRequestHandler(ReadResourceRequestSchema, async (req) => {
|
|
102
|
+
const resource = resources.find((r) => r.uri === req.params.uri);
|
|
103
|
+
if (!resource)
|
|
104
|
+
throw new Error(`Unknown resource ${req.params.uri}`);
|
|
105
|
+
const api = createApiClient(spec, clientOptions, new Set(resource.calls));
|
|
106
|
+
const text = redact(await resource.read(api));
|
|
107
|
+
return { contents: [{ uri: resource.uri, mimeType: resource.mimeType, text }] };
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
if (options.prompts?.length) {
|
|
111
|
+
const prompts = options.prompts;
|
|
112
|
+
server.setRequestHandler(ListPromptsRequestSchema, () => ({
|
|
113
|
+
prompts: prompts.map(({ name, description, arguments: args }) => ({
|
|
114
|
+
name,
|
|
115
|
+
description,
|
|
116
|
+
arguments: args
|
|
117
|
+
}))
|
|
118
|
+
}));
|
|
119
|
+
server.setRequestHandler(GetPromptRequestSchema, (req) => {
|
|
120
|
+
const prompt = prompts.find((p) => p.name === req.params.name);
|
|
121
|
+
if (!prompt)
|
|
122
|
+
throw new Error(`Unknown prompt ${req.params.name}`);
|
|
123
|
+
const text = prompt.render(req.params.arguments ?? {});
|
|
124
|
+
return { messages: [{ role: 'user', content: { type: 'text', text } }] };
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
return server;
|
|
128
|
+
}
|
|
129
|
+
function configuredKey() {
|
|
130
|
+
if (!options.apiKey)
|
|
131
|
+
throw new Error('`listen` and `verify` need `apiKey`');
|
|
132
|
+
return options.apiKey;
|
|
133
|
+
}
|
|
134
|
+
async function verify() {
|
|
135
|
+
const doFetch = options.fetch ?? fetch;
|
|
136
|
+
const url = options.baseUrl.replace(/\/$/, '') + (options.specPath ?? '/api/v1/openapi.json');
|
|
137
|
+
const res = await doFetch(url, { headers: { Authorization: `Bearer ${configuredKey()}` } });
|
|
138
|
+
if (!res.ok)
|
|
139
|
+
throw new Error(`Could not read the host's API document at ${url}: HTTP ${res.status}`);
|
|
140
|
+
const live = indexOperations(await res.json());
|
|
141
|
+
const problems = [];
|
|
142
|
+
const calls = new Set([
|
|
143
|
+
...options.tools.flatMap((t) => t.calls),
|
|
144
|
+
...(options.resources ?? []).flatMap((r) => r.calls)
|
|
145
|
+
]);
|
|
146
|
+
for (const id of calls) {
|
|
147
|
+
const want = spec.get(id);
|
|
148
|
+
const have = live.get(id);
|
|
149
|
+
if (!have)
|
|
150
|
+
problems.push(`${id} is missing`);
|
|
151
|
+
else if (have.scope !== want.scope)
|
|
152
|
+
problems.push(`${id} needs \`${have.scope}\`, not \`${want.scope}\``);
|
|
153
|
+
else if (have.method !== want.method || have.path !== want.path) {
|
|
154
|
+
problems.push(`${id} moved to ${have.method} ${have.path}`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (problems.length) {
|
|
158
|
+
throw new Error(`This MCP server does not match the host at ${options.baseUrl}; upgrade whichever is older.\n` +
|
|
159
|
+
problems.join('\n'));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return {
|
|
163
|
+
verify,
|
|
164
|
+
async listen({ verify: check = true }) {
|
|
165
|
+
const apiKey = configuredKey();
|
|
166
|
+
if (check)
|
|
167
|
+
await verify();
|
|
168
|
+
await build(apiKey).connect(new StdioServerTransport());
|
|
169
|
+
},
|
|
170
|
+
async handle(request) {
|
|
171
|
+
const apiKey = bearerOf(request);
|
|
172
|
+
if (!apiKey)
|
|
173
|
+
return keyRequired();
|
|
174
|
+
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
175
|
+
sessionIdGenerator: undefined
|
|
176
|
+
});
|
|
177
|
+
await build(apiKey).connect(transport);
|
|
178
|
+
return transport.handleRequest(request);
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
function bearerOf(request) {
|
|
183
|
+
return /^Bearer\s+(\S+)\s*$/i.exec(request.headers.get('Authorization') ?? '')?.[1];
|
|
184
|
+
}
|
|
185
|
+
function keyRequired() {
|
|
186
|
+
return new Response(JSON.stringify({
|
|
187
|
+
message: 'Send an API key as `Authorization: Bearer <key>`.',
|
|
188
|
+
code: 'UNAUTHORIZED'
|
|
189
|
+
}), { status: 401, headers: { 'Content-Type': 'application/json', 'WWW-Authenticate': 'Bearer' } });
|
|
190
|
+
}
|
|
191
|
+
function resolveTools(
|
|
192
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
193
|
+
defs, spec) {
|
|
194
|
+
const tools = new Map();
|
|
195
|
+
for (const def of defs) {
|
|
196
|
+
if (tools.has(def.name))
|
|
197
|
+
throw new Error(`Two tools are named ${def.name}`);
|
|
198
|
+
if (!def.calls.length)
|
|
199
|
+
throw new Error(`Tool ${def.name} declares no \`calls\``);
|
|
200
|
+
checkCalls(`tool ${def.name}`, def.calls, spec);
|
|
201
|
+
tools.set(def.name, {
|
|
202
|
+
def,
|
|
203
|
+
input: resolveInput(def.input, spec),
|
|
204
|
+
annotations: annotationsFor(def.calls, spec)
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
return tools;
|
|
208
|
+
}
|
|
209
|
+
function checkCalls(owner, calls, spec) {
|
|
210
|
+
for (const id of calls) {
|
|
211
|
+
const op = spec.get(id);
|
|
212
|
+
if (!op)
|
|
213
|
+
throw new Error(`${owner} calls ${id}, which is not in the host's OpenAPI document`);
|
|
214
|
+
// Internal operations carry no stability promise; a tool built on one breaks silently.
|
|
215
|
+
if (op.internal)
|
|
216
|
+
throw new Error(`${owner} calls ${id}, which is x-internal`);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
function describe(err, hint) {
|
|
220
|
+
if (err instanceof ApiCallError)
|
|
221
|
+
return describeError(err, hint);
|
|
222
|
+
if (err instanceof z.ZodError) {
|
|
223
|
+
const issues = err.issues.map((i) => ` ${i.path.join('.') || '(input)'}: ${i.message}`);
|
|
224
|
+
return ['Invalid arguments:', ...issues, 'Fix them and call again.'].join('\n');
|
|
225
|
+
}
|
|
226
|
+
return err instanceof Error ? err.message : String(err);
|
|
227
|
+
}
|
|
228
|
+
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EAAE,wCAAwC,EAAE,MAAM,+DAA+D,CAAC;AACzH,OAAO,EACN,qBAAqB,EACrB,sBAAsB,EACtB,wBAAwB,EACxB,0BAA0B,EAC1B,sBAAsB,EACtB,yBAAyB,EAEzB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,eAAe,EAAmC,MAAM,aAAa,CAAC;AAC/E,OAAO,EAAE,YAAY,EAAE,aAAa,EAAkB,MAAM,aAAa,CAAC;AAE1E,OAAO,EAAE,eAAe,EAAuB,MAAM,WAAW,CAAC;AACjE,OAAO,EACN,cAAc,EACd,YAAY,EAIZ,MAAM,WAAW,CAAC;AA+CnB,MAAM,YAAY,GAAG,MAAM,CAAC;AAc5B,MAAM,UAAU,eAAe,CAAC,OAAyB;IACxD,MAAM,IAAI,GAAG,eAAe,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAC9C,MAAM,KAAK,GAAG,YAAY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C,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACzD,CAAC"}
|
package/dist/spec.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads the parts of a host's OpenAPI document the engine relies on: what
|
|
3
|
+
* `buildOpenApiDocument` in `@selvajs/server/api` emits. Anything else in the
|
|
4
|
+
* document is ignored, so a host can describe more without the engine caring.
|
|
5
|
+
*/
|
|
6
|
+
export type ScopeAction = 'read' | 'write' | 'solve';
|
|
7
|
+
/** A JSON Schema object, as the spec carries it. */
|
|
8
|
+
export type JsonSchema = Record<string, unknown>;
|
|
9
|
+
export interface Operation {
|
|
10
|
+
operationId: string;
|
|
11
|
+
method: string;
|
|
12
|
+
/** Full path including the base, e.g. `/api/v1/definitions/{guid}`. */
|
|
13
|
+
path: string;
|
|
14
|
+
summary: string;
|
|
15
|
+
scope: ScopeAction;
|
|
16
|
+
internal: boolean;
|
|
17
|
+
idempotent: boolean;
|
|
18
|
+
pathParams: string[];
|
|
19
|
+
queryParams: {
|
|
20
|
+
name: string;
|
|
21
|
+
description?: string;
|
|
22
|
+
schema: JsonSchema;
|
|
23
|
+
}[];
|
|
24
|
+
/** JSON body schema. Absent for no body; multipart bodies are not callable as tools. */
|
|
25
|
+
body?: JsonSchema;
|
|
26
|
+
multipart: boolean;
|
|
27
|
+
paginated: boolean;
|
|
28
|
+
}
|
|
29
|
+
export type OperationIndex = ReadonlyMap<string, Operation>;
|
|
30
|
+
export declare function indexOperations(document: unknown): OperationIndex;
|
|
31
|
+
//# sourceMappingURL=spec.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"spec.d.ts","sourceRoot":"","sources":["../src/spec.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC;AAErD,oDAAoD;AACpD,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAEjD,MAAM,WAAW,SAAS;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,uEAAuE;IACvE,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,WAAW,CAAC;IACnB,QAAQ,EAAE,OAAO,CAAC;IAClB,UAAU,EAAE,OAAO,CAAC;IACpB,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,WAAW,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,UAAU,CAAA;KAAE,EAAE,CAAC;IAC1E,wFAAwF;IACxF,IAAI,CAAC,EAAE,UAAU,CAAC;IAClB,SAAS,EAAE,OAAO,CAAC;IACnB,SAAS,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,MAAM,cAAc,GAAG,WAAW,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;AA0B5D,wBAAgB,eAAe,CAAC,QAAQ,EAAE,OAAO,GAAG,cAAc,CAqCjE"}
|
package/dist/spec.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads the parts of a host's OpenAPI document the engine relies on: what
|
|
3
|
+
* `buildOpenApiDocument` in `@selvajs/server/api` emits. Anything else in the
|
|
4
|
+
* document is ignored, so a host can describe more without the engine caring.
|
|
5
|
+
*/
|
|
6
|
+
const METHODS = new Set(['get', 'post', 'put', 'patch', 'delete']);
|
|
7
|
+
export function indexOperations(document) {
|
|
8
|
+
const doc = document;
|
|
9
|
+
const shared = doc.components?.parameters ?? {};
|
|
10
|
+
const resolve = (p) => p.$ref ? (shared[p.$ref.replace('#/components/parameters/', '')] ?? {}) : p;
|
|
11
|
+
const index = new Map();
|
|
12
|
+
for (const [path, ops] of Object.entries(doc.paths ?? {})) {
|
|
13
|
+
for (const [method, op] of Object.entries(ops)) {
|
|
14
|
+
if (!METHODS.has(method) || !op.operationId)
|
|
15
|
+
continue;
|
|
16
|
+
// Without `x-scope` the annotations would be guesses; refuse the document instead.
|
|
17
|
+
if (!op['x-scope']) {
|
|
18
|
+
throw new Error(`${op.operationId} has no x-scope: build the spec with @selvajs/server/api`);
|
|
19
|
+
}
|
|
20
|
+
const params = (op.parameters ?? []).map(resolve);
|
|
21
|
+
const content = op.requestBody?.content ?? {};
|
|
22
|
+
index.set(op.operationId, {
|
|
23
|
+
operationId: op.operationId,
|
|
24
|
+
method: method.toUpperCase(),
|
|
25
|
+
path,
|
|
26
|
+
summary: op.summary ?? '',
|
|
27
|
+
scope: op['x-scope'],
|
|
28
|
+
internal: op['x-internal'] === true,
|
|
29
|
+
idempotent: params.some((p) => p.in === 'header' && p.name === 'Idempotency-Key'),
|
|
30
|
+
pathParams: params.filter((p) => p.in === 'path').map((p) => p.name),
|
|
31
|
+
queryParams: params
|
|
32
|
+
.filter((p) => p.in === 'query')
|
|
33
|
+
.map((p) => ({ name: p.name, description: p.description, schema: p.schema ?? {} })),
|
|
34
|
+
body: content['application/json']?.schema,
|
|
35
|
+
multipart: 'multipart/form-data' in content,
|
|
36
|
+
paginated: params.some((p) => p.in === 'query' && p.name === 'cursor')
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return index;
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=spec.js.map
|
package/dist/spec.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"spec.js","sourceRoot":"","sources":["../src/spec.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAgDH,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC;AAEnE,MAAM,UAAU,eAAe,CAAC,QAAiB;IAChD,MAAM,GAAG,GAAG,QAAuB,CAAC;IACpC,MAA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S,CAAC;gBACpB,QAAQ,EAAE,EAAE,CAAC,YAAY,CAAC,KAAK,IAAI;gBACnC,UAAU,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,QAAQ,IAAI,CAAC,CAAC,IAAI,KAAK,iBAAiB,CAAC;gBACjF,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAK,CAAC;gBACrE,WAAW,EAAE,MAAM;qBACjB,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,OAAO,CAAC;qBAC/B,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,IAAK,EAAE,WAAW,EAAE,CAAC,CAAC,WAAW,EAAE,MAAM,EAAE,CAAC,CAAC,MAAM,IAAI,EAAE,EAAE,CAAC,CAAC;gBACrF,IAAI,EAAE,OAAO,CAAC,kBAAkB,CAAC,EAAE,MAAM;gBACzC,SAAS,EAAE,qBAAqB,IAAI,OAAO;gBAC3C,SAAS,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,OAAO,IAAI,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC;aACtE,CAAC,CAAC;QACJ,CAAC;IACF,CAAC;IACD,OAAO,KAAK,CAAC;AACd,CAAC"}
|
package/dist/tool.d.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { type ZodType } from 'zod';
|
|
2
|
+
import type { Api } from './client.js';
|
|
3
|
+
import type { ErrorHint } from './errors.js';
|
|
4
|
+
import { type ToolOutput } from './output.js';
|
|
5
|
+
import type { JsonSchema, OperationIndex } from './spec.js';
|
|
6
|
+
export interface ToolContext {
|
|
7
|
+
signal: AbortSignal;
|
|
8
|
+
/** The host's operations, for tools that read the spec at run time. */
|
|
9
|
+
spec: OperationIndex;
|
|
10
|
+
}
|
|
11
|
+
/** A tool's input, derived from an operation once the spec is known. See `inputFrom`. */
|
|
12
|
+
export interface DerivedInput {
|
|
13
|
+
kind: 'derived';
|
|
14
|
+
operationId: string;
|
|
15
|
+
omit: string[];
|
|
16
|
+
extend: Record<string, JsonSchema>;
|
|
17
|
+
required: string[];
|
|
18
|
+
}
|
|
19
|
+
export interface ToolDefinition<Ops = never, Args = Record<string, unknown>> {
|
|
20
|
+
name: string;
|
|
21
|
+
title?: string;
|
|
22
|
+
/** When to use it, what to call first, what it returns. The model picks tools by this. */
|
|
23
|
+
description: string;
|
|
24
|
+
/** A Zod schema validates and types `args`; JSON Schema and derived inputs pass args through. */
|
|
25
|
+
input: ZodType<Args> | JsonSchema | DerivedInput;
|
|
26
|
+
/** Every operationId `run` may call. Annotations derive from these; `api.call` refuses others. */
|
|
27
|
+
calls: string[];
|
|
28
|
+
run(api: Api<Ops>, args: Args, ctx: ToolContext): Promise<ToolOutput | string>;
|
|
29
|
+
errorHint?: ErrorHint;
|
|
30
|
+
}
|
|
31
|
+
export declare function tool<Ops = never, Args = Record<string, unknown>>(def: ToolDefinition<Ops, Args>): ToolDefinition<Ops, Args>;
|
|
32
|
+
/**
|
|
33
|
+
* The input schema of an operation, flattened: path params, query params and
|
|
34
|
+
* JSON body fields side by side. `omit` drops fields the tool fills itself;
|
|
35
|
+
* `extend` adds tool-only ones.
|
|
36
|
+
*/
|
|
37
|
+
export declare function inputFrom(operationId: string, options?: {
|
|
38
|
+
omit?: string[];
|
|
39
|
+
extend?: Record<string, JsonSchema>;
|
|
40
|
+
required?: string[];
|
|
41
|
+
}): DerivedInput;
|
|
42
|
+
export interface FromOperationOptions {
|
|
43
|
+
name: string;
|
|
44
|
+
title?: string;
|
|
45
|
+
/** Defaults to the operation's summary, which rarely says enough for a model. */
|
|
46
|
+
description?: string;
|
|
47
|
+
/**
|
|
48
|
+
* Shapes the success body for the model. With one, the tool takes
|
|
49
|
+
* `detail: 'full'` to get the raw body instead.
|
|
50
|
+
*/
|
|
51
|
+
shape?: (body: unknown, args: Record<string, unknown>) => ToolOutput | string;
|
|
52
|
+
/** Page size for a paginated operation when the model doesn't pass `limit`. Default 20. */
|
|
53
|
+
limit?: number;
|
|
54
|
+
omit?: string[];
|
|
55
|
+
errorHint?: ErrorHint;
|
|
56
|
+
}
|
|
57
|
+
/** One tool calling one operation, its arguments split back into path, query and body. */
|
|
58
|
+
export declare function fromOperation(operationId: string, options: FromOperationOptions): ToolDefinition<never, Record<string, unknown>>;
|
|
59
|
+
/** Binds the host's generated `operations` type once, so each tool needn't repeat it. */
|
|
60
|
+
export declare function toolkit<Ops>(): {
|
|
61
|
+
tool: <Args = Record<string, unknown>>(def: ToolDefinition<Ops, Args>) => ToolDefinition<Ops, Args>;
|
|
62
|
+
fromOperation: (operationId: Extract<keyof Ops, string>, options: FromOperationOptions) => ToolDefinition<never, Record<string, unknown>>;
|
|
63
|
+
};
|
|
64
|
+
export interface ResolvedInput {
|
|
65
|
+
schema: JsonSchema;
|
|
66
|
+
parse(args: unknown): unknown;
|
|
67
|
+
}
|
|
68
|
+
export declare function resolveInput(input: ToolDefinition<unknown, unknown>['input'], spec: OperationIndex): ResolvedInput;
|
|
69
|
+
export interface Annotations {
|
|
70
|
+
readOnlyHint: boolean;
|
|
71
|
+
destructiveHint: boolean;
|
|
72
|
+
idempotentHint: boolean;
|
|
73
|
+
openWorldHint: boolean;
|
|
74
|
+
}
|
|
75
|
+
/** The most permissive of a tool's calls wins: one `solve` makes the whole tool open-world. */
|
|
76
|
+
export declare function annotationsFor(calls: string[], spec: OperationIndex): Annotations;
|
|
77
|
+
//# sourceMappingURL=tool.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../src/t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MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;EAEpD;AAMD,MAAM,WAAW,aAAa;IAC7B,MAAM,EAAE,UAAU,CAAC;IACnB,KAAK,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAAC;CAC9B;AAED,wBAAgB,YAAY,CAC3B,KAAK,EAAE,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,EAChD,IAAI,EAAE,cAAc,GAClB,aAAa,CAUf;AAyCD,MAAM,WAAW,WAAW;IAC3B,YAAY,EAAE,OAAO,CAAC;IACtB,eAAe,EAAE,OAAO,CAAC;IACzB,cAAc,EAAE,OAAO,CAAC;IACxB,aAAa,EAAE,OAAO,CAAC;CACvB;AAED,+FAA+F;AAC/F,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,cAAc,GAAG,WAAW,CAUjF"}
|
package/dist/tool.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { jsonOutput } from './output.js';
|
|
3
|
+
export function tool(def) {
|
|
4
|
+
return def;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* The input schema of an operation, flattened: path params, query params and
|
|
8
|
+
* JSON body fields side by side. `omit` drops fields the tool fills itself;
|
|
9
|
+
* `extend` adds tool-only ones.
|
|
10
|
+
*/
|
|
11
|
+
export function inputFrom(operationId, options = {}) {
|
|
12
|
+
return {
|
|
13
|
+
kind: 'derived',
|
|
14
|
+
operationId,
|
|
15
|
+
omit: options.omit ?? [],
|
|
16
|
+
extend: options.extend ?? {},
|
|
17
|
+
required: options.required ?? []
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
const DETAIL = {
|
|
21
|
+
type: 'string',
|
|
22
|
+
enum: ['summary', 'full'],
|
|
23
|
+
description: '`full` returns the raw response instead of the summary. Default `summary`.'
|
|
24
|
+
};
|
|
25
|
+
/** One tool calling one operation, its arguments split back into path, query and body. */
|
|
26
|
+
export function fromOperation(operationId, options) {
|
|
27
|
+
return {
|
|
28
|
+
name: options.name,
|
|
29
|
+
title: options.title,
|
|
30
|
+
description: options.description ?? '',
|
|
31
|
+
input: inputFrom(operationId, {
|
|
32
|
+
omit: options.omit,
|
|
33
|
+
extend: options.shape ? { detail: DETAIL } : {}
|
|
34
|
+
}),
|
|
35
|
+
calls: [operationId],
|
|
36
|
+
errorHint: options.errorHint,
|
|
37
|
+
async run(api, args, { spec, signal }) {
|
|
38
|
+
const op = spec.get(operationId);
|
|
39
|
+
const { detail, ...rest } = args;
|
|
40
|
+
const params = {};
|
|
41
|
+
const query = {};
|
|
42
|
+
const body = {};
|
|
43
|
+
for (const [key, value] of Object.entries(rest)) {
|
|
44
|
+
if (op.pathParams.includes(key))
|
|
45
|
+
params[key] = String(value);
|
|
46
|
+
else if (op.queryParams.some((q) => q.name === key))
|
|
47
|
+
query[key] = value;
|
|
48
|
+
else
|
|
49
|
+
body[key] = value;
|
|
50
|
+
}
|
|
51
|
+
if (op.paginated && query.limit === undefined)
|
|
52
|
+
query.limit = options.limit ?? 20;
|
|
53
|
+
const result = await api.call(operationId, {
|
|
54
|
+
params,
|
|
55
|
+
query,
|
|
56
|
+
body: op.body ? body : undefined,
|
|
57
|
+
signal
|
|
58
|
+
});
|
|
59
|
+
if (options.shape && detail !== 'full')
|
|
60
|
+
return options.shape(result, args);
|
|
61
|
+
return jsonOutput(result);
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/** Binds the host's generated `operations` type once, so each tool needn't repeat it. */
|
|
66
|
+
export function toolkit() {
|
|
67
|
+
return {
|
|
68
|
+
tool: (def) => def,
|
|
69
|
+
fromOperation: fromOperation
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
export function resolveInput(input, spec) {
|
|
73
|
+
if (input instanceof z.ZodType) {
|
|
74
|
+
const schema = z.toJSONSchema(input, { io: 'input', target: 'draft-2020-12' });
|
|
75
|
+
delete schema.$schema;
|
|
76
|
+
return { schema, parse: (args) => input.parse(args) };
|
|
77
|
+
}
|
|
78
|
+
if (input.kind === 'derived') {
|
|
79
|
+
return { schema: derive(input, spec), parse: (args) => args ?? {} };
|
|
80
|
+
}
|
|
81
|
+
return { schema: input, parse: (args) => args ?? {} };
|
|
82
|
+
}
|
|
83
|
+
function derive(input, spec) {
|
|
84
|
+
const op = spec.get(input.operationId);
|
|
85
|
+
if (!op)
|
|
86
|
+
throw new Error(`inputFrom: ${input.operationId} is not in the host's OpenAPI document`);
|
|
87
|
+
if (op.multipart)
|
|
88
|
+
throw new Error(`inputFrom: ${input.operationId} takes multipart, not JSON`);
|
|
89
|
+
const properties = {};
|
|
90
|
+
const required = new Set(input.required);
|
|
91
|
+
const add = (name, schema) => {
|
|
92
|
+
if (name in properties) {
|
|
93
|
+
throw new Error(`inputFrom: ${input.operationId} has two inputs named \`${name}\``);
|
|
94
|
+
}
|
|
95
|
+
properties[name] = schema;
|
|
96
|
+
};
|
|
97
|
+
for (const name of op.pathParams) {
|
|
98
|
+
add(name, { type: 'string' });
|
|
99
|
+
required.add(name);
|
|
100
|
+
}
|
|
101
|
+
for (const q of op.queryParams) {
|
|
102
|
+
add(q.name, q.description ? { ...q.schema, description: q.description } : q.schema);
|
|
103
|
+
}
|
|
104
|
+
const bodyProps = (op.body?.properties ?? {});
|
|
105
|
+
for (const [name, schema] of Object.entries(bodyProps))
|
|
106
|
+
add(name, schema);
|
|
107
|
+
for (const name of op.body?.required ?? [])
|
|
108
|
+
required.add(name);
|
|
109
|
+
for (const name of input.omit) {
|
|
110
|
+
delete properties[name];
|
|
111
|
+
required.delete(name);
|
|
112
|
+
}
|
|
113
|
+
Object.assign(properties, input.extend);
|
|
114
|
+
return {
|
|
115
|
+
type: 'object',
|
|
116
|
+
properties,
|
|
117
|
+
...(required.size && { required: [...required] }),
|
|
118
|
+
...(op.body && op.body.additionalProperties === false && { additionalProperties: false })
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/** The most permissive of a tool's calls wins: one `solve` makes the whole tool open-world. */
|
|
122
|
+
export function annotationsFor(calls, spec) {
|
|
123
|
+
const ops = calls.map((id) => spec.get(id));
|
|
124
|
+
return {
|
|
125
|
+
readOnlyHint: ops.every((op) => op.scope === 'read'),
|
|
126
|
+
destructiveHint: ops.some((op) => op.method === 'DELETE'),
|
|
127
|
+
idempotentHint: ops.every((op) => op.idempotent || op.method === 'GET' || op.method === 'PUT' || op.method === 'DELETE'),
|
|
128
|
+
openWorldHint: ops.some((op) => op.scope === 'solve')
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
//# sourceMappingURL=tool.js.map
|
package/dist/tool.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool.js","sourceRoot":"","sources":["../src/tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAgB,MAAM,KAAK,CAAC;AAGtC,OAAO,EAAE,UAAU,EAAmB,MAAM,aAAa,CAAC;AA+B1D,MAAM,UAAU,IAAI,CACnB,GAA8B;IAE9B,OAAO,GAAG,CAAC;AACZ,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,SAAS,CACxB,WAAmB,EACnB,UAAyF,EAAE;IAE3F,OAAO;QACN,IAAI,EAAE,SAAS;QACf,WAAW;QACX,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,EAAE;QACxB,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,EAAE;QAC5B,QAAQ,EAAE,OAAO,CAAC,QAAQ,IAAI,EAAE;KAChC,CAAC;AACH,CAAC;AAkBD,MAAM,MAAM,GAAe;IAC1B,IAAI,EAAE,QAAQ;IACd,IAAI,EAAE,CAAC,SAAS,EAAE,MAAM,CAAC;IACzB,WAAW,EAAE,4EAA4E;CACzF,CAAC;AAEF,0FAA0F;AAC1F,MAAM,UAAU,aAAa,CAC5B,WAAmB,EACnB,OAA6B;IAE7B,OAAO;QACN,IAAI,EAAE,OAAO,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E,CAAC,KAAK,KAAK,MAAM,CAAC;QACpD,eAAe,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,MAAM,KAAK,QAAQ,CAAC;QACzD,cAAc,EAAE,GAAG,CAAC,KAAK,CACxB,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,UAAU,IAAI,EAAE,CAAC,MAAM,KAAK,KAAK,IAAI,EAAE,CAAC,MAAM,KAAK,KAAK,IAAI,EAAE,CAAC,MAAM,KAAK,QAAQ,CAC7F;QACD,aAAa,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,KAAK,KAAK,OAAO,CAAC;KACrD,CAAC;AACH,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,62 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@selvajs/mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0-beta.1",
|
|
4
|
+
"description": "MCP server machinery for Selva hosts: tools over a host's /api/v1, with key auth, error mapping and annotations from its OpenAPI document",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "VektorNode",
|
|
7
|
+
"homepage": "https://selva.dev",
|
|
8
|
+
"bugs": "https://github.com/VektorNode/selva/issues",
|
|
9
|
+
"keywords": [
|
|
10
|
+
"selva",
|
|
11
|
+
"mcp",
|
|
12
|
+
"model-context-protocol",
|
|
13
|
+
"openapi"
|
|
14
|
+
],
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/VektorNode/selva.git",
|
|
18
|
+
"directory": "packages/mcp"
|
|
19
|
+
},
|
|
20
|
+
"publishConfig": {
|
|
21
|
+
"access": "public"
|
|
22
|
+
},
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=24.0.0"
|
|
25
|
+
},
|
|
26
|
+
"type": "module",
|
|
27
|
+
"main": "./dist/index.js",
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"selva-source": "./src/index.ts",
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"import": "./dist/index.js"
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"files": [
|
|
37
|
+
"dist",
|
|
38
|
+
"!**/__tests__/**",
|
|
39
|
+
"!**/*.test.*",
|
|
40
|
+
"!**/*.spec.*"
|
|
41
|
+
],
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"@modelcontextprotocol/sdk": "^1.30.1",
|
|
44
|
+
"zod": "^4.6.5"
|
|
45
|
+
},
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"@types/node": "^26.6.2",
|
|
48
|
+
"typescript": "~6.0.3",
|
|
49
|
+
"vitest": "^5.0.2",
|
|
50
|
+
"@selvajs/config": "0.0.4",
|
|
51
|
+
"@selvajs/server": "1.5.0-beta.5"
|
|
52
|
+
},
|
|
53
|
+
"scripts": {
|
|
54
|
+
"build": "tsc",
|
|
55
|
+
"dev": "tsc --watch",
|
|
56
|
+
"type-check": "tsc --noEmit",
|
|
57
|
+
"test": "vitest run",
|
|
58
|
+
"test:watch": "vitest",
|
|
59
|
+
"lint": "eslint .",
|
|
60
|
+
"lint:types": "eslint . --config eslint.typed.config.js"
|
|
61
|
+
}
|
|
6
62
|
}
|