@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,84 @@
1
+ // `defineAppMcp({ catalog })` — the app's per-caller resolver, checked into what the server serves.
2
+ //
3
+ // Only `runtimeTool()` values pass (so every runtime tool borrows a declared permission); each one's
4
+ // `scope` is held to the boot `scopes:` map exactly as `withScopes` holds a static tool; and each is
5
+ // wrapped by the registered confirmation gate a static tool gets. Per request, never cached.
6
+
7
+ import { renderCauseValue } from '@ultimat3/core';
8
+ import { McpCatalogUnresolvedError } from './catalog-errors';
9
+ import { withConfirmations } from './confirmation-gate';
10
+ import type { McpResourceGroups } from './meta-surface';
11
+ import type { AnyMcpTool, McpCaller } from './registry';
12
+ import type { McpRuntimeTool } from './runtime-tool';
13
+ import { builtRuntimeTool } from './runtime-tool';
14
+ import type { McpScopes } from './scopes';
15
+ import type { McpCatalogSource, McpResolvedCatalog } from './server-catalog';
16
+
17
+ /** What the app's resolver answers for one caller. */
18
+ export interface McpRuntimeCatalog {
19
+ /** Built by `runtimeTool()` — nothing else is servable. */
20
+ readonly tools: readonly McpRuntimeTool[];
21
+ /** Resources for `list_resources` on a meta surface, beside `groups:` — new names only. */
22
+ readonly groups?: McpResourceGroups;
23
+ }
24
+
25
+ /**
26
+ * The tools THIS caller may call beyond the static ones, asked for every `tools/list` and every
27
+ * `tools/call`. It already filters by caller, so a runtime tool takes no `visibleTo`. On a `tenant`
28
+ * server, `tools/list` asks it for the person and `tools/call` for the call's tenant actor.
29
+ */
30
+ export type McpCatalog = (caller: McpCaller) => Promise<McpRuntimeCatalog> | McpRuntimeCatalog;
31
+
32
+ export function appCatalogSource(
33
+ catalog: McpCatalog,
34
+ scopes: McpScopes | undefined,
35
+ ): McpCatalogSource {
36
+ return async (caller) => checked(await catalog(caller), scopes);
37
+ }
38
+
39
+ function checked(resolved: McpRuntimeCatalog, scopes: McpScopes | undefined): McpResolvedCatalog {
40
+ if (typeof resolved !== 'object' || resolved === null || !Array.isArray(resolved.tools)) {
41
+ throw new McpCatalogUnresolvedError({
42
+ cause: 'the catalog resolver answered something other than { tools: runtimeTool()[] }',
43
+ });
44
+ }
45
+ const tools = resolved.tools.map((entry, index): AnyMcpTool => {
46
+ const tool = builtRuntimeTool(entry);
47
+ if (tool === undefined) {
48
+ throw new McpCatalogUnresolvedError({
49
+ cause: `catalog entry ${index} was not built by runtimeTool(), so it carries no declared permission`,
50
+ });
51
+ }
52
+ return scoped(tool, entry.scope, scopes);
53
+ });
54
+ return {
55
+ tools: withConfirmations(tools, undefined),
56
+ ...(resolved.groups === undefined ? {} : { groups: resolved.groups }),
57
+ };
58
+ }
59
+
60
+ /** Outcome 2 for a runtime tool: a key of the boot `scopes:` map, required exactly when there is one. */
61
+ function scoped(
62
+ tool: AnyMcpTool,
63
+ scope: string | undefined,
64
+ scopes: McpScopes | undefined,
65
+ ): AnyMcpTool {
66
+ const name = renderCauseValue(tool.name);
67
+ if (scopes === undefined) {
68
+ if (scope === undefined) return tool;
69
+ throw new McpCatalogUnresolvedError({
70
+ cause: `runtime tool ${name} names scope ${renderCauseValue(scope)}, and defineAppMcp declares no scopes:`,
71
+ });
72
+ }
73
+ if (scope === undefined) {
74
+ throw new McpCatalogUnresolvedError({
75
+ cause: `runtime tool ${name} names no scope, and defineAppMcp declares scopes: — it would answer every token`,
76
+ });
77
+ }
78
+ if (!Object.hasOwn(scopes, scope)) {
79
+ throw new McpCatalogUnresolvedError({
80
+ cause: `runtime tool ${name} names scope ${renderCauseValue(scope)}, which scopes: does not declare`,
81
+ });
82
+ }
83
+ return { ...tool, scope };
84
+ }
package/src/app-tool.ts CHANGED
@@ -10,14 +10,18 @@
10
10
  // tool therefore has no authz of its own — it borrows the action tier's, so a rule change cannot
11
11
  // apply to routes and miss tools.
12
12
 
