@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,118 @@
1
+ // Signed decisions for `mcpConfirmations({ evidence })`: the exact payload an approver signs, and the
2
+ // verifier over a STORED row that any process can run — the gate before it consumes an approval, or
3
+ // a separate executor that trusts nothing the app server wrote. Key lookup and signature maths are
4
+ // the app's (`evidence.verify`); this file owns what is signed and what a valid approval set is.
5
+
6
+ import { canonicalJson, compareFingerprint, finiteCount } from '@ultimat3/core';
7
+ import type { McpConfirmation } from './confirmation-store';
8
+
9
+ /** What one approver signs, by construction: never a value a caller assembles by hand. */
10
+ export const MCP_CONFIRMATION_SIGNING_PURPOSE = 'x-mcp-confirmation.approve/v1';
11
+
12
+ /** The keyed-digest purpose `inputDigest` uses; restated so this leaf imports no gate. */
13
+ const DIGEST_PURPOSE = 'mcp-confirmation';
14
+
15
+ /** What `evidence.verify` is asked about one signature. */
16
+ export interface McpEvidenceCheck {
17
+ /** The approving actor's id — the one whose registered keys the signature must verify under. */
18
+ readonly approver: string;
19
+ readonly confirmation: string;
20
+ readonly tool: string;
21
+ /** The row's keyed argument digest (`h1:<key id>:<mac>`), bound into `payload`. */
22
+ readonly digest: string;
23
+ /** The exact string signed: `confirmationSigningPayload(row)`. Verify the signature over THIS. */
24
+ readonly payload: string;
25
+ readonly signature: string;
26
+ /** The row's approver selectors, so a key registry can also confirm the approver's standing. */
27
+ readonly from: readonly string[] | null;
28
+ }
29
+
30
+ export interface McpConfirmationEvidence {
31
+ /**
32
+ * `true` only when `signature` verifies over `payload` under a key registered to `approver`.
33
+ * Anything else — `false`, a non-boolean — refuses. A throw propagates: an unreachable key store
34
+ * is an outage, never a verdict, and the row is left as it was for a retry.
35
+ */
36
+ readonly verify: (check: McpEvidenceCheck) => boolean | Promise<boolean>;
37
+ }
38
+
39
+ /**
40
+ * The payload an approver signs: purpose, confirmation id, tool and keyed digest, as canonical JSON.
41
+ * The id makes a signature good for ONE row — replayed onto a later identical call it binds a
42
+ * different id — and the digest makes it good for one set of arguments.
43
+ */
44
+ export function confirmationSigningPayload(
45
+ row: Pick<McpConfirmation, 'id' | 'tool' | 'inputDigest'>,
46
+ ): string {
47
+ return canonicalJson({
48
+ purpose: MCP_CONFIRMATION_SIGNING_PURPOSE,
49
+ confirmation: row.id,
50
+ tool: row.tool,
51
+ digest: row.inputDigest,
52
+ });
53
+ }
54
+
55
+ export interface VerifyConfirmationOptions {
56
+ /** Absent: signatures are not checked — only distinctness, eligibility and the quorum. */
57
+ readonly evidence?: McpConfirmationEvidence | undefined;
58
+ /** The bar the VERIFIER holds the row to; the row's own `quorum` is a floor it can only raise. */
59
+ readonly quorum?: number | undefined;
60
+ /** The verifier's selectors; defaults to the row's. Only `actor:` selectors are checked here. */
61
+ readonly from?: readonly string[] | null | undefined;
62
+ /** The arguments about to run: when given, the row's digest must be theirs (`compareFingerprint`). */
63
+ readonly arguments?: Readonly<Record<string, unknown>> | undefined;
64
+ }
65
+
66
+ export type McpConfirmationVerdict =
67
+ | { readonly ok: true; readonly approvers: readonly string[] }
68
+ | { readonly ok: false; readonly reason: 'binding' | 'refused' | 'quorum' };
69
+
70
+ /**
71
+ * Is this stored row a valid approval? Approved; bound to `arguments` when given; every stored
72
+ * signature verifying (one forged vote fails the row — it is evidence the row was written around
73
+ * the gate); and `quorum` distinct approvers counted, the requester never among them when selectors
74
+ * were declared. Exported so the process that EXECUTES can re-check what the server stored.
75
+ */
76
+ export async function verifyConfirmationEvidence(
77
+ row: McpConfirmation,
78
+ options: VerifyConfirmationOptions = {},
79
+ ): Promise<McpConfirmationVerdict> {
80
+ if (row.status !== 'approved') return { ok: false, reason: 'binding' };
81
+ if (options.arguments !== undefined) {
82
+ const bound = compareFingerprint(row.inputDigest, options.arguments, DIGEST_PURPOSE);
83
+ if (bound !== 'match') return { ok: false, reason: 'binding' };
84
+ }
85
+ const from = options.from === undefined ? row.approvers : options.from;
86
+ // A stored quorum that is not a number (a hand-edited row) makes `max` NaN, which no count meets.
87
+ const floor = finiteCount('verifyConfirmationEvidence', 'quorum', options.quorum ?? 1, 1);
88
+ const quorum = Math.max(row.quorum, floor);
89
+ const payload = confirmationSigningPayload(row);
90
+ const counted = new Set<string>();
91
+ for (const vote of row.approvals) {
92
+ if (options.evidence !== undefined) {
93
+ if (vote.signature === null) return { ok: false, reason: 'refused' };
94
+ const check = {
95
+ approver: vote.approver,
96
+ confirmation: row.id,
97
+ tool: row.tool,
98
+ digest: row.inputDigest,
99
+ payload,
100
+ signature: vote.signature,
101
+ from,
102
+ };
103
+ if ((await options.evidence.verify(check)) !== true) return { ok: false, reason: 'refused' };
104
+ }
105
+ if (eligible(vote.approver, row.actorId, from)) counted.add(vote.approver);
106
+ }
107
+ return counted.size >= quorum
108
+ ? { ok: true, approvers: [...counted] }
109
+ : { ok: false, reason: 'quorum' };
110
+ }
111
+
112
+ /** Countable here: not the requester under selectors, and named when every selector is an actor. */
113
+ function eligible(approver: string, requester: string, from: readonly string[] | null): boolean {
114
+ if (from === null) return true;
115
+ if (approver === requester) return false;
116
+ if (!from.every((one) => one.startsWith('actor:'))) return true;
117
+ return from.includes(`actor:${approver}`);
118
+ }
@@ -1,9 +1,13 @@
1
- // The agent's side of `mcpConfirmations`: a gated tool's `handle`, wrapped. It runs AFTER the
2
- // registry's visibility → scope → args and the tool's caller-only `admit`, and BEFORE the tool's own
3
- // `handle` — where a projected action's full policy runs. So the order is visibility → scope →
4
- // args → admit → confirmation → policy, and a caller the tool refuses outright never opens a row.
1
+ // The agent's side of `mcpConfirmations`: a gated tool's `handle`, wrapped, so the order is
2
+ // visibility → scope → args → admit → confirmation → policy (a projected action's full policy runs
3
+ // in `handle`), and a caller the tool refuses outright never opens a row. An in-app agent meets the
4
+ // same body through `confirmationToolGate`, read by `@ultimat3/ai`'s adapter.
5
5
 
