@ultimat3/mcp 29.4.0 → 30.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.
Files changed (63) hide show
  1. package/CLAUDE.md +54 -59
  2. package/README.md +259 -2
  3. package/package.json +21 -10
  4. package/src/app-catalog.ts +84 -0
  5. package/src/app-tool.ts +6 -2
  6. package/src/app-tools.ts +80 -5
  7. package/src/audit-hook.ts +7 -1
  8. package/src/audit.ts +12 -1
  9. package/src/catalog-errors.ts +97 -0
  10. package/src/confirmation-approvers.ts +85 -0
  11. package/src/confirmation-decide.ts +78 -8
  12. package/src/confirmation-evidence.ts +118 -0
  13. package/src/confirmation-gate.ts +147 -44
  14. package/src/confirmation-postgres.ts +88 -7
  15. package/src/confirmation-quorum-errors.ts +102 -0
  16. package/src/confirmation-schema.ts +13 -2
  17. package/src/confirmation-store.ts +54 -19
  18. package/src/confirmations.ts +77 -8
  19. package/src/dev-graph-tool.ts +62 -0
  20. package/src/dev-server.ts +10 -2
  21. package/src/errors-transport.ts +84 -3
  22. package/src/errors.ts +46 -0
  23. package/src/exposed.ts +13 -3
  24. package/src/framework-error.ts +8 -1
  25. package/src/from-action.ts +2 -3
  26. package/src/index.ts +102 -1
  27. package/src/job-status-tool.ts +66 -0
  28. package/src/job-tool-errors.ts +15 -0
  29. package/src/job-tool.ts +167 -0
  30. package/src/oauth-metadata.ts +2 -2
  31. package/src/oauth-server.ts +80 -0
  32. package/src/projectable.ts +15 -10
  33. package/src/protocol-era.ts +270 -0
  34. package/src/recipe-errors.ts +75 -0
  35. package/src/recipe-links.ts +49 -0
  36. package/src/recipe-markdown.ts +143 -0
  37. package/src/recipe-replay.ts +101 -0
  38. package/src/recipe-search.ts +82 -0
  39. package/src/recipes-surface.ts +55 -0
  40. package/src/recipes-tool.ts +123 -0
  41. package/src/recipes.ts +167 -0
  42. package/src/registry.ts +5 -0
  43. package/src/remote-client.ts +378 -0
  44. package/src/remote-errors.ts +76 -0
  45. package/src/remote-listen.ts +108 -0
  46. package/src/remote-lock.ts +139 -0
  47. package/src/remote-oauth.ts +258 -0
  48. package/src/remote-schema.ts +51 -0
  49. package/src/remote-tools.ts +157 -0
  50. package/src/remote-wire.ts +121 -0
  51. package/src/resources.ts +84 -13
  52. package/src/runtime-schema.ts +132 -0
  53. package/src/runtime-tool.ts +115 -0
  54. package/src/scopes.ts +8 -1
  55. package/src/server-catalog.ts +200 -0
  56. package/src/server-resources.ts +117 -0
  57. package/src/server-voice.ts +10 -5
  58. package/src/server.ts +149 -168
  59. package/src/tenant.ts +189 -0
  60. package/src/transport-http-answers.ts +124 -0
  61. package/src/transport-http.ts +50 -94
  62. package/src/wire.ts +18 -4
  63. package/src/caller-context.ts +0 -22
