@ultimat3/mcp 29.3.2 → 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,121 @@
1
+ // The bytes of one call to ANOTHER server's MCP endpoint: the headers each era owes, an answer that
2
+ // is JSON or an SSE stream (streamable HTTP lets a server pick either), and the JSON-RPC envelope
3
+ // read out of it. No state lives here — `remote-client.ts` holds the era and the session.
4
+
5
+ import { isJsonObject } from '@ultimat3/core';
6
+ import { META_PROTOCOL_VERSION } from './wire';
7
+
8
+ /** The answer body a streamable-HTTP server may send: a JSON-RPC response, or SSE carrying one. */
9
+ export function readRpcAnswer(
10
+ contentType: string | null,
11
+ text: string,
12
+ id: number,
13
+ ): Record<string, unknown> | undefined {
14
+ if (contentType?.toLowerCase().startsWith('text/event-stream') === true) {
15
+ for (const event of text.split(/\r?\n\r?\n/)) {
16
+ const data = event
17
+ .split(/\r?\n/)
18
+ .filter((line) => line.startsWith('data:'))
19
+ .map((line) => line.slice(5).replace(/^ /, ''))
20
+ .join('\n');
21
+ const parsed = parseJson(data);
22
+ // A server may interleave its own requests and notifications; only OUR answer counts.
23
+ if (isJsonObject(parsed) && parsed['id'] === id) return parsed;
24
+ }
25
+ return undefined;
26
+ }
27
+ const parsed = parseJson(text);
28
+ return isJsonObject(parsed) ? parsed : undefined;
29
+ }
30
+
31
+ /** The `method` of every notification (no `id`) on an SSE answer; a JSON answer carries none. */
32
+ export function readNotifications(contentType: string | null, text: string): readonly string[] {
33
+ if (contentType?.toLowerCase().startsWith('text/event-stream') !== true) return [];
34
+ const methods: string[] = [];
35
+ for (const event of text.split(/\r?\n\r?\n/)) {
36
+ const data = event
37
+ .split(/\r?\n/)
38
+ .filter((line) => line.startsWith('data:'))
39
+ .map((line) => line.slice(5).replace(/^ /, ''))
40
+ .join('\n');
41
+ const parsed = parseJson(data);
42
+ if (
43
+ isJsonObject(parsed) &&
44
+ parsed['id'] === undefined &&
45
+ typeof parsed['method'] === 'string'
46
+ ) {
47
+ methods.push(parsed['method']);
48
+ }
49
+ }
50
+ return methods;
51
+ }
52
+
53
+ /** RFC 9728 §5.1: `resource_metadata="<url>"` in a 401's `WWW-Authenticate`, when it is there. */
54
+ export function resourceMetadataOf(challenge: string | null): string | undefined {
55
+ const match = /resource_metadata="([^"]+)"/i.exec(challenge ?? '');
56
+ return match?.[1];
57
+ }
58
+
59
+ function parseJson(text: string): unknown {
60
+ if (text.trim() === '') return undefined;
61
+ try {
62
+ return JSON.parse(text) as unknown;
63
+ } catch {
64
+ // Not JSON is "no answer" — the caller names it as the server's refusal.
65
+ return undefined;
66
+ }
67
+ }
68
+
69
+ /** `Mcp-Name` must be a header value: printable ASCII verbatim, else the base64 sentinel. */
70
+ export function encodeHeader(value: string): string {
71
+ if (/^[\x20-\x7e]*$/.test(value) && !value.startsWith('=?')) return value;
72
+ const bytes = new TextEncoder().encode(value);
73
+ return `=?base64?${btoa(String.fromCharCode(...bytes))}?=`;
74
+ }
75
+
76
+ /** Which body field a modern request mirrors into `Mcp-Name`. */
77
+ const NAMED: ReadonlyMap<string, string> = new Map([
78
+ ['tools/call', 'name'],
79
+ ['prompts/get', 'name'],
80
+ ['resources/read', 'uri'],
81
+ ]);
82
+
83
+ /** A modern request: `_meta` names the version, and the headers mirror the body. */
84
+ export function modernRequest(
85
+ version: string,
86
+ id: number,
87
+ method: string,
88
+ params: Record<string, unknown>,
89
+ ): { readonly body: Record<string, unknown>; readonly headers: Record<string, string> } {
90
+ const headers: Record<string, string> = {
91
+ 'mcp-protocol-version': version,
92
+ 'mcp-method': method,
93
+ };
94
+ const field = NAMED.get(method);
95
+ const named = field === undefined ? undefined : field === 'uri' ? params['uri'] : params['name'];
96
+ if (typeof named === 'string') headers['mcp-name'] = encodeHeader(named);
97
+ const meta = isJsonObject(params['_meta']) ? params['_meta'] : {};
98
+ return {
99
+ body: {
100
+ jsonrpc: '2.0',
101
+ id,
102
+ method,
103
+ params: { ...params, _meta: { ...meta, [META_PROTOCOL_VERSION]: version } },
104
+ },
105
+ headers,
106
+ };
107
+ }
108
+
109
+ /** The text a model reads from a `tools/call` result: text blocks joined, others named. */
110
+ export function resultText(result: Record<string, unknown>): string {
111
+ const content = Array.isArray(result['content']) ? result['content'] : [];
112
+ const parts = content.map((block: unknown) => {
113
+ if (!isJsonObject(block)) return '';
114
+ if (block['type'] === 'text' && typeof block['text'] === 'string') return block['text'];
115
+ return `[${typeof block['type'] === 'string' ? block['type'] : 'unknown'} content]`;
116
+ });
117
+ if (parts.length === 0 && result['structuredContent'] !== undefined) {
118
+ return JSON.stringify(result['structuredContent']);
119
+ }
120
+ return parts.join('\n');
121
+ }
package/src/resources.ts CHANGED
@@ -31,8 +31,21 @@ export interface McpResource {
31
31
  readonly scope?: string;
32
32
  /** Who may see and read it — OUTCOME 1. Absent = everyone. Same `McpVisibility` as a tool's. */
33
33
  readonly visibleTo?: McpVisibility;
34
- /** Read on demand — a resource is never eagerly materialised at boot. */
35
- read(): Promise<string> | string;
34
+ /**
35
+ * Read on demand — a resource is never eagerly materialised at boot. Handed the caller the gates
36
+ * already admitted, so a body may vary by caller (a tenant's own docs); a reader that takes no
37
+ * argument is the same document for everyone.
38
+ */
39
+ read(caller: McpCaller): Promise<string> | string;
40
+ }
41
+
42
+ /**
43
+ * Resources whose LIST depends on the caller — a tenant's own documents. Asked per request, after
44
+ * the fixed resources: a URI the fixed list holds is never shadowed by one of these. Each listed
45
+ * resource still passes `visibleTo` and `scope`, the gates every resource takes.
46
+ */
47
+ export interface McpResourceSource {
48
+ list(caller: McpCaller): Promise<readonly McpResource[]> | readonly McpResource[];
36
49
  }