6
+ import type { ToolGate } from '@ultimat3/action';
7
+ import { toolGateFor } from '@ultimat3/action';
8
+ import type { Actor, UltimateError } from '@ultimat3/core';
6
9
  import { keyedFingerprint, seal, uuidV7 } from '@ultimat3/core';
10
+ import { resolveApprovers } from './confirmation-approvers';
7
11
  import {
8
12
  McpConfirmationContestedError,
9
13
  McpConfirmationExpiredError,
@@ -11,23 +15,59 @@ import {
11
15
  McpConfirmationRejectedError,
12
16
  McpConfirmationToolUnknownError,
13
17
  } from './confirmation-errors';
18
+ import { verifyConfirmationEvidence } from './confirmation-evidence';
19
+ import {
20
+ McpConfirmationEvidenceInvalidError,
21
+ McpConfirmationQuorumPendingError,
22
+ } from './confirmation-quorum-errors';
23
+ import type { McpConfirmation } from './confirmation-store';
14
24
  import type { McpConfirmations } from './confirmations';
15
25
  import type { AnyMcpTool, McpCaller, McpToolResult, ToolArgs } from './registry';
26
+ import { invalidArgsError } from './server-voice';
27
+ import { validateArgs } from './validate-args';
16
28
 
17
29
  /**
18
- * The gated catalog. Refuses at boot a name the catalog does not hold — that call would run with
19
- * no person ever asked, which is exactly the silent pass the gate exists to remove.
30
+ * The gated catalog. The server's own `confirmations` wins for the names it gates, and refuses at
31
+ * boot a name the catalog does not hold — that call would run with no person ever asked, which is
32
+ * exactly the silent pass the gate exists to remove. Every other tool asks the registered gate at
33
+ * call time: `mcpConfirmations({ tools })` says every call waits, so forgetting this option is no way
34
+ * around it, and the module declaring the gate may evaluate after this server.
20
35
  */
21
36
  export function withConfirmations(
22
37
  tools: readonly AnyMcpTool[],
23
38
  confirmations: McpConfirmations | undefined,
24
39
  ): readonly AnyMcpTool[] {
25
- if (confirmations === undefined) return tools;
40
+ const own = confirmations?.tools ?? [];
26
41
  const known = tools.map((tool) => tool.name);
27
- const unknown = confirmations.tools.filter((name) => !known.includes(name));
42
+ const unknown = own.filter((name) => !known.includes(name));
28
43
  if (unknown.length > 0) throw new McpConfirmationToolUnknownError({ unknown, known });
29
- const gated = new Set(confirmations.tools);
30
- return tools.map((tool) => (gated.has(tool.name) ? gate(tool, confirmations) : tool));
44
+ return tools.map((tool) =>
45
+ confirmations !== undefined && own.includes(tool.name)
46
+ ? gate(tool, confirmations)
47
+ : registeredGate(tool),
48
+ );
49
+ }
50
+
51
+ /** `tool`, asking the gate registered for its name per call. Same order as `gate` below. */
52
+ function registeredGate(tool: AnyMcpTool): AnyMcpTool {
53
+ return {
54
+ ...tool,
55
+ // The catalog's label reads what is declared by now; the refusal below reads the call's truth.
56
+ ...(toolGateFor(tool.name) === undefined ? {} : { confirms: true }),
57
+ async handle(args: ToolArgs, caller: McpCaller): Promise<McpToolResult> {
58
+ const toolGate = toolGateFor(tool.name);
59
+ if (toolGate === undefined) return tool.handle(args, caller);
60
+ tool.admit?.(caller);
61
+ const call = {
62
+ tool: tool.name,
63
+ args,
64
+ inputSchema: tool.inputSchema,
65
+ actor: caller.actor,
66
+ };
67
+ // What a gate answers is what `run` answered, or it threw: this `run` answers a tool result.
68
+ return (await toolGate(call, async () => tool.handle(args, caller))) as McpToolResult;
69
+ },
70
+ };
31
71
  }
32
72
 
33
73
  /** What the arguments are sealed FOR — bound into the AES-GCM tag, so they open as nothing else. */
@@ -55,7 +95,6 @@ export function inputDigest(args: ToolArgs): string {
55
95
  }
56
96
 
57
97
  function gate(tool: AnyMcpTool, confirmations: McpConfirmations): AnyMcpTool {
58
- const { store, clock, ttlMs, sealKeys } = confirmations;
59
98
  return {
60
99
  ...tool,
61
100
  confirms: true,
@@ -63,39 +102,103 @@ function gate(tool: AnyMcpTool, confirmations: McpConfirmations): AnyMcpTool {
63
102
  // Caller-only half of the policy first: one who may never call this opens no row for a person
64
103
  // to look at. Throws the same denial `handle` would, rendered by the server.
65
104
  tool.admit?.(caller);
66
- const now = clock.now();
67
- const draft = {
68
- id: uuidV7(clock),
69
- actorId: caller.actor.id,
70
- orgId: caller.actor.orgId ?? null,
71
- tool: tool.name,
72
- inputDigest: inputDigest(args),
73
- // Sealed, never plaintext at rest: the person deciding reads them through the decision
74
- // action's `view`, and approves only by sending them back (`confirmation-decide.ts`).
75
- sealedArguments: await seal(JSON.stringify(args), {
76
- purpose: MCP_CONFIRMATION_ARGUMENTS_PURPOSE,
77
- ...sealKeys,
78
- }),
79
- createdAt: now,
80
- expiresAt: new Date(now.getTime() + ttlMs),
81
- };
82
- // Bounded: `consume` loses only to a concurrent identical call by the same agent, which then
83
- // carries the outcome; this one opens the next row on the following pass.
84
- for (let attempt = 0; attempt < 3; attempt += 1) {
85
- const { row, created } = await store.open(draft);
86
- const subject = { id: row.id, tool: tool.name, expiresAt: row.expiresAt };
87
- const live = row.expiresAt.getTime() > now.getTime();
88
- if (created || (row.status === 'pending' && live)) {
89
- throw new McpConfirmationPendingError({ ...subject, decider: confirmations.name });
90
- }
91
- // Every other state is an OUTCOME, delivered once: taking it is what frees this call to
92
- // ask again, and what makes one approval run one call.
93
- if (!(await store.consume(row.id, now))) continue;
94
- if (row.status === 'rejected') throw new McpConfirmationRejectedError(subject);
95
- if (!live) throw new McpConfirmationExpiredError({ ...subject, at: 'call' });
96
- return tool.handle(args, caller);
97
- }
98
- throw new McpConfirmationContestedError(tool.name);
105
+ return confirmedCall(
106
+ confirmations,
107
+ { tool: tool.name, args, actor: caller.actor },
108
+ async () => tool.handle(args, caller),
109
+ );
99
110
  },
100
111
  };
101
112
  }
113
+
114
+ /**
115
+ * The gate a tool meets outside any MCP server: `@ultimat3/ai`'s adapter runs it for an in-app agent.
116
+ * The arguments are checked here because no registry did, so the digest is over the same validated,
117
+ * defaulted arguments the MCP path digests, and a repeat spelling a default differently consumes the
118
+ * approval. A failure REFUSES and never calls `run`: the action's own parse drops a key it does not
119
+ * declare, so handing it `{ orderId, invented: 1 }` would run the tool with nobody asked. No schema
120
+ * declared: whatever object was sent is what a person is shown and what the digest binds.
121
+ */
122
+ export function confirmationToolGate(confirmations: McpConfirmations): ToolGate {
123
+ return async ({ tool, args, inputSchema, actor }, run) => {
124
+ const checked = validateArgs(inputSchema ?? { type: 'object' }, args);
125
+ if (!checked.ok) throw invalidArgsError(tool, checked.issues);
126
+ return confirmedCall(confirmations, { tool, args: checked.value, actor }, run);
127
+ };
128
+ }
129
+
130
+ /** One gated call: asks a person, or takes the decided outcome, and runs `proceed` on an approval. */
131
+ async function confirmedCall<T>(
132
+ confirmations: McpConfirmations,
133
+ call: { readonly tool: string; readonly args: ToolArgs; readonly actor: Actor },
134
+ proceed: () => Promise<T>,
135
+ ): Promise<T> {
136
+ const { store, clock, ttlMs, sealKeys } = confirmations;
137
+ const { tool, args, actor } = call;
138
+ const now = clock.now();
139
+ // Resolved from the validated arguments before any row opens: a bar nobody can meet is refused
140
+ // here, and the one met is stored on the row so a later declaration cannot lower it.
141
+ const bar = resolveApprovers(confirmations.approvers, { tool, args, actor });
142
+ const draft = {
143
+ id: uuidV7(clock),
144
+ actorId: actor.id,
145
+ orgId: actor.orgId ?? null,
146
+ tool,
147
+ inputDigest: inputDigest(args),
148
+ // Sealed, never plaintext at rest: the person deciding reads them through the decision
149
+ // action's `view`, and approves only by sending them back (`confirmation-decide.ts`).
150
+ sealedArguments: await seal(JSON.stringify(args), {
151
+ purpose: MCP_CONFIRMATION_ARGUMENTS_PURPOSE,
152
+ ...sealKeys,
153
+ }),
154
+ createdAt: now,
155
+ expiresAt: new Date(now.getTime() + ttlMs),
156
+ quorum: bar.quorum,
157
+ approvers: bar.from,
158
+ };
159
+ // Bounded: `consume` loses only to a concurrent identical call by the same agent, which then
160
+ // carries the outcome; this one opens the next row on the following pass.
161
+ for (let attempt = 0; attempt < 3; attempt += 1) {
162
+ const { row, created } = await store.open(draft);
163
+ const subject = { id: row.id, tool, expiresAt: row.expiresAt };
164
+ // Before any outcome is taken: a row of another org is not this call's to wait on, run or
165
+ // consume — the actor id alone would carry one org's approval into another's call.
166
+ if (row.orgId !== draft.orgId) {
167
+ throw new McpConfirmationEvidenceInvalidError({ ...subject, reason: 'org' });
168
+ }
169
+ const live = row.expiresAt.getTime() > now.getTime();
170
+ if (created || (row.status === 'pending' && live)) throw waiting(row, confirmations.name);
171
+ if (row.status === 'approved' && live) {
172
+ // Re-verified from what is STORED, before the CAS: a row written around the decision action
173
+ // runs nothing, and a verifier that throws leaves the approval in place for a retry.
174
+ const verdict = await verifyConfirmationEvidence(row, {
175
+ evidence: confirmations.evidence,
176
+ quorum: bar.quorum,
177
+ from: bar.from,
178
+ arguments: args,
179
+ });
180
+ if (!verdict.ok) {
181
+ if (!(await store.consume(row.id, now))) continue;
182
+ throw new McpConfirmationEvidenceInvalidError({ ...subject, reason: verdict.reason });
183
+ }
184
+ }
185
+ // Every other state is an OUTCOME, delivered once: taking it is what frees this call to
186
+ // ask again, and what makes one approval run one call.
187
+ if (!(await store.consume(row.id, now))) continue;
188
+ if (row.status === 'rejected') throw new McpConfirmationRejectedError(subject);
189
+ if (!live) throw new McpConfirmationExpiredError({ ...subject, at: 'call' });
190
+ return proceed();
191
+ }
192
+ throw new McpConfirmationContestedError(tool);
193
+ }
194
+
195
+ /** Pending with no vote yet asks a person; pending with some asks for the rest of the quorum. */
196
+ function waiting(row: McpConfirmation, decider: string): UltimateError {
197
+ const subject = { id: row.id, tool: row.tool, expiresAt: row.expiresAt };
198
+ if (row.approvals.length === 0) return new McpConfirmationPendingError({ ...subject, decider });
199
+ return new McpConfirmationQuorumPendingError({
200
+ ...subject,
201
+ approvals: row.approvals.length,
202
+ quorum: row.quorum,
203
+ });
204
+ }
@@ -6,28 +6,54 @@ import type { PgExecutor } from '@ultimat3/core';
6
6
  import { McpConfirmationContestedError } from './confirmation-errors';
7
7
  import type {
8
8
  McpConfirmation,
9
+ McpConfirmationApproval,
9
10
  McpConfirmationStatus,
10
11
  McpConfirmationStore,
11
12
  } from './confirmation-store';
12
13
 
13
14
  export const SQL_MCP_CONFIRMATION_OPEN = `
14
15
  insert into x_mcp_confirmations
15
- (id, actor_id, org_id, tool, input_digest, sealed_arguments, created_at, expires_at)
16
- values ($1, $2, $3, $4, $5, $6, $7, $8)
17
- on conflict (actor_id, tool, input_digest) where consumed_at is null do nothing
16
+ (id, actor_id, org_id, tool, input_digest, sealed_arguments, created_at, expires_at, quorum,
17
+ approvers)
18
+ values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb)
19
+ on conflict (actor_id, coalesce(org_id, ''), (org_id is null), tool, input_digest)
20
+ where consumed_at is null do nothing
18
21
  returning *
19
22
  `;
20
23
 
21
24
  export const SQL_MCP_CONFIRMATION_OPEN_ROW = `
22
25
  select * from x_mcp_confirmations
23
- where actor_id = $1 and tool = $2 and input_digest = $3 and consumed_at is null
26
+ where actor_id = $1 and org_id is not distinct from $2 and tool = $3 and input_digest = $4
27
+ and consumed_at is null
24
28
  `;
25
29
 
26
30
  export const SQL_MCP_CONFIRMATION_GET = 'select * from x_mcp_confirmations where id = $1';
27
31
 
32
+ /**
33
+ * One statement for both decisions, so a vote and the flip it causes are one row-locked write: two
34
+ * approvers racing re-evaluate against each other's committed vote (READ COMMITTED re-checks the
35
+ * WHERE on the newer row), so neither is lost and the quorum flips exactly once. A repeated
36
+ * approver matches no row (`approvals @> [{ approver }]`).
37
+ */
28
38
  export const SQL_MCP_CONFIRMATION_DECIDE = `
29
- update x_mcp_confirmations set status = $2, decided_by = $3, decided_at = $4
30
- where id = $1 and status = 'pending' and consumed_at is null and expires_at > $4
39
+ update x_mcp_confirmations set
40
+ approvals = case when $2::text = 'approved'
41
+ then approvals || jsonb_build_array(jsonb_build_object(
42
+ 'approver', $3::text, 'at', $4::timestamptz, 'signature', $5::text))
43
+ else approvals end,
44
+ status = case
45
+ when $2::text = 'rejected' then 'rejected'
46
+ when jsonb_array_length(approvals) + 1 >= quorum then 'approved'
47
+ else 'pending' end,
48
+ decided_by = case
49
+ when $2::text = 'rejected' or jsonb_array_length(approvals) + 1 >= quorum then $3::text
50
+ else decided_by end,
51
+ decided_at = case
52
+ when $2::text = 'rejected' or jsonb_array_length(approvals) + 1 >= quorum then $4::timestamptz
53
+ else decided_at end
54
+ where id = $1 and status = 'pending' and consumed_at is null and expires_at > $4::timestamptz
55
+ and ($2::text = 'rejected'
56
+ or not approvals @> jsonb_build_array(jsonb_build_object('approver', $3::text)))
31
57
  returning *
32
58
  `;
33
59
 
@@ -53,6 +79,10 @@ interface Row {
53
79
  readonly decided_at: Date | string | null;
54
80
  readonly decided_by: string | null;
55
81
  readonly consumed_at: Date | string | null;
82
+ readonly quorum: number | string;
83
+ /** `jsonb`: decoded by `Bun.SQL`, a string from a client that leaves it as text. */
84
+ readonly approvers: unknown;
85
+ readonly approvals: unknown;
56
86
  }
57
87
 
58
88
  export interface PostgresConfirmationStoreOptions {
@@ -85,10 +115,15 @@ export function postgresConfirmationStore(
85
115
  draft.sealedArguments,
86
116
  draft.createdAt,
87
117
  draft.expiresAt,
118
+ draft.quorum ?? 1,
119
+ draft.approvers === undefined || draft.approvers === null
120
+ ? null
121
+ : JSON.stringify(draft.approvers),
88
122
  ]);
89
123
  if (created !== undefined) return { row: created, created: true };
90
124
  const held = await first(SQL_MCP_CONFIRMATION_OPEN_ROW, [
91
125
  draft.actorId,
126
+ draft.orgId,
92
127
  draft.tool,
93
128
  draft.inputDigest,
94
129
  ]);
@@ -98,7 +133,8 @@ export function postgresConfirmationStore(
98
133
  throw new McpConfirmationContestedError(draft.tool);
99
134
  },
100
135
  get: (id) => first(SQL_MCP_CONFIRMATION_GET, [id]),
101
- decide: (id, status, by, at) => first(SQL_MCP_CONFIRMATION_DECIDE, [id, status, by, at]),
136
+ decide: (id, status, by, at, signature) =>
137
+ first(SQL_MCP_CONFIRMATION_DECIDE, [id, status, by, at, signature]),
102
138
  async consume(id, at) {
103
139
  return (await exec.query(SQL_MCP_CONFIRMATION_CONSUME, [id, at])).length === 1;
104
140
  },
@@ -139,5 +175,50 @@ function toConfirmation(row: Row): McpConfirmation {
139
175
  decidedAt: maybeDate(row.decided_at),
140
176
  decidedBy: row.decided_by,
141
177
  consumedAt: maybeDate(row.consumed_at),
178
+ quorum: Number(row.quorum),
179
+ approvers: selectorsOf(row.approvers),
180
+ approvals: approvalsOf(row.approvals),
142
181
  };
143
182
  }