@@ -0,0 +1,139 @@
1
+ // `tools.lock.json`: what a person reviewed of each remote MCP server — per allowed tool, the
2
+ // description the model will read and the input schema it will fill, plus `readOnly`, which only a
3
+ // person sets. `x mcp lock <name>` writes it; `mcpTools()` reads it; any difference from the live
4
+ // server is `X_MCP_REMOTE_TOOL_CHANGED`. Deterministic bytes, so a diff is the review.
5
+
6
+ import { isJsonObject } from '@ultimat3/core';
7
+ import type { RemoteTool } from './remote-client';
8
+ import { McpRemoteToolChangedError } from './remote-errors';
9
+
10
+ export const TOOLS_LOCK_FILE = 'tools.lock.json';
11
+
12
+ export interface LockedTool {
13
+ readonly description: string;
14
+ readonly inputSchema: Readonly<Record<string, unknown>>;
15
+ /** Set by a reviewer, never by the remote's hint: `false` keeps the confirmation gate binding. */
16
+ readonly readOnly: boolean;
17
+ }
18
+
19
+ export interface LockedServer {
20
+ readonly url: string;
21
+ readonly tools: ReadonlyMap<string, LockedTool>;
22
+ }
23
+
24
+ /** The parsed lock: server name → its locked tools. Unknown or malformed entries are absent. */
25
+ export function readToolsLock(raw: unknown): ReadonlyMap<string, LockedServer> {
26
+ const servers = new Map<string, LockedServer>();
27
+ const listed = isJsonObject(raw) && isJsonObject(raw['servers']) ? raw['servers'] : {};
28
+ for (const [name, entry] of Object.entries(listed)) {
29
+ if (!isJsonObject(entry) || typeof entry['url'] !== 'string') continue;
30
+ const tools = new Map<string, LockedTool>();
31
+ for (const [tool, value] of Object.entries(
32
+ isJsonObject(entry['tools']) ? entry['tools'] : {},
33
+ )) {
34
+ if (!isJsonObject(value) || !isJsonObject(value['inputSchema'])) continue;
35
+ tools.set(tool, {
36
+ description: typeof value['description'] === 'string' ? value['description'] : '',
37
+ inputSchema: value['inputSchema'],
38
+ readOnly: value['readOnly'] === true,
39
+ });
40
+ }
41
+ servers.set(name, { url: entry['url'], tools });
42
+ }
43
+ return servers;
44
+ }
45
+
46
+ /** Why the live tools differ from the locked ones, one line per change; empty when they agree. */
47
+ export function lockChanges(
48
+ locked: LockedServer | undefined,
49
+ url: string,
50
+ allow: readonly string[],
51
+ live?: readonly RemoteTool[],
52
+ ): readonly string[] {
53
+ if (locked === undefined) return ['no entry in tools.lock.json'];
54
+ const changes: string[] = [];
55
+ if (locked.url !== url) changes.push(`url is ${url}, the lock has ${locked.url}`);
56
+ const seen = live === undefined ? undefined : new Map(live.map((tool) => [tool.name, tool]));
57
+ for (const name of allow) {
58
+ const entry = locked.tools.get(name);
59
+ if (entry === undefined) {
60
+ changes.push(`"${name}" is allowed but not locked`);
61
+ continue;
62
+ }
63
+ if (seen === undefined) continue;
64
+ const current = seen.get(name);
65
+ if (current === undefined) changes.push(`"${name}" is gone from the server`);
66
+ else if (current.description !== entry.description)
67
+ changes.push(`"${name}" changed its description`);
68
+ else if (canonical(current.inputSchema) !== canonical(entry.inputSchema)) {
69
+ changes.push(`"${name}" changed its input schema`);
70
+ }
71
+ }
72
+ return changes;
73
+ }
74
+
75
+ export function assertLocked(
76
+ server: string,
77
+ locked: LockedServer | undefined,
78
+ url: string,
79
+ allow: readonly string[],
80
+ live?: readonly RemoteTool[],
81
+ ): void {
82
+ const changes = lockChanges(locked, url, allow, live);
83
+ if (changes.length > 0) throw new McpRemoteToolChangedError({ server, changes });
84
+ }
85
+
86
+ /**
87
+ * The lock with `server` rewritten from `live`, keeping every other server and each tool's
88
+ * reviewed `readOnly`. Serialised with sorted keys: the same tools are the same bytes.
89
+ */
90
+ export function writeToolsLock(
91
+ previous: unknown,
92
+ server: string,
93
+ url: string,
94
+ allow: readonly string[],
95
+ live: readonly RemoteTool[],
96
+ ): string {
97
+ const prior = readToolsLock(previous);
98
+ const found = new Map(live.map((tool) => [tool.name, tool]));
99
+ const missing = allow.filter((name) => !found.has(name));
100
+ if (missing.length > 0) {
101
+ throw new McpRemoteToolChangedError({
102
+ server,
103
+ changes: missing.map((name) => `"${name}" is allowed but the server does not list it`),
104
+ });
105
+ }
106
+ const servers = new Map<string, unknown>();
107
+ for (const [name, entry] of prior) servers.set(name, serialisable(entry));
108
+ const tools = new Map<string, LockedTool>();
109
+ for (const name of allow) {
110
+ const tool = found.get(name);
111
+ if (tool === undefined) continue;
112
+ tools.set(name, {
113
+ description: tool.description,
114
+ inputSchema: tool.inputSchema,
115
+ readOnly: prior.get(server)?.tools.get(name)?.readOnly ?? false,
116
+ });
117
+ }
118
+ servers.set(server, serialisable({ url, tools }));
119
+ return `${canonical({ version: 1, servers: Object.fromEntries(servers) }, 2)}\n`;
120
+ }
121
+
122
+ function serialisable(entry: LockedServer): unknown {
123
+ return { url: entry.url, tools: Object.fromEntries(entry.tools) };
124
+ }
125
+
126
+ /** JSON with every object's keys sorted, at any depth. */
127
+ export function canonical(value: unknown, indent?: number): string {
128
+ return JSON.stringify(sortKeys(value), null, indent);
129
+ }
130
+
131
+ function sortKeys(value: unknown): unknown {
132
+ if (Array.isArray(value)) return value.map(sortKeys);
133
+ if (!isJsonObject(value)) return value;
134
+ return Object.fromEntries(
135
+ Object.keys(value)
136
+ .sort()
137
+ .map((key) => [key, sortKeys(value[key])]),
138
+ );
139
+ }
@@ -0,0 +1,258 @@
1
+ /**
2
+ * `mcpOAuthClient()` — this app authorising to ANOTHER server's MCP endpoint per the MCP auth spec:
3
+ * RFC 9728 then RFC 8414 discovery, a client ID metadata document as `client_id`, PKCE S256
4
+ * (`@ultimat3/auth`'s `pkcePair`) and RFC 8707 `resource` in both legs.
5
+ */
6
+
7
+ import { pkcePair, randomToken } from '@ultimat3/auth';
8
+ import { isJsonObject, timingSafeEqual } from '@ultimat3/core';
9
+ import type { OutboundFetch } from '@ultimat3/core/outbound';
10
+ import { outboundResponse } from '@ultimat3/core/outbound';
11
+ import { McpRemoteRefusedError } from './remote-errors';
12
+
13
+ export interface McpOAuthClientOptions {
14
+ /**
15
+ * The client's id: the HTTPS URL its metadata document is served at (serve `metadata()` there),
16
+ * or an id the authorization server issued when this app was registered by hand.
17
+ */
18
+ readonly clientId: string;
19
+ /** Shown to the person on the consent screen. */
20
+ readonly clientName: string;
21
+ /** This app's callback; listed in the metadata document. */
22
+ readonly redirectUri: string;
23
+ /** Asked for when given; else what the server's metadata lists as supported, if anything. */
24
+ readonly scopes?: readonly string[];
25
+ readonly dial?: 'public' | 'named';
26
+ readonly deadlineMs?: number;
27
+ readonly fetch?: OutboundFetch;
28
+ }
29
+
30
+ /** Everything the callback needs — keep it server-side (a sealed cookie, a row), never in a URL. */
31
+ export interface McpOAuthHandshake {
32
+ readonly state: string;
33
+ readonly verifier: string;
34
+ readonly redirectUri: string;
35
+ /** The MCP server's URL: RFC 8707's `resource`, sent in both legs. */
36
+ readonly resource: string;
37
+ readonly tokenEndpoint: string;
38
+ }
39
+
40
+ export interface McpOAuthStart {
41
+ /** Where to send the person. */
42
+ readonly authorizeUrl: string;
43
+ readonly handshake: McpOAuthHandshake;
44
+ }
45
+
46
+ export interface McpOAuthTokens {
47
+ readonly accessToken: string;
48
+ readonly refreshToken: string | null;
49
+ /** Seconds, as the server said; the app stamps its own clock on it. */
50
+ readonly expiresIn: number | null;
51
+ }
52
+
53
+ export interface McpOAuthClient {
54
+ /** The client ID metadata document — serve it, as JSON, at `clientId`. */
55
+ metadata(): Readonly<Record<string, unknown>>;
56
+ begin(serverUrl: string): Promise<McpOAuthStart>;
57
+ exchange(
58
+ handshake: McpOAuthHandshake,
59
+ callback: { readonly code: string; readonly state: string },
60
+ ): Promise<McpOAuthTokens>;
61
+ refresh(
62
+ handshake: Pick<McpOAuthHandshake, 'resource' | 'tokenEndpoint'>,
63
+ refreshToken: string,
64
+ ): Promise<McpOAuthTokens>;
65
+ }
66
+
67
+ const DEFAULT_DEADLINE_MS = 10_000;
68
+
69
+ export function mcpOAuthClient(options: McpOAuthClientOptions): McpOAuthClient {
70
+ const refused = (url: string, reason: string, status?: number) =>
71
+ new McpRemoteRefusedError({
72
+ server: 'oauth',
73
+ url,
74
+ reason,
75
+ failure: status === undefined ? 'malformed' : 'status',
76
+ ...(status === undefined ? {} : { status }),
77
+ });
78
+
79
+ /** One metadata read: the JSON object, or `undefined` for a 404 (the next candidate is tried). */
80
+ const send = (url: string, init: { method?: 'POST'; body?: URLSearchParams }) =>
81
+ outboundResponse(
82
+ {
83
+ url,
84
+ vendor: 'mcp:oauth',
85
+ dial: options.dial ?? 'public',
86
+ deadlineMs: options.deadlineMs ?? DEFAULT_DEADLINE_MS,
87
+ headers: { accept: 'application/json' },
88
+ ...init,
89
+ },
90
+ options.fetch === undefined ? {} : { fetch: options.fetch },
91
+ );
92
+
93
+ /** One metadata read: the JSON object, or `undefined` for a 404 (the next candidate is tried). */
94
+ const getJson = async (url: string): Promise<Record<string, unknown> | undefined> => {
95
+ const answer = await send(url, {});
96
+ if (answer.status === 404) return undefined;
97
+ if (!answer.ok)
98
+ throw refused(url, `answered its metadata with HTTP ${answer.status}`, answer.status);
99
+ const body = parseObject(await answer.text());
100
+ if (body === undefined) throw refused(url, 'answered its metadata with no JSON object');
101
+ return body;
102
+ };
103
+
104
+ const firstOf = async (url: string, candidates: readonly string[]) => {
105
+ for (const candidate of candidates) {
106
+ const found = await getJson(candidate);
107
+ if (found !== undefined) return found;
108
+ }
109
+ throw refused(url, `published no metadata at ${candidates.join(' or ')}`);
110
+ };
111
+
112
+ const token = async (endpoint: string, form: URLSearchParams): Promise<McpOAuthTokens> => {
113
+ const answer = await send(endpoint, { method: 'POST', body: form });
114
+ if (!answer.ok) {
115
+ // The body is not quoted: a token endpoint echoing its request would echo the code.
116
+ throw refused(
117
+ endpoint,
118
+ `refused the token request with HTTP ${answer.status}`,
119
+ answer.status,
120
+ );
121
+ }
122
+ const body = parseObject(await answer.text());
123
+ const access = body?.['access_token'];
124
+ if (body === undefined || typeof access !== 'string' || access === '') {
125
+ throw refused(endpoint, 'answered the token request with no access_token');
126
+ }
127
+ const refresh = body['refresh_token'];
128
+ const expires = body['expires_in'];
129
+ return {
130
+ accessToken: access,
131
+ refreshToken: typeof refresh === 'string' && refresh !== '' ? refresh : null,
132
+ expiresIn: typeof expires === 'number' && Number.isFinite(expires) ? expires : null,
133
+ };
134
+ };
135
+
136
+ return {
137
+ metadata: () => ({
138
+ client_id: options.clientId,
139
+ client_name: options.clientName,
140
+ redirect_uris: [options.redirectUri],
141
+ grant_types: ['authorization_code', 'refresh_token'],
142
+ response_types: ['code'],
143
+ token_endpoint_auth_method: 'none',
144
+ }),
145
+
146
+ async begin(serverUrl) {
147
+ const resource = new URL(serverUrl);
148
+ resource.hash = '';
149
+ const prm = await firstOf(serverUrl, wellKnown(resource, 'oauth-protected-resource'));
150
+ const issuer = Array.isArray(prm['authorization_servers'])
151
+ ? prm['authorization_servers'].find((entry) => typeof entry === 'string')
152
+ : undefined;
153
+ if (typeof issuer !== 'string') {
154
+ throw refused(serverUrl, 'names no authorization server in its resource metadata');
155
+ }
156
+ const as = await firstOf(issuer, authServerCandidates(new URL(issuer)));
157
+ // RFC 8414 §3.3: a document answering for another issuer is not this issuer's.
158
+ if (as['issuer'] !== issuer) throw refused(issuer, 'published metadata for another issuer');
159
+ const authorize = as['authorization_endpoint'];
160
+ const tokenEndpoint = as['token_endpoint'];
161
+ if (typeof authorize !== 'string' || typeof tokenEndpoint !== 'string') {
162
+ throw refused(issuer, 'names no authorization_endpoint or token_endpoint');
163
+ }
164
+ const methods = as['code_challenge_methods_supported'];
165
+ if (!Array.isArray(methods) || !methods.includes('S256')) {
166
+ throw refused(issuer, 'does not offer PKCE S256, which an MCP client must use');
167
+ }
168
+ if (
169
+ options.clientId.startsWith('https://') &&
170
+ as['client_id_metadata_document_supported'] !== true
171
+ ) {
172
+ throw refused(issuer, 'does not accept a client ID metadata document');
173
+ }
174
+ const pkce = pkcePair();
175
+ const state = randomToken(16);
176
+ const url = new URL(authorize);
177
+ const scopes = options.scopes ?? stringList(prm['scopes_supported']);
178
+ url.searchParams.set('response_type', 'code');
179
+ url.searchParams.set('client_id', options.clientId);
180
+ url.searchParams.set('redirect_uri', options.redirectUri);
181
+ url.searchParams.set('state', state);
182
+ url.searchParams.set('code_challenge', pkce.challenge);
183
+ url.searchParams.set('code_challenge_method', pkce.method);
184
+ url.searchParams.set('resource', resource.toString());
185
+ if (scopes.length > 0) url.searchParams.set('scope', scopes.join(' '));
186
+ return {
187
+ authorizeUrl: url.toString(),
188
+ handshake: {
189
+ state,
190
+ verifier: pkce.verifier,
191
+ redirectUri: options.redirectUri,
192
+ resource: resource.toString(),
193
+ tokenEndpoint,
194
+ },
195
+ };
196
+ },
197
+
198
+ exchange(handshake, callback) {
199
+ // The one gate between a redirect and a token: a forged callback carries another state.
200
+ if (!timingSafeEqual(handshake.state, callback.state)) {
201
+ return Promise.reject(refused(handshake.tokenEndpoint, 'came back with another state'));
202
+ }
203
+ return token(
204
+ handshake.tokenEndpoint,
205
+ new URLSearchParams({
206
+ grant_type: 'authorization_code',
207
+ code: callback.code,
208
+ redirect_uri: handshake.redirectUri,
209
+ client_id: options.clientId,
210
+ code_verifier: handshake.verifier,
211
+ resource: handshake.resource,
212
+ }),
213
+ );
214
+ },
215
+
216
+ refresh: (handshake, refreshToken) =>
217
+ token(
218
+ handshake.tokenEndpoint,
219
+ new URLSearchParams({
220
+ grant_type: 'refresh_token',
221
+ refresh_token: refreshToken,
222
+ client_id: options.clientId,
223
+ resource: handshake.resource,
224
+ }),
225
+ ),
226
+ };
227
+ }
228
+
229
+ /** RFC 9728 §3.1: the suffix goes between host and path, then the root as a fallback. */
230
+ function wellKnown(url: URL, suffix: string): readonly string[] {
231
+ const path = url.pathname === '/' ? '' : url.pathname.replace(/\/+$/, '');
232
+ const root = `${url.origin}/.well-known/${suffix}`;
233
+ return path === '' ? [root] : [`${root}${path}`, root];
234
+ }
235
+
236
+ /** RFC 8414 first, then OIDC discovery in both placements the MCP spec lists. */
237
+ function authServerCandidates(issuer: URL): readonly string[] {
238
+ const path = issuer.pathname === '/' ? '' : issuer.pathname.replace(/\/+$/, '');
239
+ return [
240
+ `${issuer.origin}/.well-known/oauth-authorization-server${path}`,
241
+ `${issuer.origin}/.well-known/openid-configuration${path}`,
242
+ ...(path === '' ? [] : [`${issuer.origin}${path}/.well-known/openid-configuration`]),
243
+ ];
244
+ }
245
+
246
+ function stringList(value: unknown): readonly string[] {
247
+ return Array.isArray(value) ? value.filter((entry) => typeof entry === 'string') : [];
248
+ }
249
+
250
+ function parseObject(text: string): Record<string, unknown> | undefined {
251
+ try {
252
+ const parsed = JSON.parse(text) as unknown;
253
+ return isJsonObject(parsed) ? parsed : undefined;
254
+ } catch {
255
+ // Not JSON is "no document": the caller names the refusal.
256
+ return undefined;
257
+ }
258
+ }
@@ -0,0 +1,51 @@
1
+ // A remote tool's locked JSON Schema → a `t` schema, so the action wrapping it parses what the model
2
+ // sends before anything leaves this process. The common subset is translated (object, string,
3
+ // number, integer, boolean, array, string enum, `description`); anything else becomes `t.json()`,
4
+ // which the REMOTE server still validates — never wider than the remote, only less precise.
5
+
6
+ import { isJsonObject } from '@ultimat3/core';
7
+ import type { AnySchema } from '@ultimat3/schema';
8
+ import { t } from '@ultimat3/schema';
9
+
10
+ const MAX_DEPTH = 8;
11
+
12
+ export function schemaFromJson(raw: unknown, depth = 0): AnySchema {
13
+ if (!isJsonObject(raw) || depth > MAX_DEPTH) return t.json();
14
+ const described = (schema: AnySchema): AnySchema =>
15
+ typeof raw['description'] === 'string' ? schema.describe(raw['description']) : schema;
16
+ const values = raw['enum'];
17
+ if (Array.isArray(values) && values.length > 0 && values.every((v) => typeof v === 'string')) {
18
+ return described(t.enum(values as [string, ...string[]]));
19
+ }
20
+ switch (raw['type']) {
21
+ case 'string':
22
+ return described(t.string);
23
+ case 'number':
24
+ return described(t.number);
25
+ case 'integer':
26
+ return described(t.number.int());
27
+ case 'boolean':
28
+ return described(t.boolean);
29
+ case 'array':
30
+ return described(t.array(schemaFromJson(raw['items'], depth + 1)));
31
+ case 'object':
32
+ return described(objectFromJson(raw, depth));
33
+ default:
34
+ return described(t.json());
35
+ }
36
+ }
37
+
38
+ function objectFromJson(raw: Record<string, unknown>, depth: number): AnySchema {
39
+ const properties = isJsonObject(raw['properties']) ? raw['properties'] : undefined;
40
+ // An object with no declared properties is a free-form map: the remote decides what it takes.
41
+ if (properties === undefined) return t.record(t.json());
42
+ const required = new Set(
43
+ Array.isArray(raw['required']) ? raw['required'].filter((k) => typeof k === 'string') : [],
44
+ );
45
+ const shape = new Map<string, AnySchema>();
46
+ for (const [key, value] of Object.entries(properties)) {
47
+ const field = schemaFromJson(value, depth + 1);
48
+ shape.set(key, required.has(key) ? field : field.optional());
49
+ }
50
+ return t.object(Object.fromEntries(shape));
51
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * `mcpTools()` — another server's MCP tools as this app's `action`s: a factory over `action`, so a
3
+ * remote tool takes the app's own `policy`, its rate limit, the confirmation gate and a manifest row,
4
+ * and an agent sees one tool list. Nothing is discovered at run time: `allow` names the tools, the
5
+ * committed `tools.lock.json` holds what a person reviewed, and the live server must still agree.
6
+ */
7
+
8
+ import type { Action } from '@ultimat3/action';
9
+ import { action } from '@ultimat3/action';
10
+ import { finiteCount } from '@ultimat3/core';
11
+ import type { OutboundFetch } from '@ultimat3/core/outbound';
12
+ import type { KnownPermission } from '@ultimat3/policy';
13
+ import { can } from '@ultimat3/policy';
14
+ import type { AnySchema } from '@ultimat3/schema';
15
+ import { t } from '@ultimat3/schema';
16
+ import type { McpClient, RemoteTool } from './remote-client';
17
+ import { mcpClient } from './remote-client';
18
+ import { assertLocked, readToolsLock } from './remote-lock';
19
+ import { schemaFromJson } from './remote-schema';
20
+
21
+ export interface McpToolsDef {
22
+ /** This server's name in `tools.lock.json`, every cause and each action's name prefix. */
23
+ readonly name: string;
24
+ readonly url: string;
25
+ readonly auth?: () =>
26
+ | Readonly<Record<string, string>>
27
+ | Promise<Readonly<Record<string, string>>>;
28
+ /** The remote tools this app uses. Required: a tool nobody named is never offered. */
29
+ readonly allow: readonly string[];
30
+ /**
31
+ * Who may call these tools here: an existing `resource:verb` permission of the APP's, never the
32
+ * remote server's — as a hand-written tool or a `jobTool()` takes one. A permission and not a
33
+ * predicate: the input is the remote's schema, and an app rule reading it would read nothing.
34
+ */
35
+ readonly policy: KnownPermission;
36
+ /** The parsed `tools.lock.json` (`x mcp lock <name>` writes it). */
37
+ readonly lock: unknown;
38
+ readonly dial?: 'public' | 'named';
39
+ readonly deadlineMs?: number;
40
+ /** The longest answer handed to a model; the middle of a longer one is cut. Default 20,000. */
41
+ readonly maxResultChars?: number;
42
+ readonly fetch?: OutboundFetch;
43
+ }
44
+
45
+ /** What a remote tool answers: its text, delimited as untrusted, and whether it reported an error. */
46
+ export const RemoteToolOutput = t.object({ untrusted: t.string, isError: t.boolean });
47
+
48
+ export type RemoteToolAction = Action<AnySchema, typeof RemoteToolOutput>;
49
+
50
+ export interface McpTools {
51
+ /** One action per allowed tool, keyed by the REMOTE tool's name. */
52
+ readonly tools: ReadonlyMap<string, RemoteToolAction>;
53
+ readonly client: McpClient;
54
+ /** Lists the live server and refuses a drift from the lock — what boot and `verify` call. */
55
+ check(options?: { readonly signal?: AbortSignal }): Promise<readonly RemoteTool[]>;
56
+ }
57
+
58
+ /** One declared remote server, as `x mcp lock` and `--check` read it. */
59
+ export interface DeclaredMcpServer {
60
+ readonly name: string;
61
+ readonly url: string;
62
+ readonly allow: readonly string[];
63
+ readonly client: McpClient;
64
+ }
65
+
66
+ const DECLARED = new Map<string, DeclaredMcpServer>();
67
+
68
+ /** Every `mcpTools()` this process evaluated, by name — the CLI loads the app, then reads this. */
69
+ export function declaredMcpServers(): ReadonlyMap<string, DeclaredMcpServer> {
70
+ return DECLARED;
71
+ }
72
+
73
+ export function mcpTools(def: McpToolsDef): McpTools {
74
+ const maxChars = finiteCount('mcpTools', 'maxResultChars', def.maxResultChars ?? 20_000, 1);
75
+ const locked = readToolsLock(def.lock).get(def.name);
76
+ const client = mcpClient({
77
+ name: def.name,
78
+ url: def.url,
79
+ ...(def.dial === undefined ? {} : { dial: def.dial }),
80
+ ...(def.deadlineMs === undefined ? {} : { deadlineMs: def.deadlineMs }),
81
+ ...(def.auth === undefined ? {} : { auth: def.auth }),
82
+ ...(def.fetch === undefined ? {} : { fetch: def.fetch }),
83
+ // The server's list moved: forget the verdict, so the next call re-lists and is held to the
84
+ // lock again — a drift there is `X_MCP_REMOTE_TOOL_CHANGED`, never a quietly new tool.
85
+ onToolsChanged: () => {
86
+ verified = undefined;
87
+ },
88
+ });
89
+ // Recorded BEFORE the lock is judged: `x mcp lock` must find a server whose lock is missing.
90
+ DECLARED.set(def.name, { name: def.name, url: def.url, allow: [...def.allow], client });
91
+ // At declaration: an allowed tool the lock does not hold was never reviewed.
92
+ assertLocked(def.name, locked, def.url, def.allow);
93
+ // Checked against the live server once per process, before the first call goes out.
94
+ let verified: Promise<readonly RemoteTool[]> | undefined;
95
+ const check = (options: { readonly signal?: AbortSignal } = {}) => {
96
+ verified ??= client.listTools(options).then((live) => {
97
+ assertLocked(def.name, locked, def.url, def.allow, live);
98
+ return live;
99
+ });
100
+ // A failed check is not remembered: the next call asks again.
101
+ verified.catch(() => {
102
+ verified = undefined;
103
+ });
104
+ return verified;
105
+ };
106
+ const tools = new Map<string, RemoteToolAction>();
107
+ for (const tool of def.allow) {
108
+ const entry = locked?.tools.get(tool);
109
+ if (entry === undefined) continue;
110
+ const source = `mcp:${def.name}/${tool}`;
111
+ const built = action({
112
+ input: schemaFromJson(entry.inputSchema),
113
+ output: RemoteToolOutput,
114
+ policy: can(def.policy),
115
+ mcp: {
116
+ expose: true,
117
+ // The LOCKED description, never the live one: what the model reads is what was reviewed.
118
+ description: `[remote ${def.name}] ${entry.description}`,
119
+ annotations: {
120
+ readOnlyHint: entry.readOnly,
121
+ destructiveHint: !entry.readOnly,
122
+ openWorldHint: true,
123
+ },
124
+ },
125
+ async handle({ input, ctx }) {
126
+ await check({ signal: ctx.signal });
127
+ const args = typeof input === 'object' && input !== null ? input : {};
128
+ const answer = await client.callTool(tool, args as Record<string, unknown>, {
129
+ signal: ctx.signal,
130
+ });
131
+ return { untrusted: delimit(source, answer.text, maxChars), isError: answer.isError };
132
+ },
133
+ }).named(actionNameFor(def.name, tool));
134
+ tools.set(tool, built);
135
+ }
136
+ return { tools, client, check };
137
+ }
138
+
139
+ /** `docs` + `fetch-page` → `docs_fetch_page`: letters, digits and `_`, as a model's tool name. */
140
+ export function actionNameFor(server: string, tool: string): string {
141
+ return `${server}_${tool}`.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 64);
142
+ }
143
+
144
+ /**
145
+ * The remote's words inside a fence a model is told not to obey. A closing tag inside the text is
146
+ * broken, so the remote cannot end the fence early and speak as the app.
147
+ */
148
+ export function delimit(source: string, text: string, max: number): string {
149
+ const body = truncate(text, max).replaceAll('</untrusted', '<\\/untrusted');
150
+ return `<untrusted source="${source}">\n${body}\n</untrusted>`;
151
+ }
152
+
153
+ function truncate(text: string, max: number): string {
154
+ if (text.length <= max) return text;
155
+ const keep = Math.max(1, Math.floor((max - 40) / 2));
156
+ return `${text.slice(0, keep)}\n…[${String(text.length - keep * 2)} characters cut]…\n${text.slice(-keep)}`;
157
+ }