13
- import { guardAction, guardActionBeforeInput, InputInvalidError } from '@ultimat3/action';
13
+ import {
14
+ asCallerContext,
15
+ guardAction,
16
+ guardActionBeforeInput,
17
+ InputInvalidError,
18
+ } from '@ultimat3/action';
14
19
  import type { Ctx, McpEffect } from '@ultimat3/core';
15
20
  import { actorOf, useContext } from '@ultimat3/core';
16
21
  import type { KnownPermission } from '@ultimat3/policy';
17
22
  import { can } from '@ultimat3/policy';
18
23
  import type { InferOutput, StandardSchemaV1 } from '@ultimat3/schema';
19
24
  import { formatIssues, toValidationIssues, toWireSchema, validateAsync } from '@ultimat3/schema';
20
- import { asCallerContext } from './caller-context';
21
25
  import { McpToolUnsafeError } from './errors';
22
26
  import type { ProjectablePrimitive } from './from-action';
23
27
  import type { McpRole, McpToolAnnotations } from './registry';
package/src/app-tools.ts CHANGED
@@ -8,9 +8,12 @@
8
8
  // Deliberately one function: an app author should never have to know that `ToolRegistry`,
9
9
  // `frameworkResources` and `mcpHttpRoute` exist.
10
10
 
11
+ import { noteToolNames } from '@ultimat3/action';
11
12
  import type { ErrorAudience } from '@ultimat3/core';
12
13
  import type { RequestFacts as McpRequestFacts, RateLimitStore } from '@ultimat3/http';
13
14
  import type { StandardSchemaV1 } from '@ultimat3/schema';
15
+ import type { McpCatalog } from './app-catalog';
16
+ import { appCatalogSource } from './app-catalog';
14
17
  import type { AnyAppToolDefinition, AppTools } from './app-tool';
15
18
  import { appToolPrimitives } from './app-tool';
16
19
  import type { McpAuditHook } from './audit-hook';
@@ -19,10 +22,15 @@ import type { McpConfirmations } from './confirmations';
19
22
  import { McpToolDuplicateError } from './errors';
20
23
  import { exposedPrimitives } from './exposed';
21
24
  import { toolsFrom, toolsListed } from './from-action';
25
+ import { jobStatusPrimitive } from './job-status-tool';
26
+ import { jobToolBrand } from './job-tool';
22
27
  import type { McpResourceGroups, McpSurfaceOption } from './meta-surface';
23
28
  import type { McpOAuth } from './oauth-metadata';
24
29
  import type { ListedPrimitive } from './projectable';
25
30
  import { asProjectable } from './projectable';
31
+ import type { McpRecipe } from './recipes';
32
+ import { withRecipes } from './recipes-surface';
33
+ import type { ExtraRecipes } from './recipes-tool';
26
34
  import type { AnyMcpTool } from './registry';
27
35
  import type { McpPrompt, McpResource } from './resources';
28
36
  import { toPrompts } from './resources';
@@ -31,6 +39,7 @@ import { withScopes } from './scopes';
31
39
  import type { McpServerInput } from './server';
32
40
  import { type McpServer, mcpServer } from './server';
33
41
  import type { McpInstructions } from './server-voice';
42
+ import type { McpTenant } from './tenant';
34
43
  import type { McpRateLimits, McpRouteDescriptor, ResolvedToken } from './transport-http';
35
44
  import { mcpHttpRoute } from './transport-http';
36
45
 
@@ -59,6 +68,19 @@ export interface DefineAppMcpInput<TSchemas extends AppToolSchemas = AppToolSche
59
68
  readonly queries?: readonly ListedPrimitive[];
60
69
  /** App-specific readable documents (a catalog export, a report). */
61
70
  readonly resources?: readonly McpResource[];
71
+ /**
72
+ * How-to recipes, each served as `docs://recipes/<name>` and through a read-only `docs` tool.
73
+ * Every step names a tool of THIS server and its example must pass that tool's input — checked
74
+ * here, so a renamed tool fails the boot instead of sending an agent to nothing. With recipes
75
+ * declared, `resources:` may not hold a `docs://recipes/` URI (`X_MCP_RECIPE_URI_RESERVED`).
76
+ */
77
+ readonly recipes?: readonly McpRecipe[];
78
+ /**
79
+ * The caller's OWN recipes beside `recipes:` — a tenant's runbooks — asked per request, listed
80
+ * by `docs` as `source: 'caller'` and on `resources/list` to that caller alone. Not checked at
81
+ * boot (they do not exist yet): one naming a tool the caller cannot call is simply not shown.
82
+ */
83
+ readonly extraRecipes?: ExtraRecipes;
62
84
  /** Prompts the app ships: a path to a versioned artifact, or the full descriptor. */
63
85
  readonly prompts?: readonly (string | McpPrompt)[];