183
+
184
+ /** A client that leaves `jsonb` as text hands back its JSON; text that is not JSON reads as junk. */
185
+ function decoded(value: unknown): unknown {
186
+ if (typeof value !== 'string') return value;
187
+ try {
188
+ return JSON.parse(value);
189
+ } catch {
190
+ // Not JSON: a hand-edited cell, read by both callers as the shape that refuses.
191
+ return MALFORMED;
192
+ }
193
+ }
194
+
195
+ const MALFORMED = Symbol('malformed');
196
+
197
+ /** `null` stays "any admitted decider"; a non-array is a hand-edited row and admits NOBODY. */
198
+ function selectorsOf(value: unknown): readonly string[] | null {
199
+ const held = decoded(value);
200
+ if (held === null || held === undefined) return null;
201
+ // Anything else that is not an array, MALFORMED included, admits nobody.
202
+ if (!Array.isArray(held)) return [];
203
+ return held.filter((one): one is string => typeof one === 'string');
204
+ }
205
+
206
+ /**
207
+ * Votes as stored. A malformed entry is dropped rather than repaired: it then counts toward no
208
+ * quorum, so a hand-edited row reads as fewer approvals — the reading that can only refuse.
209
+ */
210
+ function approvalsOf(value: unknown): McpConfirmationApproval[] {
211
+ const held = decoded(value);
212
+ if (!Array.isArray(held)) return [];
213
+ const votes: McpConfirmationApproval[] = [];
214
+ for (const entry of held) {
215
+ if (typeof entry !== 'object' || entry === null) continue;
216
+ const approver: unknown = Reflect.get(entry, 'approver');
217
+ const at: unknown = Reflect.get(entry, 'at');
218
+ const signature: unknown = Reflect.get(entry, 'signature');
219
+ if (typeof approver !== 'string' || typeof at !== 'string') continue;
220
+ if (signature !== null && typeof signature !== 'string') continue;
221
+ votes.push({ approver, at: new Date(at), signature });
222
+ }
223
+ return votes;
224
+ }
@@ -0,0 +1,102 @@
1
+ // The refusals the quorum and signed-evidence half of `mcpConfirmations` adds: a call that has some
2
+ // approvals and needs more, an approval (or a stored row) whose signed evidence does not verify, and
3
+ // an `approvers` declaration no approver set could ever meet. Split from `confirmation-errors.ts`
4
+ // for its ceiling; each `cause` names the confirmation id, the one fact every reader needs.
5
+
6
+ import { UltimateError } from '@ultimat3/core';
7
+
8
+ interface Subject {
9
+ readonly id: string;
10
+ readonly tool: string;
11
+ readonly expiresAt: Date;
12
+ }
13
+
14
+ const until = (subject: Subject): string => subject.expiresAt.toISOString();
15
+
16
+ /** Some distinct approvers have approved; the quorum the row was opened with is not yet met. */
17
+ export class McpConfirmationQuorumPendingError extends UltimateError {
18
+ constructor(
19
+ subject: Subject & {
20
+ readonly approvals: number;
21
+ readonly quorum: number;
22
+ /** Set when THIS approver had already counted: a second vote is never a second approver. */
23
+ readonly repeated?: string | undefined;
24
+ },
25
+ ) {
26
+ const already =
27
+ subject.repeated === undefined
28
+ ? ''
29
+ : `; ${subject.repeated} has already approved it, and one approver counts once`;
30
+ super({
31
+ code: 'X_MCP_CONFIRMATION_QUORUM_PENDING',
32
+ cause: `confirmation ${subject.id} for ${subject.tool} has ${subject.approvals} of the ${subject.quorum} distinct approvals it needs${already}; it stays open until ${until(subject)}`,
33
+ fix: `confirmations({ id, decision: 'view' }) # as ANOTHER approver the quorum names, with id ${subject.id}; then confirmations({ id, decision: 'approve', arguments }) with exactly what view returned, and the agent repeats the same tools/call before ${until(subject)}`,
34
+ callerFix: `ask ${subject.quorum - subject.approvals} more person(s) who may approve it to view confirmation ${subject.id} and approve it, then call ${subject.tool} again with exactly the same arguments before ${until(subject)}`,
35
+ meta: {
36
+ confirmation: subject.id,
37
+ tool: subject.tool,
38
+ expiresAt: until(subject),
39
+ approvals: subject.approvals,
40
+ quorum: subject.quorum,
41
+ },
42
+ });
43
+ }
44
+ }
45
+
46
+ /** Why evidence did not verify — a closed list, so a reader can branch on `meta.reason`. */
47
+ export type McpEvidenceFailure =
48
+ /** An approval was sent with no signature while `evidence` is declared. */
49
+ | 'missing'
50
+ /** `evidence.verify` answered anything but `true` for the signature sent or stored. */
51
+ | 'refused'
52
+ /** The stored row's distinct, eligible, verified approvals fall short of the quorum. */
53
+ | 'quorum'
54
+ /** The row is not approved, or the arguments presented are not the ones its digest binds. */
55
+ | 'binding'
56
+ /** The store answered a row opened in another org than the calling actor's. */
57
+ | 'org';
58
+
59
+ const WHY: Readonly<Record<McpEvidenceFailure, string>> = {
60
+ missing: 'the approval carried no signature, and mcpConfirmations({ evidence }) requires one',
61
+ refused:
62
+ "a signature did not verify against the keys registered to its approver over this confirmation's signing payload",
63
+ quorum:
64
+ 'its stored approvals are fewer distinct, eligible approvers than its quorum — the row was altered after the decision',
65
+ binding:
66
+ 'the stored row is not an approval of these arguments — it was altered after the decision',
67
+ org: "the store answered a row opened in another org than the caller's, and an org's approval never runs a call in another",
68
+ };
69
+
70
+ /** Signed evidence failed: at the decision (no vote stored) or at the call (nothing ran). */
71
+ export class McpConfirmationEvidenceInvalidError extends UltimateError {
72
+ constructor(subject: Subject & { readonly reason: McpEvidenceFailure }) {
73
+ super({
74
+ code: 'X_MCP_CONFIRMATION_EVIDENCE_INVALID',
75
+ cause: `confirmation ${subject.id} for ${subject.tool} was not accepted: ${WHY[subject.reason]}`,
76
+ fix:
77
+ subject.reason === 'missing' || subject.reason === 'refused'
78
+ ? `confirmations({ id, decision: 'view' }) # for ${subject.id}; sign the signingPayload it returns with a key registered to you, then confirmations({ id, decision: 'approve', arguments, signature })`
79
+ : subject.reason === 'org'
80
+ ? `mcpConfirmations({ store: postgresConfirmationStore({ executor }) }) # or memoryConfirmationStore(); a custom store's open() must key the open row by orgId too — audit who wrote x_mcp_confirmations ${subject.id}`
81
+ : `{ method: 'tools/call', params: { name, arguments } } # ${subject.tool} again opens a new confirmation; audit who wrote to x_mcp_confirmations for ${subject.id}`,
82
+ meta: {
83
+ confirmation: subject.id,
84
+ tool: subject.tool,
85
+ expiresAt: until(subject),
86
+ reason: subject.reason,
87
+ },
88
+ });
89
+ }
90
+ }
91
+
92
+ /** `approvers({ args })` answered a bar no approver set can meet. Refused before a row opens. */
93
+ export class McpConfirmationQuorumInvalidError extends UltimateError {
94
+ constructor(input: { readonly tool: string; readonly reason: string }) {
95
+ super({
96
+ code: 'X_MCP_CONFIRMATION_QUORUM_INVALID',
97
+ cause: `mcpConfirmations({ approvers }) for ${input.tool}: ${input.reason}; the call would wait until it expired with nobody able to approve it`,
98
+ fix: `mcpConfirmations({ approvers: ({ args }) => ({ quorum: 1, from: ['role:<name>'] }) }) # a whole quorum of at least 1, over 'role:<name>' or 'actor:<id>' selectors that reach it without the asking actor`,
99
+ meta: { tool: input.tool },
100
+ });
101
+ }
102
+ }
@@ -10,6 +10,10 @@ export const MCP_CONFIRMATIONS_TABLE = 'x_mcp_confirmations';
10
10
  * Applied by the boot, never by an app migration — the rule `SQL_IDEMPOTENCY_TABLE` follows.