37
50
 
38
51
  /** The gates that run before a resource is read. The tool surface's `ToolResolution` twin. */
@@ -196,6 +209,50 @@ export class ResourceRegistry {
196
209
  return this;
197
210
  }
198
211
 
212
+ private readonly sources: McpResourceSource[] = [];
213
+
214
+ /** A per-caller list, consulted after the fixed resources (`McpResourceSource`). */
215
+ addSource(source: McpResourceSource): this {
216
+ this.sources.push(source);
217
+ return this;
218
+ }
219
+
220
+ /** This caller's resources from every source, minus any URI the fixed list already holds. */
221
+ private async sourced(caller: McpCaller): Promise<readonly McpResource[]> {
222
+ const out = new Map<string, McpResource>();
223
+ for (const source of this.sources) {
224
+ for (const resource of await source.list(caller)) {
225
+ if (!this.resources.has(resource.uri) && !out.has(resource.uri)) {
226
+ out.set(resource.uri, resource);
227
+ }
228
+ }
229
+ }
230
+ return [...out.values()];
231
+ }
232
+
233
+ /** `list(caller)` plus the per-caller sources: what `resources/list` answers. */
234
+ async listFor(caller: McpCaller): Promise<readonly ResourceListEntry[]> {
235
+ if (this.sources.length === 0) return this.list(caller);
236
+ const extra = (await this.sourced(caller)).filter((r) => visibleToCaller(r, caller));
237
+ return [...this.list(caller), ...extra.map(listEntry)].sort(byUri);
238
+ }
239
+
240
+ /** `resolve`, falling back to the per-caller sources for a URI the fixed list does not hold. */
241
+ async resolveFor(uri: string, caller: McpCaller): Promise<ResourceResolution> {
242
+ const fixed = this.resolve(uri, caller);
243
+ if (fixed.kind !== 'not-found' || this.resources.has(uri) || this.sources.length === 0) {
244
+ return fixed;
245
+ }
246
+ const resource = (await this.sourced(caller)).find((r) => r.uri === uri);
247
+ if (resource === undefined || !visibleToCaller(resource, caller)) {
248
+ return { kind: 'not-found', uri };
249
+ }
250
+ if (resource.scope !== undefined && !caller.scopes.has(resource.scope)) {
251
+ return { kind: 'scope-denied', uri, scope: resource.scope };
252
+ }
253
+ return { kind: 'ok', resource };
254
+ }
255
+
199
256
  /**
200
257
  * Sorted by URI: a stable list is diffable between two boots. Role-filtered when a caller is
201
258
  * supplied, exactly as `ToolRegistry.list` is — `resources/list` answered every URI to every
@@ -204,14 +261,7 @@ export class ResourceRegistry {
204
261
  list(caller?: McpCaller): readonly ResourceListEntry[] {
205
262
  const all = [...this.resources.values()];
206
263
  const visible = caller === undefined ? all : all.filter((r) => visibleToCaller(r, caller));
207
- return visible
208
- .map((r) => ({
209
- uri: r.uri,
210
- name: r.name,
211
- description: r.description,
212
- mimeType: r.mimeType,
213
- }))
214
- .sort((a, b) => (a.uri < b.uri ? -1 : a.uri > b.uri ? 1 : 0));
264
+ return visible.map(listEntry).sort(byUri);
215
265
  }
216
266
 
217
267
  /**
@@ -230,14 +280,35 @@ export class ResourceRegistry {
230
280
  return { kind: 'ok', resource };
231
281
  }
232
282
 
233
- /** Raw read with NO gate applied — the resolver owns the gates, as it does for a tool. */
234
- async read(uri: string): Promise<ResourceContents | undefined> {
283
+ /**
284
+ * Raw read with NO gate applied — the resolver owns the gates, as it does for a tool. `caller` is
285
+ * the one the resolver admitted, handed to the reader.
286
+ */
287
+ async read(uri: string, caller: McpCaller): Promise<ResourceContents | undefined> {
235
288
  const resource = this.resources.get(uri);
236
289
  if (resource === undefined) return undefined;
237
- return { uri, mimeType: resource.mimeType, text: await resource.read() };
290
+ return readResource(resource, caller);
238
291
  }
239
292
  }