64
86
  /**
@@ -67,6 +89,29 @@ export interface DefineAppMcpInput<TSchemas extends AppToolSchemas = AppToolSche
67
89
  * surfaces that build their catalog programmatically (`@ultimat3/admin` does).
68
90
  */
69
91
  readonly tools?: readonly AnyMcpTool[] | AppTools<TSchemas>;
92
+ /**
93
+ * Tools that exist per caller — a tenant's connectors, a project's integrations — resolved for
94
+ * every `tools/list` and `tools/call` (never cached) and served beside `tools` under the same
95
+ * gates. Each is a `runtimeTool()`, borrowing a declared `permission`; `groups` adds resources to
96
+ * a meta surface. A name taken twice is `X_MCP_CATALOG_TOOL_DUPLICATE`, a resolver that throws or
97
+ * answers anything unservable `X_MCP_CATALOG_UNRESOLVED` — the request fails, never a smaller list.
98
+ *
99
+ * ```ts
100
+ * catalog: async (caller) => ({
101
+ * tools: (await connectorsOf(caller.actor)).map((row) =>
102
+ * runtimeTool({ name: row.name, description: row.description, inputSchema: row.schema,
103
+ * permission: 'connector:call', destructive: false, run: ({ input, ctx }) => call(ctx, row, input) })),
104
+ * }),
105
+ * ```
106
+ */
107
+ readonly catalog?: McpCatalog;
108
+ /**
109
+ * One token across tenants: `resolveToken` answers the PERSON, and every `tools/call` names its
110
+ * tenant under `arg` — stripped before validation, checked by `resolve` (`null` answers as a
111
+ * hidden tool), and the actor `resolve` answers is the caller for every gate and the policy.
112
+ * `list_tenants` serves `list`; a call naming none is `X_MCP_TENANT_REQUIRED`.
113
+ */
114
+ readonly tenant?: McpTenant;
70
115
  /**
71
116
  * Scope name → the tools that capability covers, by tool name. The connection gate, and the
72
117
  * second of the three outcomes: a caller that may SEE a tool but whose token does not carry
@@ -171,10 +216,11 @@ export interface DefineAppMcpInput<TSchemas extends AppToolSchemas = AppToolSche
171
216
  * OAuth discovery for remote MCP clients (the MCP authorization spec, RFC 9728): the route's 401
172
217
  * says `WWW-Authenticate: Bearer resource_metadata="<origin>/.well-known/oauth-protected-resource/mcp"`,
173
218
  * and the boot serves that document (and the root one) naming `authorizationServers`. The
174
- * authorization server — consent, `/oauth/token` — is the app's own routes.
219
+ * authorization server is `mcpAuthorizationServer(...)`: its `routes` go in `runtime.routes`,
220
+ * its consent page is the app's, and its `oauth` and `resolveToken` are handed in here.
175
221
  *
176
222
  * ```ts
177
- * oauth: { authorizationServers: ['https://www.example.com'], resourceName: 'Example' },
223
+ * oauth: as.oauth, resolveToken: as.resolveToken,
178
224
  * ```
179
225
  */
180
226
  readonly oauth?: McpOAuth | undefined;
@@ -227,7 +273,10 @@ export function defineAppMcp<TSchemas extends AppToolSchemas>(
227
273
  const included =
228
274
  input.include === 'exposed' ? notNamed(toolsFrom(exposedPrimitives()), listed) : [];
229
275
  const written = handWritten(input.tools);
230
- const named = [...listed, ...included, ...written];
276
+ // One `job_status` for every `jobTool()` here, projected beside them; an app tool already named
277
+ // that is a duplicate below, never a silent shadow.
278
+ const status = jobStatusFor(input.tools);
279
+ const named = [...listed, ...included, ...written, ...status];
231
280
  // Unique names FIRST: the scope map addresses tools by name, so a duplicate would make
232
281
  // "which tool did this scope gate?" unanswerable before the question is worth asking.
233
282
  //
@@ -237,13 +286,24 @@ export function defineAppMcp<TSchemas extends AppToolSchemas>(
237
286
  { source: 'actions:/queries:', tools: listed },
238
287
  { source: "include: 'exposed'", tools: included },
239
288
  { source: 'tools:', tools: written },
289
+ { source: 'jobTool()', tools: status },
240
290
  ]);
291
+ // The `manifest` step reads these: a hand-written tool is in no registry, and a gate on one is real.
292
+ noteToolNames(named.map((tool) => tool.name));
241
293
  // Scopes, then the gate: the gate wraps `handle`, which every resolve reaches last.