11
11
  * `create … if not exists` throughout, so every boot can run it; a new column is an
12
12
  * `alter table … add column if not exists`, never an edit to the `create`.
13
+ *
14
+ * The open key carries the org: keyed by actor id alone, an id that stays the same across orgs
15
+ * carried an approval given in one org into a call in another. `coalesce` plus `is null` keeps a
16
+ * null org and `''` apart. The org-blind index is dropped in the same applied transaction.
13
17
  */
14
18
  export const SQL_MCP_CONFIRMATIONS_TABLE = `
15
19
  create table if not exists x_mcp_confirmations (
@@ -27,8 +31,15 @@ create table if not exists x_mcp_confirmations (
27
31
  consumed_at timestamptz
28
32
  );
29
33
 
30
- create unique index if not exists x_mcp_confirmations_open_idx
31
- on x_mcp_confirmations (actor_id, tool, input_digest) where consumed_at is null;
34
+ drop index if exists x_mcp_confirmations_open_idx;
35
+
36
+ create unique index if not exists x_mcp_confirmations_open_org_idx
37
+ on x_mcp_confirmations (actor_id, coalesce(org_id, ''), (org_id is null), tool, input_digest)
38
+ where consumed_at is null;
32
39
 
33
40
  create index if not exists x_mcp_confirmations_expires_at_idx on x_mcp_confirmations (expires_at);
41
+
42
+ alter table x_mcp_confirmations add column if not exists quorum integer not null default 1;
43
+ alter table x_mcp_confirmations add column if not exists approvers jsonb;
44
+ alter table x_mcp_confirmations add column if not exists approvals jsonb not null default '[]'::jsonb;
34
45
  `;