240
293
 
294
+ /** One resolved resource's contents, read as `caller`. */
295
+ export async function readResource(
296
+ resource: McpResource,
297
+ caller: McpCaller,
298
+ ): Promise<ResourceContents> {
299
+ return { uri: resource.uri, mimeType: resource.mimeType, text: await resource.read(caller) };
300
+ }
301
+
302
+ const listEntry = (r: McpResource): ResourceListEntry => ({
303
+ uri: r.uri,
304
+ name: r.name,
305
+ description: r.description,
306
+ mimeType: r.mimeType,
307
+ });
308
+
309
+ const byUri = (a: ResourceListEntry, b: ResourceListEntry): number =>
310
+ a.uri < b.uri ? -1 : a.uri > b.uri ? 1 : 0;
311
+
241
312
  /** JSON Schema for a tool that takes one resource URI — reused by app surfaces. */
242
313
  export const URI_ARG_SCHEMA: JsonSchema = {
243
314
  type: 'object',
@@ -0,0 +1,132 @@
1
+ // A runtime tool's `inputSchema`, read off a row: copied into the wire subset or refused whole.
2
+ //
3
+ // A static tool's schema is narrowed from a Standard Schema by `@ultimat3/schema`, so what
4
+ // `tools/list` publishes is what `validateArgs` enforces. A row's JSON Schema has no such step, and a
5
+ // keyword outside the subset (`format`, `oneOf`, `$ref`) would be PUBLISHED and never enforced — so
6
+ // it is refused, never dropped: dropping a constraint the author wrote widens the tool silently.
7
+
8
+ import { renderCauseValue } from '@ultimat3/core';
9
+ import { McpCatalogUnresolvedError } from './catalog-errors';
10
+ import type { JsonSchema } from './wire';
11
+
12
+ /** Every keyword `validateArgs` enforces — `WireJsonSchema`'s members, nothing else. */
13
+ const KEYWORDS: ReadonlySet<string> = new Set([
14
+ 'type',
15
+ 'title',
16
+ 'description',
17
+ 'properties',
18
+ 'required',
19
+ 'additionalProperties',
20
+ 'items',
21
+ 'minItems',
22
+ 'maxItems',
23
+ 'enum',
24
+ 'const',
25
+ 'default',
26
+ 'minimum',
27
+ 'maximum',
28
+ 'minLength',
29
+ 'maxLength',
30
+ 'pattern',
31
+ 'x-ultimate-pattern-flags',
32
+ 'anyOf',
33
+ ]);
34
+
35
+ const TYPES: ReadonlySet<unknown> = new Set([
36
+ 'object',
37
+ 'string',
38
+ 'number',
39
+ 'integer',
40
+ 'boolean',
41
+ 'array',
42
+ 'null',
43
+ ]);
44
+
45
+ /** Nesting a row's schema may reach. Deeper is a cycle or a schema no model reads. */
46
+ const MAX_DEPTH = 16;
47
+
48
+ /** `value` as a wire-subset schema whose root is an object, or `X_MCP_CATALOG_UNRESOLVED`. */
49
+ export function runtimeInputSchema(tool: string, value: unknown): JsonSchema {
50
+ const schema = node(tool, value, 'inputSchema', 0);
51
+ if (schema.type !== 'object') refuse(tool, 'inputSchema', 'its root must be { type: "object" }');
52
+ return schema;
53
+ }
54
+
55
+ function node(tool: string, value: unknown, at: string, depth: number): JsonSchema {
56
+ if (depth > MAX_DEPTH) refuse(tool, at, `nests deeper than ${MAX_DEPTH}`);
57
+ if (!isRecord(value)) refuse(tool, at, 'is not a JSON Schema object');
58
+ const out: Record<string, unknown> = {};
59
+ for (const [key, child] of Object.entries(value)) {
60
+ if (!KEYWORDS.has(key)) {
61
+ refuse(tool, at, `uses ${renderCauseValue(key)}, outside the subset validateArgs enforces`);
62
+ }
63
+ put(out, key, keyword(tool, key, child, `${at}.${key}`, depth));
64
+ }
65
+ return out as JsonSchema;
66
+ }
67
+
68
+ function keyword(tool: string, key: string, value: unknown, at: string, depth: number): unknown {
69
+ switch (key) {
70
+ case 'type':
71
+ if (!TYPES.has(value)) refuse(tool, at, 'is not a JSON Schema type');
72
+ return value;
73
+ case 'properties': {
74
+ if (!isRecord(value)) refuse(tool, at, 'is not an object');
75
+ const out: Record<string, unknown> = {};
76
+ for (const [name, child] of Object.entries(value)) {
77
+ put(out, name, node(tool, child, `${at}.${name}`, depth + 1));
78
+ }
79
+ return out;
80
+ }
81
+ case 'items':
82
+ return node(tool, value, at, depth + 1);
83
+ case 'anyOf':
84
+ if (!Array.isArray(value)) refuse(tool, at, 'is not an array');
85
+ return value.map((child, index) => node(tool, child, `${at}[${index}]`, depth + 1));
86
+ case 'required':
87
+ if (!Array.isArray(value) || !value.every((name) => typeof name === 'string')) {
88
+ refuse(tool, at, 'is not a list of names');
89
+ }
90
+ return [...value];
91
+ case 'enum':
92
+ if (!Array.isArray(value) || !value.every(isScalar)) refuse(tool, at, 'is not scalars');
93
+ return [...value];
94
+ case 'const':
95
+ if (!isScalar(value)) refuse(tool, at, 'is not a scalar');
96
+ return value;
97
+ case 'additionalProperties':
98
+ if (typeof value !== 'boolean') refuse(tool, at, 'is not a boolean');
99
+ return value;
100
+ case 'title':
101
+ case 'description':
102
+ case 'pattern':
103
+ case 'x-ultimate-pattern-flags':
104
+ if (typeof value !== 'string') refuse(tool, at, 'is not a string');
105
+ return value;
106
+ case 'default':
107
+ return value;
108
+ // minItems, maxItems, minimum, maximum, minLength, maxLength — the rest of `KEYWORDS`.
109
+ default:
110
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
111
+ refuse(tool, at, 'is not a finite number');
112
+ }
113
+ return value;
114
+ }
115
+ }
116
+
117
+ /** Through `defineProperty`: a property named `__proto__` is a key, never a re-prototyping. */
118
+ function put(out: Record<string, unknown>, key: string, value: unknown): void {
119
+ Object.defineProperty(out, key, { value, enumerable: true, writable: true, configurable: true });
120
+ }
121
+
122
+ function refuse(tool: string, at: string, why: string): never {
123
+ throw new McpCatalogUnresolvedError({
124
+ cause: `runtime tool ${renderCauseValue(tool)}: ${at} ${why}`,
125
+ });
126
+ }
127
+
128
+ const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
129
+ typeof value === 'object' && value !== null && !Array.isArray(value);
130
+
131
+ const isScalar = (value: unknown): value is string | number | boolean | null =>
132
+ value === null || ['string', 'number', 'boolean'].includes(typeof value);
@@ -0,0 +1,115 @@
1
+ // `runtimeTool()` — an app tool whose definition arrives at REQUEST time (`defineAppMcp({ catalog
2
+ // })`). Same projection as an authored app tool, no authz of its own: it BORROWS a declared
3
+ // permission through `@ultimat3/action`'s guards, and `can()` refuses one nobody declared.
4
+ //
5
+ // Only a value this factory built is servable (the `BUILT` brand).
6
+
7
+ import { asCallerContext, guardAction, guardActionBeforeInput } from '@ultimat3/action';
8
+ import type { Ctx, McpEffect } from '@ultimat3/core';
9
+ import { actorOf, renderCauseValue, useContext } from '@ultimat3/core';
10
+ import type { KnownPermission } from '@ultimat3/policy';
11
+ import { can } from '@ultimat3/policy';
12
+ import { McpCatalogUnresolvedError } from './catalog-errors';
13
+ import { McpToolUnsafeError } from './errors';
14
+ import { toolFrom } from './from-action';
15
+ import type { AnyMcpTool, McpToolAnnotations } from './registry';
16
+ import { runtimeInputSchema } from './runtime-schema';
17
+ import type { JsonSchema } from './wire';
18
+
19
+ export interface RuntimeToolArgs {
20
+ /** Validated against `inputSchema` (the wire subset, defaults applied) — the only parse there is. */
21
+ readonly input: Readonly<Record<string, unknown>>;
22
+ /** The ambient request context, `actor` set to the MCP caller — the tenant's, on a `tenant` server. */
23
+ readonly ctx: Ctx;
24
+ }
25
+
26
+ export interface RuntimeToolDefinition {
27
+ readonly name: string;
28
+ /** Says what it does AND whether it costs money or sends mail. Agents read only this. */
29
+ readonly description: string;
30
+ /**
31
+ * A JSON Schema in the wire subset, root `type: 'object'` — typically a row's column. `unknown`
32
+ * because it usually is: anything outside the subset is refused, never published unenforced.
33
+ */
34
+ readonly inputSchema: unknown;
35
+ /** An existing, DECLARED `resource:verb` permission. Never a rule invented for one tool. */
36
+ readonly permission: KnownPermission;
37
+ /**
38
+ * The `scopes:` key this tool is gated under — required exactly when `defineAppMcp` declares
39
+ * `scopes:`, and one of its keys (`X_MCP_CATALOG_UNRESOLVED` otherwise): a tool outside the map
40
+ * would answer every token, which `X_MCP_SCOPE_UNCOVERED` refuses for a static one.
41
+ */
42
+ readonly scope?: string;
43
+ /** Defaults to `true` (a write), as an app tool does: an unmarked tool is metered strictly. */
44
+ readonly destructive?: boolean;
45
+ /** `'write'` | `'delete'` — its dispatcher on a `'meta-split'` surface. */
46
+ readonly effect?: McpEffect;
47
+ readonly title?: string;
48
+ readonly annotations?: McpToolAnnotations;
49
+ run(args: RuntimeToolArgs): unknown;
50
+ }
51
+
52
+ /** What `runtimeTool()` hands back. Opaque: the catalog resolver returns it, the server serves it. */
53
+ export interface McpRuntimeTool {
54
+ readonly name: string;
55
+ /** The `scopes:` key it declared, read by `defineAppMcp`'s request-time scope check. */
56
+ readonly scope: string | undefined;
57
+ }
58
+
59
+ /** MCP's tool-name alphabet. A row's name is data, so it is checked before it is a key. */
60
+ const TOOL_NAME = /^[A-Za-z0-9_.-]{1,128}$/;
61
+
62
+ /** The brand: only a value built here is servable, so no hand-built tool skips the permission. */
63
+ const BUILT = new WeakMap<McpRuntimeTool, AnyMcpTool>();
64
+
65
+ export function runtimeTool(def: RuntimeToolDefinition): McpRuntimeTool {
66
+ const name = def.name;
67
+ if (typeof name !== 'string' || !TOOL_NAME.test(name)) {
68
+ throw new McpCatalogUnresolvedError({
69
+ cause: `a runtime tool is named ${renderCauseValue(name)}, and a tool name is 1-128 of A-Z a-z 0-9 _ - .`,
70
+ });
71
+ }
72
+ // At construction, as an app tool's is at boot: an unguarded tool is never servable.
73
+ if (typeof def.permission !== 'string' || def.permission.length === 0) {
74
+ throw new McpToolUnsafeError({ name });
75
+ }
76
+ const inputSchema: JsonSchema = runtimeInputSchema(name, def.inputSchema);
77
+ const policy = can(def.permission);
78
+ const tool = toolFrom({
79
+ name,
80
+ description: def.description,
81
+ mcp: {
82
+ expose: true,
83
+ description: def.description,
84
+ ...(def.title === undefined ? {} : { title: def.title }),
85
+ ...(def.effect === undefined ? {} : { effect: def.effect }),
86
+ ...(def.annotations === undefined ? {} : { annotations: def.annotations }),
87
+ },
88
+ inputJsonSchema: inputSchema,
89
+ mutates: def.destructive ?? true,
90
+ admit: (actor) =>
91
+ asCallerContext(actor, () => {
92
+ const ctx = useContext();
93
+ guardActionBeforeInput(policy, { actor: actorOf(ctx), ctx, action: name }, 'mcp');
94
+ }),
95
+ run: ({ input, actor }) =>
96
+ // The caller is the actor for the whole call, exactly as `app-tool.ts` runs one.
97
+ asCallerContext(actor, async () => {
98
+ const ctx = useContext();
99
+ guardActionBeforeInput(policy, { actor: actorOf(ctx), ctx, action: name }, 'mcp');
100
+ const args = input as Readonly<Record<string, unknown>>;
101
+ guardAction(policy, { actor: actorOf(ctx), input: args, ctx, action: name }, 'mcp');
102
+ return def.run({ input: args, ctx });
103
+ }),
104
+ });
105
+ const handle: McpRuntimeTool = Object.freeze({ name, scope: def.scope });
106
+ BUILT.set(handle, tool);
107
+ return handle;
108
+ }
109
+
110
+ /** The tool `runtimeTool()` built for this value, or `undefined` for anything else. */
111
+ export function builtRuntimeTool(value: unknown): AnyMcpTool | undefined {
112
+ return typeof value === 'object' && value !== null
113
+ ? BUILT.get(value as McpRuntimeTool)
114
+ : undefined;
115
+ }
package/src/scopes.ts CHANGED
@@ -44,6 +44,11 @@ export type McpScopes = Readonly<Record<string, readonly string[]>>;
44
44
  export function withScopes(
45
45
  tools: readonly AnyMcpTool[],
46
46
  scopes: McpScopes | undefined,
47
+ /**
48
+ * Reads the framework projected itself and gates per row or per caller (`job_status`, the
49
+ * recipes' `docs`): no scope covers them, because a scope would gate what the row gate decides.
50
+ */
51
+ exempt: ReadonlySet<string> = new Set(),
47
52
  ): readonly AnyMcpTool[] {
48
53
  if (scopes === undefined) return tools;
49
54
 
@@ -70,7 +75,9 @@ export function withScopes(
70
75
  }
71
76
 
72
77
  const uncovered = tools
73
- .filter((tool) => tool.scope === undefined && !required.has(tool.name))
78
+ .filter(
79
+ (tool) => tool.scope === undefined && !required.has(tool.name) && !exempt.has(tool.name),
80
+ )
74
81
  .map((tool) => tool.name)
75
82
  .sort();
76
83
  if (uncovered.length > 0) throw new McpScopeUncoveredError({ uncovered });