242
- const projected = withConfirmations(withScopes(named, input.scopes), input.confirmations);
294
+ const exempt = new Set(status.map((tool) => tool.name));
295
+ const confirmed = withConfirmations(withScopes(named, input.scopes, exempt), input.confirmations);
296
+ // Recipes last, over the FINAL catalog: a step is checked against what a caller can call.
297
+ const {
298
+ tools: projected,
299
+ resources,
300
+ resourceSources,
301
+ } = withRecipes(confirmed, input.resources ?? [], input.recipes, input.extraRecipes);
243
302
 
244
303
  const config: McpServerInput = {
245
304
  tools: projected,
246
- resources: input.resources ?? [],
305
+ resources,
306
+ ...(resourceSources.length === 0 ? {} : { resourceSources }),
247
307
  prompts: toPrompts(input.prompts ?? []),
248
308
  serverInfo: { name: input.name ?? 'ultimate-app', version: input.version ?? '0.0.0' },
249
309
  ...(input.surface === undefined ? {} : { surface: input.surface }),
@@ -251,6 +311,10 @@ export function defineAppMcp<TSchemas extends AppToolSchemas>(
251
311
  ...(input.instructions === undefined ? {} : { instructions: input.instructions }),
252
312
  errorAudience: input.errorAudience ?? 'caller',
253
313
  ...(input.onAudit === undefined ? {} : { onAudit: input.onAudit }),
314
+ ...(input.catalog === undefined
315
+ ? {}
316
+ : { catalog: appCatalogSource(input.catalog, input.scopes) }),
317
+ ...(input.tenant === undefined ? {} : { tenant: input.tenant }),
254
318
  };
255
319
  const server = mcpServer(config);
256
320
 
@@ -287,6 +351,17 @@ function handWritten(
287
351
  return toolsFrom(appToolPrimitives(tools as Readonly<Record<string, AnyAppToolDefinition>>));
288
352
  }
289
353
 
354
+ /** `job_status`, once, when the record holds any `jobTool()`; else nothing. */
355
+ function jobStatusFor(
356
+ tools: readonly AnyMcpTool[] | AppTools<AppToolSchemas> | undefined,
357
+ ): readonly AnyMcpTool[] {
358
+ if (tools === undefined || Array.isArray(tools)) return [];
359
+ const brands = Object.values(tools as Readonly<Record<string, AnyAppToolDefinition>>)
360
+ .map((def) => jobToolBrand(def))
361
+ .filter((brand) => brand !== undefined);
362
+ return brands.length === 0 ? [] : toolsFrom([jobStatusPrimitive(brands)]);
363
+ }
364
+
290
365
  function notNamed(
291
366
  tools: readonly AnyMcpTool[],
292
367
  exclude: readonly AnyMcpTool[],
package/src/audit-hook.ts CHANGED
@@ -11,7 +11,13 @@ import type { McpAuditEntry, McpResourceAuditEntry } from './audit';
11
11
  import { auditResourceRead, auditToolCall } from './audit';
12
12
 
13
13
  /** Why the transport refused before a caller existed. The 429 is `throttled` whichever came first. */
14
- export type McpAuthRefusal = 'missing-token' | 'rejected-token' | 'not-an-agent' | 'throttled';
14
+ /** `origin-refused`: a cross-origin `Origin`, refused 403 before the token is read. */
15
+ export type McpAuthRefusal =
16
+ | 'missing-token'
17
+ | 'rejected-token'
18
+ | 'not-an-agent'
19
+ | 'throttled'
20
+ | 'origin-refused';
15
21
 
16
22
  /** One decision. `at` is the auditor's clock, never `new Date()`; the token never travels. */
17
23
  export type McpAuditEvent =
package/src/audit.ts CHANGED
@@ -50,6 +50,8 @@ const DENIAL_CODES: ReadonlySet<string> = new Set([
50
50
  'X_ADMIN_DENIED',
51
51
  'X_FORBIDDEN',
52
52
  'X_MCP_CONFIRMATION_REJECTED',
53
+ // A quorum vote whose signed evidence does not verify: a refusal, in the denial bucket.
54
+ 'X_MCP_CONFIRMATION_EVIDENCE_INVALID',
53
55
  'X_UNAUTHENTICATED',
54
56
  ]);
55
57
 
@@ -64,7 +66,12 @@ const DENIAL_CODES: ReadonlySet<string> = new Set([
64
66
  * input this server already validated failing inside the action means the two have drifted, and
65
67
  * that wants a human.
66
68
  */
67
- const ARGUMENT_CODES: ReadonlySet<string> = new Set(['X_ADMIN_INVALID', 'X_MCP_WRONG_TOOL']);
69
+ const ARGUMENT_CODES: ReadonlySet<string> = new Set([
70
+ 'X_ADMIN_INVALID',
71
+ 'X_MCP_WRONG_TOOL',
72
+ // A call on a `tenant` server that named none: a client slip, answered with `list_tenants`.
73
+ 'X_MCP_TENANT_REQUIRED',
74
+ ]);
68
75
 
69
76
  /**
70
77
  * `mcpConfirmations`' answers for a call no live approval covers. A rejection is NOT here: a human
@@ -73,6 +80,8 @@ const ARGUMENT_CODES: ReadonlySet<string> = new Set(['X_ADMIN_INVALID', 'X_MCP_W
73
80
  const UNCONFIRMED_CODES: ReadonlySet<string> = new Set([
74
81
  'X_MCP_CONFIRMATION_PENDING',
75
82
  'X_MCP_CONFIRMATION_EXPIRED',
83
+ // Approved by fewer people than the quorum asks: still waiting, as a pending one is.
84
+ 'X_MCP_CONFIRMATION_QUORUM_PENDING',
76
85
  'X_MCP_USER_CONFIRMATION_REQUIRED',
77
86
  ]);
78
87
 
@@ -187,6 +196,8 @@ function callerFields(entry: McpResourceAuditEntry | McpAuditEntry): LogFields {
187
196
  actor: entry.caller.actor.id,
188
197
  actorKind: entry.caller.actor.kind,
189
198
  ...(entry.caller.role === undefined ? {} : { role: entry.caller.role }),
199
+ // The tenant a `tenant` server resolved for this call — the decision's subject, not an argument.
200
+ ...(entry.caller.tenant === undefined ? {} : { tenant: entry.caller.tenant }),
190
201
  ...(entry.scope === undefined ? {} : { scope: entry.scope }),
191
202
  ...(entry.code === undefined ? {} : { code: entry.code }),
192
203
  };
@@ -0,0 +1,97 @@
1
+ // The refusals of a per-caller catalog (`defineAppMcp({ catalog })`) and of a per-call tenant
2
+ // (`defineAppMcp({ tenant })`). Codes and titles are registered in `errors.ts` with the rest of the
3
+ // package's; these classes sit apart so that file stays under the size ceiling.
4
+ //
5
+ // A runtime name came out of a row, so it is rendered (`renderCauseValue`/`renderFixLiteral`), never spliced.
6
+
7
+ import { renderCauseValue, renderFixLiteral, renderThrowable, UltimateError } from '@ultimat3/core';
8
+
9
+ /** Where a name the resolved catalog collided with came from. */
10
+ export type McpCatalogNameSource =
11
+ | 'tools:'
12
+ | 'catalog'
13
+ | 'a meta tool'
14
+ | 'list_tenants'
15
+ | 'groups:';
16
+
17
+ /**
18
+ * A resolved catalog answers to one name twice: a static tool, a meta tool, `list_tenants`, a boot
19
+ * resource group, or another runtime entry. Boot's `X_MCP_TOOL_DUPLICATE` cannot fire for a name
20
+ * that does not exist at boot, so this is that refusal at request time — the agent would otherwise
21
+ * reach whichever copy the registry met first.
22
+ */
23
+ export class McpCatalogToolDuplicateError extends UltimateError {
24
+ constructor(input: {
25
+ readonly name: unknown;
26
+ readonly kind: 'tool' | 'resource';
27
+ readonly first: McpCatalogNameSource;
28
+ }) {
29
+ super({
30
+ code: 'X_MCP_CATALOG_TOOL_DUPLICATE',
31
+ cause: `the catalog resolved a ${input.kind} named ${renderCauseValue(input.name)}, and ${input.first} already answers to that name`,
32
+ fix: `defineAppMcp({ catalog: (caller) => ({ tools: [runtimeTool({ name: '<unique-name>', … })] }) }) — rename the runtime ${input.kind} now called ${renderFixLiteral(input.name, '<its name>')}; x mcp tools --json lists the static names`,
33
+ });
34
+ }
35
+ }
36
+
37
+ /**
38
+ * The catalog could not be served for this caller: the resolver threw, or answered something this
39
+ * server refuses to serve (an entry not built by `runtimeTool()`, a scope the boot map does not
40
+ * declare, a schema outside the wire subset). Never a silently smaller catalog — a tool missing
41
+ * from `tools/list` sends an agent away from a call that exists.
42
+ */
43
+ export class McpCatalogUnresolvedError extends UltimateError {
44
+ constructor(input: { readonly cause: string; readonly sourceError?: unknown }) {
45
+ super({
46
+ code: 'X_MCP_CATALOG_UNRESOLVED',
47
+ cause: input.cause,
48
+ fix: 'defineAppMcp({ catalog: (caller) => ({ tools: [runtimeTool({ name, description, inputSchema, permission, run })] }) }) — fix what the cause names in the catalog function: its throw, an entry not built by runtimeTool(), or a scope the boot scopes: map does not declare',
49
+ ...(input.sourceError === undefined ? {} : { sourceError: input.sourceError }),
50
+ });
51
+ }
52
+
53
+ /** The resolver itself threw: the thrown value rendered totally, never interpolated. */
54
+ static threw(thrown: unknown): McpCatalogUnresolvedError {
55
+ return new McpCatalogUnresolvedError({
56
+ cause: `the catalog resolver threw: ${renderThrowable(thrown)}`,
57
+ sourceError: thrown,
58
+ });
59
+ }
60
+ }
61
+
62
+ /** A call on a `tenant` server whose arguments carry no tenant value. */
63
+ export class McpTenantRequiredError extends UltimateError {
64
+ constructor(input: { readonly arg: string }) {
65
+ super({
66
+ code: 'X_MCP_TENANT_REQUIRED',
67
+ cause: `this server acts every call in the tenant the call names, and this call's arguments carry no "${input.arg}"`,
68
+ fix: `list_tenants({}) — then send one of its values as "${input.arg}" in the arguments of every tools/call`,
69
+ });
70
+ }
71
+ }
72
+
73
+ /**
74
+ * `tenant.resolve` threw, or answered an actor that is not an agent. A failed lookup is NOT "not a
75
+ * member": answering it as not-found would tell an agent a tool it may call does not exist.
76
+ */
77
+ export class McpTenantUnresolvedError extends UltimateError {
78
+ constructor(input: { readonly cause: string; readonly sourceError?: unknown }) {
79
+ super({
80
+ code: 'X_MCP_TENANT_UNRESOLVED',
81
+ cause: input.cause,
82
+ fix: "defineAppMcp({ tenant: { arg, resolve: ({ person, value }) => (member ? agentActor({ id: person.id, orgId: value }) : null), list } }) — the cause names what refused; resolve answers a kind: 'agent' actor, or null for a non-member, and never throws",
83
+ ...(input.sourceError === undefined ? {} : { sourceError: input.sourceError }),
84
+ });
85
+ }
86
+ }
87
+
88
+ /** `tenant.arg` is unusable: not a plain name, or a tool's own input already declares it. */
89
+ export class McpTenantInvalidError extends UltimateError {
90
+ constructor(input: { readonly cause: string }) {
91
+ super({
92
+ code: 'X_MCP_TENANT_INVALID',
93
+ cause: input.cause,
94
+ fix: "defineAppMcp({ tenant: { arg: 'tenant', resolve, list } }) — pick an argument name no tool's input declares",
95
+ });
96
+ }
97
+ }
@@ -0,0 +1,85 @@
1
+ // `mcpConfirmations({ approvers })`: WHO may approve one gated call and HOW MANY of them must, resolved
2
+ // per call from its validated arguments, checked here before any row opens, and stored on the row so
3
+ // a later declaration change never moves the bar of a confirmation already asked. Matching a decider
4
+ // against the stored selectors is this file's too: the decision action's policy calls it.
5
+
6
+ import type { Actor } from '@ultimat3/core';
7
+ import { McpConfirmationQuorumInvalidError } from './confirmation-quorum-errors';
8
+
9
+ /**
10
+ * One way to name an approver: `actor:<id>` (that actor exactly) or `role:<name>` (any actor holding
11
+ * that application role). A closed template type, so `'finance'` is a compile error, not a selector
12
+ * that silently matches nobody.
13
+ */
14
+ export type McpApproverSelector = `actor:${string}` | `role:${string}`;
15
+
16
+ /** What `approvers({ args })` answers: `quorum` distinct approvers matching `from`, requester excluded. */
17
+ export interface McpConfirmationApprovers {
18
+ readonly quorum: number;
19
+ readonly from: readonly McpApproverSelector[];
20
+ }
21
+
22
+ /** The call `approvers` resolves over — the VALIDATED, defaulted arguments the digest binds. */
23
+ export interface McpApproversCall {
24
+ readonly tool: string;
25
+ readonly args: Readonly<Record<string, unknown>>;
26
+ /** The asking actor. It never counts toward its own quorum, whatever `from` says. */
27
+ readonly actor: Actor;
28
+ }
29
+
30
+ export type McpApproversResolver = (call: McpApproversCall) => McpConfirmationApprovers;
31
+
32
+ /** The bar one row is held to: `from: null` is "any decider the policy admits" (no `approvers`). */
33
+ export interface ResolvedApprovers {
34
+ readonly quorum: number;
35
+ readonly from: readonly string[] | null;
36
+ }
37
+
38
+ /** No `approvers` declared: one decision by anyone the policy admits — the original gate. */
39
+ export const SINGLE_APPROVAL: ResolvedApprovers = Object.freeze({ quorum: 1, from: null });
40
+
41
+ const SELECTOR = /^(actor|role):.+$/;
42
+
43
+ /**
44
+ * Resolve and refuse: a quorum that is not a whole number of at least one, an empty or malformed
45
+ * `from`, or more named actors than exist once the requester is excluded would hold the call until
46
+ * it expires with nobody able to free it — a misdeclaration, so it is refused before a row opens.
47
+ * A `role:` selector's membership is only known at decision time, so its reach is not checked here.
48
+ */
49
+ export function resolveApprovers(
50
+ resolver: McpApproversResolver | undefined,
51
+ call: McpApproversCall,
52
+ ): ResolvedApprovers {
53
+ if (resolver === undefined) return SINGLE_APPROVAL;
54
+ const { quorum, from } = resolver(call);
55
+ const refuse = (reason: string) =>
56
+ new McpConfirmationQuorumInvalidError({ tool: call.tool, reason });
57
+ if (!Number.isSafeInteger(quorum) || quorum < 1) {
58
+ throw refuse(`quorum is ${String(quorum)}, not a whole number of at least 1`);
59
+ }
60
+ if (from.length === 0) throw refuse('from is empty, so no actor could ever approve');
61
+ const malformed = from.filter((selector) => !SELECTOR.test(selector));
62
+ if (malformed.length > 0) {
63
+ throw refuse(
64
+ `from holds ${malformed.length} selector(s) that are not actor:<id> or role:<name>`,
65
+ );
66
+ }
67
+ const named = new Set(from.filter((one) => one.startsWith('actor:')).map((one) => one.slice(6)));
68
+ named.delete(call.actor.id);
69
+ if (from.every((one) => one.startsWith('actor:')) && named.size < quorum) {
70
+ throw refuse(
71
+ `quorum ${quorum} needs more approvers than the ${named.size} named actor(s) other than the requester`,
72
+ );
73
+ }
74
+ return Object.freeze({ quorum, from: Object.freeze([...new Set(from)]) });
75
+ }
76
+
77
+ /** Does `actor` match one of a row's stored selectors? `null` selectors admit every decider. */
78
+ export function matchesApprover(actor: Actor, from: readonly string[] | null): boolean {
79
+ if (from === null) return true;
80
+ return from.some((selector) =>
81
+ selector.startsWith('actor:')
82
+ ? selector.slice(6) === actor.id
83
+ : selector.startsWith('role:') && actor.roles.includes(selector.slice(5)),
84
+ );
85
+ }
@@ -1,7 +1,7 @@
1
1
  // The decision action's handle: `view` shows a person the request exactly as the agent sent it;
2
- // `approve` / `reject` take a decision once, and an approval only for those same arguments. The
3
- // policy already ran (the factory's `can(…)`, agent refusal and tenant default included), so this
4
- // file decides STATE, never who.
2
+ // `approve` / `reject` take a decision once per decider, an approval only for those same arguments
3
+ // and, under `evidence`, only with a signature that verifies. The policy already ran (agent and
4
+ // requester refusals, `approvers` selectors, tenant default), so this file decides STATE, never who.
5
5
 
6
6
  import type { Clock, SealKeySource, UltimateError } from '@ultimat3/core';
7
7
  import { compareFingerprint, openText } from '@ultimat3/core';
@@ -12,10 +12,16 @@ import {
12
12
  McpConfirmationExpiredError,
13
13
  McpConfirmationUnknownError,
14
14
  } from './confirmation-errors';
15
+ import type { McpConfirmationEvidence } from './confirmation-evidence';
16
+ import { confirmationSigningPayload } from './confirmation-evidence';
15
17
  import {
16
18
  MCP_CONFIRMATION_ARGUMENTS_PURPOSE,
17
19
  MCP_CONFIRMATION_DIGEST_PURPOSE,
18
20
  } from './confirmation-gate';
21
+ import {
22
+ McpConfirmationEvidenceInvalidError,
23
+ McpConfirmationQuorumPendingError,
24
+ } from './confirmation-quorum-errors';
19
25
  import type { McpConfirmation, McpConfirmationStore } from './confirmation-store';
20
26
 
21
27
  export interface DecisionAsked {
@@ -23,6 +29,8 @@ export interface DecisionAsked {
23
29
  readonly decision: 'view' | 'approve' | 'reject';
24
30
  /** What the person approves — the `arguments` `view` returned. Required to approve. */
25
31
  readonly arguments?: Readonly<Record<string, JsonValue>> | undefined;
32
+ /** The approver's signature over `signingPayload`. Required to approve under `evidence`. */
33
+ readonly signature?: string | undefined;
26
34
  }
27
35
 
28
36
  export interface DecisionAnswer {
@@ -33,12 +41,18 @@ export interface DecisionAnswer {
33
41
  readonly decidedAt: Date | null;
34
42
  /** The arguments the agent sent, opened — what the person sees and what an approval binds to. */
35
43
  readonly arguments: Record<string, JsonValue>;
44
+ /** Distinct approvals this confirmation needs, and who has given one so far, in order. */
45
+ readonly quorum: number;
46
+ readonly approvedBy: string[];
47
+ /** What an approver signs under `evidence`: `confirmationSigningPayload(row)`. */
48
+ readonly signingPayload: string;
36
49
  }
37
50
 
38
51
  export interface DecideDeps {
39
52
  readonly store: McpConfirmationStore;
40
53
  readonly clock: Clock;
41
54
  readonly sealKeys: SealKeySource;
55
+ readonly evidence?: McpConfirmationEvidence | undefined;
42
56
  }
43
57
 
44
58
  export async function decideConfirmation(
@@ -53,17 +67,70 @@ export async function decideConfirmation(
53
67
  const at = deps.clock.now();
54
68
  const refused = stateRefusal(row, at);
55
69
  if (refused !== undefined) throw refused;
56
- if (asked.decision === 'approve') assertSameArguments(row, asked.arguments);
57
- const status = asked.decision === 'approve' ? 'approved' : 'rejected';
58
- const decided = await deps.store.decide(row.id, status, deciderId, at);
59
- // The CAS lost to a concurrent decision or the expiry: re-read and say which.
70
+ const approving = asked.decision === 'approve';
71
+ let signature: string | null = null;
72
+ if (approving) {
73
+ assertSameArguments(row, asked.arguments);
74
+ const repeated = repeatRefusal(row, deciderId);
75
+ if (repeated !== undefined) throw repeated;
76
+ signature = await signedBy(deps.evidence, row, deciderId, asked.signature);
77
+ }
78
+ const status = approving ? 'approved' : 'rejected';
79
+ const decided = await deps.store.decide(row.id, status, deciderId, at, signature);
80
+ // The CAS lost to a concurrent decision, the expiry, or this approver's own concurrent vote.
60
81
  if (decided === undefined) {
61
82
  const now = await deps.store.get(row.id);
62
- throw (now === undefined ? undefined : stateRefusal(now, at)) ?? expired(row);
83
+ const why =
84
+ now === undefined ? undefined : (stateRefusal(now, at) ?? repeatRefusal(now, deciderId));
85
+ throw why ?? expired(row);
63
86
  }
64
87
  return answer(decided, shown);
65
88
  }
66
89
 
90
+ /** An approver who already counted: a second vote is never a second approver. */
91
+ function repeatRefusal(row: McpConfirmation, deciderId: string): UltimateError | undefined {
92
+ if (!row.approvals.some((vote) => vote.approver === deciderId)) return undefined;
93
+ return new McpConfirmationQuorumPendingError({
94
+ id: row.id,
95
+ tool: row.tool,
96
+ expiresAt: row.expiresAt,
97
+ approvals: row.approvals.length,
98
+ quorum: row.quorum,
99
+ repeated: deciderId,
100
+ });
101
+ }
102
+
103
+ /**
104
+ * Under `evidence`, the vote's signature must verify over THIS row's signing payload under a key
105
+ * registered to the decider — checked before any write, so a refused one stores no vote. A throw
106
+ * from `verify` is an outage and propagates; only `true` admits.
107
+ */
108
+ async function signedBy(
109
+ evidence: McpConfirmationEvidence | undefined,
110
+ row: McpConfirmation,
111
+ approver: string,
112
+ signature: string | undefined,
113
+ ): Promise<string | null> {
114
+ if (evidence === undefined) return null;
115
+ const subject = { id: row.id, tool: row.tool, expiresAt: row.expiresAt };
116
+ if (signature === undefined || signature.length === 0) {
117
+ throw new McpConfirmationEvidenceInvalidError({ ...subject, reason: 'missing' });
118
+ }
119
+ const verified = await evidence.verify({
120
+ approver,
121
+ confirmation: row.id,
122
+ tool: row.tool,
123
+ digest: row.inputDigest,
124
+ payload: confirmationSigningPayload(row),
125
+ signature,
126
+ from: row.approvers,
127
+ });
128
+ if (verified !== true) {
129
+ throw new McpConfirmationEvidenceInvalidError({ ...subject, reason: 'refused' });
130
+ }
131
+ return signature;
132
+ }
133
+
67
134
  /**
68
135
  * The approval binds to what the person was SHOWN: the keyed digest of the arguments they send back
69
136
  * must match the row's, timing-safe (`compareFingerprint`). A swap between `view` and `approve` —
@@ -113,4 +180,7 @@ const answer = (row: McpConfirmation, shown: Record<string, JsonValue>): Decisio
113
180
  expiresAt: row.expiresAt,
114
181
  decidedAt: row.decidedAt,
115
182
  arguments: shown,
183
+ quorum: row.quorum,
184
+ approvedBy: row.approvals.map((vote) => vote.approver),
185
+ signingPayload: confirmationSigningPayload(row),
116
186
  });