@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
@@ -29,8 +29,17 @@ export interface McpConfirmation {
29
29
  /** After this instant the row can be neither decided nor used. */
30
30
  readonly expiresAt: Date;
31
31
  readonly decidedAt: Date | null;
32
- /** The deciding actor's id. */
32
+ /** The deciding actor's id: the rejecter, or the approver whose vote met the quorum. */
33
33
  readonly decidedBy: string | null;
34
+ /** Distinct approvals this row needs, resolved from `approvers({ args })` when it opened. */
35
+ readonly quorum: number;
36
+ /**
37
+ * The `approvers` selectors (`actor:<id>`, `role:<name>`) resolved when it opened; `null` when
38
+ * none were declared, and any decider the policy admits may approve.
39
+ */
40
+ readonly approvers: readonly string[] | null;
41
+ /** One entry per distinct approver, in order — the stored evidence a separate process verifies. */
42
+ readonly approvals: readonly McpConfirmationApproval[];
34
43
  /**
35
44
  * When the asking agent's next identical call took the outcome — ran it, or was told it was
36
45
  * rejected or expired. A consumed row is history: the same call afterwards asks again.
@@ -38,34 +47,47 @@ export interface McpConfirmation {
38
47
  readonly consumedAt: Date | null;
39
48
  }
40
49
 
41
- export type McpConfirmationDraft = Pick<
42
- McpConfirmation,
43
- | 'id'
44
- | 'actorId'
45
- | 'orgId'
46
- | 'tool'
47
- | 'inputDigest'
48
- | 'sealedArguments'
49
- | 'createdAt'
50
- | 'expiresAt'
51
- >;
50
+ /** One approver's vote: who, when, and their signature over the row's signing payload. */
51
+ export interface McpConfirmationApproval {
52
+ readonly approver: string;
53
+ readonly at: Date;
54
+ /** `null` when `mcpConfirmations({ evidence })` is not declared. */
55
+ readonly signature: string | null;
56
+ }
57
+
58
+ /** Optional so a row opened without `approvers` needs neither: one approval, any admitted decider. */
59
+ export type McpConfirmationDraft = Partial<Pick<McpConfirmation, 'quorum' | 'approvers'>> &
60
+ Pick<
61
+ McpConfirmation,
62
+ | 'id'
63
+ | 'actorId'
64
+ | 'orgId'
65
+ | 'tool'
66
+ | 'inputDigest'
67
+ | 'sealedArguments'
68
+ | 'createdAt'
69
+ | 'expiresAt'
70
+ >;
52
71
 
53
72
  export interface McpConfirmationStore {
54
73
  /**
55
- * The OPEN (unconsumed) row for this actor + tool + digest, or a new pending one built from
74
+ * The OPEN (unconsumed) row for this actor + org + tool + digest, or a new pending one built from
56
75
  * `draft` when there is none — atomically, so two identical calls racing open ONE row.
57
76
  */
58
77
  open(draft: McpConfirmationDraft): Promise<{ row: McpConfirmation; created: boolean }>;
59
78
  get(id: string): Promise<McpConfirmation | undefined>;
60
79
  /**
61
- * Pending, unconsumed and unexpired at `at` → `status`. `undefined` when the row is not in that
62
- * state (or does not exist): a decision is taken once, and the caller re-reads to say why.
80
+ * Pending, unconsumed and unexpired at `at`, as ONE conditional write. `rejected` settles the row.
81
+ * `approved` appends `by`'s vote — refused when `by` already voted — and flips the row to
82
+ * `approved` only when the votes reach its `quorum`. `undefined` when the row is not in that state
83
+ * (or does not exist): a vote is taken once, and the caller re-reads to say why.
63
84
  */
64
85
  decide(
65
86
  id: string,
66
87
  status: 'approved' | 'rejected',
67
88
  by: string,
68
89
  at: Date,
90
+ signature: string | null,
69
91
  ): Promise<McpConfirmation | undefined>;
70
92
  /** Unconsumed → consumed at `at`. `false` when another call took it first. */
71
93
  consume(id: string, at: Date): Promise<boolean>;
@@ -73,8 +95,10 @@ export interface McpConfirmationStore {
73
95
  purge(before: Date): Promise<number>;
74
96
  }
75
97
 
76
- const openKey = (row: Pick<McpConfirmation, 'actorId' | 'tool' | 'inputDigest'>): string =>
77
- JSON.stringify([row.actorId, row.tool, row.inputDigest]);
98
+ /** The org is in the key: an actor id the same in two orgs is two callers, as Postgres' index. */
99
+ const openKey = (
100
+ row: Pick<McpConfirmation, 'actorId' | 'orgId' | 'tool' | 'inputDigest'>,
101
+ ): string => JSON.stringify([row.actorId, row.orgId, row.tool, row.inputDigest]);
78
102
 
79
103
  /**
80
104
  * Per PROCESS: right for a test and for `x dev`, and a lie for a fleet — an agent's call opens the
@@ -100,6 +124,9 @@ export function memoryConfirmationStore(): McpConfirmationStore {
100
124
  decidedAt: null,
101
125
  decidedBy: null,
102
126
  consumedAt: null,
127
+ quorum: draft.quorum ?? 1,
128
+ approvers: draft.approvers ?? null,
129
+ approvals: [],
103
130
  });
104
131
  open.set(openKey(row), row.id);
105
132
  return { row, created: true };
@@ -107,12 +134,20 @@ export function memoryConfirmationStore(): McpConfirmationStore {
107
134
  async get(id) {
108
135
  return rows.get(id);
109
136
  },
110
- async decide(id, status, by, at) {
137
+ async decide(id, status, by, at, signature) {
111
138
  const row = rows.get(id);
112
139
  if (row === undefined || row.status !== 'pending' || row.consumedAt !== null)
113
140
  return undefined;
114
141
  if (row.expiresAt.getTime() <= at.getTime()) return undefined;
115
- return put({ ...row, status, decidedBy: by, decidedAt: at });
142
+ if (status === 'rejected') return put({ ...row, status, decidedBy: by, decidedAt: at });
143
+ if (row.approvals.some((one) => one.approver === by)) return undefined;
144
+ const approvals = [...row.approvals, { approver: by, at, signature }];
145
+ const met = approvals.length >= row.quorum;
146
+ return put({
147
+ ...row,
148
+ approvals,
149
+ ...(met ? { status: 'approved' as const, decidedBy: by, decidedAt: at } : {}),
150
+ });
116
151
  },
117
152
  async consume(id, at) {
118
153
  const row = rows.get(id);
@@ -2,20 +2,29 @@
2
2
  // ninth primitive. What it returns IS the decision action (`{ id, decision: 'approve' | 'reject' }`):
3
3
  // registered like any other, it has its route, OpenAPI operation, typed client and audit record, and
4
4
  // its policy is decided by `guard()` like every other write. The gate the agent meets lives in
5
- // `confirmation-gate.ts`, applied by `defineAppMcp({ confirmations })`.
5
+ // `confirmation-gate.ts`, applied by `defineAppMcp({ confirmations })` for an MCP server and registered
6
+ // by name for an in-app agent's `agent({ tools })`.
6
7
 
7
8
  import type { Action } from '@ultimat3/action';
8
- import { action } from '@ultimat3/action';
9
+ import { action, registerToolGate } from '@ultimat3/action';
9
10
  import type { Clock, SealKeySource } from '@ultimat3/core';
10
11
  import { finiteCount, systemClock } from '@ultimat3/core';
11
12
  import type { KnownPermission, PolicyArgs, PolicyDecision } from '@ultimat3/policy';
12
13
  import { can, denied } from '@ultimat3/policy';
13
14
  import type { JsonValue } from '@ultimat3/schema';
14
15
  import { t } from '@ultimat3/schema';
16
+ import type { McpApproversResolver } from './confirmation-approvers';
17
+ import { matchesApprover } from './confirmation-approvers';
15
18
  import { decideConfirmation } from './confirmation-decide';
16
19
  import { McpConfirmationToolUnknownError } from './confirmation-errors';
20
+ import type { McpConfirmationEvidence } from './confirmation-evidence';
21
+ import { confirmationToolGate } from './confirmation-gate';
22
+ import { McpConfirmationQuorumInvalidError } from './confirmation-quorum-errors';
17
23
  import type { McpConfirmation, McpConfirmationStore } from './confirmation-store';
18
24
 
25
+ /** Room for any detached signature encoding (Ed25519 base64url is 86); a megabyte vote is not one. */
26
+ const MAX_SIGNATURE_LENGTH = 4096;
27
+
19
28
  /** Ten minutes: long enough for a person to read a request, short enough to go stale. */
20
29
  export const DEFAULT_MCP_CONFIRMATION_TTL_MS = 600_000;
21
30
 
@@ -25,6 +34,8 @@ const decisionInput = () =>
25
34
  decision: t.enum(['view', 'approve', 'reject'] as const),
26
35
  /** What the person approves: the `arguments` `view` returned. Required to approve. */
27
36
  arguments: t.optional(t.record(t.json())),
37
+ /** The approver's signature over `signingPayload`, under `evidence`. Bounded: it is stored. */
38
+ signature: t.optional(t.string.max(MAX_SIGNATURE_LENGTH)),
28
39
  });
29
40
 
30
41
  const decisionOutput = () =>
@@ -35,6 +46,9 @@ const decisionOutput = () =>
35
46
  decidedAt: t.nullable(t.date),
36
47
  expiresAt: t.date,
37
48
  arguments: t.record(t.json()),
49
+ quorum: t.number,
50
+ approvedBy: t.array(t.string),
51
+ signingPayload: t.string,
38
52
  });
39
53
 
40
54
  type DecisionInput = ReturnType<typeof decisionInput>;
@@ -48,10 +62,15 @@ export interface McpConfirmationDecision {
48
62
  readonly id: string;
49
63
  readonly decision: 'view' | 'approve' | 'reject';
50
64
  readonly arguments?: Readonly<Record<string, JsonValue>>;
65
+ /** The approver's signature over the `signingPayload` `view` returned, under `evidence`. */
66
+ readonly signature?: string;
51
67
  }
52
68
 
53
69
  export interface McpConfirmationsInput<TTools extends string = string> {
54
- /** The tools whose every call waits for a person. Each must be one the server projects. */
70
+ /**
71
+ * The tools whose every call waits for a person, from `defineAppMcp({ confirmations })` AND from
72
+ * `agent({ tools })`. Each must be one the server projects.
73
+ */
55
74
  readonly tools: readonly TTools[];
56
75
  /** `memoryConfirmationStore()` for a test or `x dev`; `postgresConfirmationStore()` for a fleet. */
57
76
  readonly store: McpConfirmationStore;
@@ -72,6 +91,19 @@ export interface McpConfirmationsInput<TTools extends string = string> {
72
91
  readonly audit?: boolean | undefined;
73
92
  /** Where the seal key is read (`.secrets.key` / `ULTIMATE_SECRETS_KEY`). Defaults to the app's. */
74
93
  readonly sealKeys?: SealKeySource | undefined;
94
+ /**
95
+ * N of M: per call, from its validated arguments, how many DISTINCT approvers matching `from`
96
+ * must approve. Stored on the row when it opens. Declared, the requesting actor never counts (nor
97
+ * an impersonated decider), and one approver counts once. Absent: one decision by anyone the
98
+ * policy admits.
99
+ */
100
+ readonly approvers?: McpApproversResolver | undefined;
101
+ /**
102
+ * Signed decisions: every approval carries a signature over `signingPayload` (the row's id, tool
103
+ * and keyed argument digest), checked by `verify` against keys registered to the approver at the
104
+ * decision, stored with the vote, and re-checked from the stored row before the call runs.
105
+ */
106
+ readonly evidence?: McpConfirmationEvidence | undefined;
75
107
  }
76
108
 
77
109
  /** The decision action, carrying what the gate needs. `defineAppMcp({ confirmations })` reads it. */
@@ -83,6 +115,8 @@ export interface McpConfirmations<TTools extends string = string>
83
115
  readonly ttlMs: number;
84
116
  readonly clock: Clock;
85
117
  readonly sealKeys: SealKeySource;
118
+ readonly approvers: McpApproversResolver | undefined;
119
+ readonly evidence: McpConfirmationEvidence | undefined;
86
120
  }
87
121
 
88
122
  /**
@@ -109,8 +143,20 @@ export function mcpConfirmations<const TTools extends string>(
109
143
  1,
110
144
  );
111
145
  const clock = input.clock ?? systemClock;
112
- const { store, check } = input;
146
+ const { store, check, approvers, evidence } = input;
113
147
  const sealKeys: SealKeySource = input.sealKeys ?? {};
148
+ if (approvers !== undefined && typeof approvers !== 'function') {
149
+ throw new McpConfirmationQuorumInvalidError({
150
+ tool: input.tools.join(', '),
151
+ reason: 'approvers is not a function of the call',
152
+ });
153
+ }
154
+ if (evidence !== undefined && typeof evidence.verify !== 'function') {
155
+ throw new McpConfirmationQuorumInvalidError({
156
+ tool: input.tools.join(', '),
157
+ reason: 'evidence declares no verify function, so no signature could ever be checked',
158
+ });
159
+ }
114
160
 
115
161
  const decide = action({
116
162
  input: decisionInput(),
@@ -118,23 +164,46 @@ export function mcpConfirmations<const TTools extends string>(
118
164
  // The agent refusal is IN the policy, so it is decided by `guard()` — the one authz path — and
119
165
  // reads as the same `X_FORBIDDEN` on every surface. A confirmation an agent can grant is a
120
166
  // confirmation the agent that asked can grant.
121
- policy: can<unknown, McpConfirmation>(input.permission, (args) => {
167
+ policy: can<McpConfirmationDecision, McpConfirmation>(input.permission, (args) => {
122
168
  if (args.actor?.kind === 'agent') return denied('mcp-confirmation.agent-decider');
123
- return (check ?? sameTenant)(args);
169
+ const standing = approverStanding(args);
170
+ return standing ?? (check ?? sameTenant)(args);
124
171
  }),
125
172
  ...(input.audit === true ? { audit: true } : {}),
126
173
  row: async ({ input: asked }) => (await store.get(asked.id)) ?? null,
127
174
  // The view and the decision: state only — the policy above has already decided who.
128
175
  handle: ({ input: asked, ctx }) =>
129
- decideConfirmation({ store, clock, sealKeys }, asked, ctx.actor.id),
176
+ decideConfirmation({ store, clock, sealKeys, evidence }, asked, ctx.actor.id),
130
177
  });
131
- return Object.assign(decide, {
178
+ const confirmations = Object.assign(decide, {
132
179
  tools: Object.freeze([...input.tools]),
133
180
  store,
134
181
  ttlMs,
135
182
  clock,
136
183
  sealKeys,
184
+ approvers,
185
+ evidence,
137
186
  });
187
+ // On the declaration, so there is no `agent({ confirmations })` for an author to forget. A worker
188
+ // holds it only if it imports this module, which is `X_ROLE_LOAD_INCOMPLETE` when it would not.
189
+ registerToolGate(confirmations.tools, confirmationToolGate(confirmations));
190
+ return confirmations;
191
+ }
192
+
193
+ /**
194
+ * A decision on a row opened under `approvers`: the requester never decides its own request, an
195
+ * impersonated actor never stands in for the person it wears, and the decider must match one of the
196
+ * row's stored selectors. `undefined` defers to `check`. `view` stays the policy's alone.
197
+ */
198
+ function approverStanding(
199
+ args: PolicyArgs<McpConfirmationDecision, McpConfirmation>,
200
+ ): PolicyDecision | undefined {
201
+ const { actor, row } = args;
202
+ if (row === null || row.approvers === null || args.input.decision === 'view') return undefined;
203
+ if (actor === null || actor.id === row.actorId) return denied('mcp-confirmation.requester');
204
+ if (actor.onBehalfOf !== undefined) return denied('mcp-confirmation.impersonated');
205
+ if (!matchesApprover(actor, row.approvers)) return denied('mcp-confirmation.not-an-approver');
206
+ return undefined;
138
207
  }
139
208
 
140
209
  /**
@@ -0,0 +1,62 @@
1
+ // `graph.query` — `x impact` and `x graph --from --to` as one dev tool: what an edit to a file or a
2
+ // primitive reaches, or the chain linking two nodes. The graph is `@ultimat3/manifest`'s, a tier
3
+ // this package may not import, so the CLI answers through `DevCapabilities.queryGraph`.
4
+
5
+ import type { AnyMcpTool, ToolArgs } from './registry';
6
+ import { jsonResult, textResult } from './registry';
7
+
8
+ /** One question of the app graph: `impact` of one node, or the `path` between two. */
9
+ export type DevGraphQuestion =
10
+ | { readonly kind: 'impact'; readonly node: string }
11
+ | { readonly kind: 'path'; readonly from: string; readonly to: string };
12
+
13
+ export interface DevGraphHost {
14
+ /** `x impact <node> --json`'s data, or `x graph --from --to --json`'s. Throws on an unknown node. */
15
+ queryGraph(question: DevGraphQuestion): Promise<unknown>;
16
+ }
17
+
18
+ const ASK =
19
+ 'graph.query takes { node } for what a change to it reaches, or { from, to } for the path between two — e.g. { "node": "apps/web/app/posts/queries/post-by-id.ts" }';
20
+
21
+ /** The question the arguments ask, or `undefined` for a combination that asks none. */
22
+ export function graphQuestion(args: ToolArgs): DevGraphQuestion | undefined {
23
+ const text = (key: string): string | undefined => {
24
+ const value = args[key];
25
+ return typeof value === 'string' && value.trim() !== '' ? value : undefined;
26
+ };
27
+ const node = text('node');
28
+ const from = text('from');
29
+ const to = text('to');
30
+ if (node !== undefined && from === undefined && to === undefined) return { kind: 'impact', node };
31
+ if (node === undefined && from !== undefined && to !== undefined) {
32
+ return { kind: 'path', from, to };
33
+ }
34
+ return undefined;
35
+ }
36
+
37
+ export function graphTool(host: DevGraphHost, scope: string): AnyMcpTool {
38
+ return {
39
+ name: 'graph.query',
40
+ description:
41
+ 'What a change reaches, before it is made: { node } (a file path, a primitive name or a node id) ' +
42
+ 'answers the routes, actions, queries, jobs, MCP tools, published operations, tests and budgets ' +
43
+ 'that depend on it, each with the provenance of the edges that reached it; { from, to } answers ' +
44
+ 'the chain of edges linking two nodes. The same graph as `x impact` and `x graph`.',
45
+ scope,
46
+ destructive: false,
47
+ inputSchema: {
48
+ type: 'object',
49
+ properties: {
50
+ node: { type: 'string', description: 'A file path, a primitive name or a node id.' },
51
+ from: { type: 'string', description: 'One end of a path; needs `to`.' },
52
+ to: { type: 'string', description: 'The other end of a path; needs `from`.' },
53
+ },
54
+ additionalProperties: false,
55
+ },
56
+ async handle(args: ToolArgs) {
57
+ const question = graphQuestion(args);
58
+ if (question === undefined) return textResult(ASK, true);
59
+ return jsonResult(await host.queryGraph(question));
60
+ },
61
+ };
62
+ }
package/src/dev-server.ts CHANGED
@@ -10,6 +10,8 @@
10
10
  // packages of this same tier, and the shell-side capabilities (db, tests, logs) belong to
11
11
  // the CLI, so this file defines the interface and the CLI satisfies it.
12
12
 
13
+ import type { DevGraphHost } from './dev-graph-tool';
14
+ import { graphTool } from './dev-graph-tool';
13
15
  import type { UiInteractInput, UiInteractResult } from './dev-ui-interact';
14
16
  import { uiInteractTools } from './dev-ui-interact';
15
17
  import type {
@@ -130,8 +132,11 @@ export interface DevIntrospection {
130
132
  jobInspect(name: string): unknown;
131
133
  }
132
134
 
133
- /** Shell-side capabilities. Satisfied by the CLI, which owns the process and the DB. */
134
- export interface DevCapabilities {
135
+ /**
136
+ * Shell-side capabilities. Satisfied by the CLI, which owns the process and the DB — and the app
137
+ * graph (`queryGraph`, from `DevGraphHost`), which is `@ultimat3/manifest`'s, a tier beside this one.
138
+ */
139
+ export interface DevCapabilities extends DevGraphHost {
135
140
  readonly database: DatabaseTarget;
136
141
  /**
137
142
  * Run one already-parsed read-only statement under layers 1–2 (a SELECT-only role, a
@@ -229,6 +234,9 @@ export function devTools(host: DevHost): readonly AnyMcpTool[] {
229
234
  textResult(await host.readManifest()),
230
235
  ),
231
236
 
237
+ // What an edit reaches, before it is made: `x impact` / `x graph --from --to` as a tool.
238
+ graphTool(host, DEV_SCOPES.read),
239
+
232
240
  read(
233
241
  'errors.explain',
234
242
  'Explain a stable X_* error code: cause, exact fix command, docs link.',
@@ -1,8 +1,9 @@
1
1
  // The refusals a TRANSPORT raises before dispatch: one message too large for the wire, a caller
2
- // past its rate allowance, an `oauth` block that cannot be published. Split from `errors.ts`,
2
+ // past its rate allowance, an `oauth` block that cannot be published, a protocol version or a
3
+ // mirrored header the request got wrong, a cross-origin page. Split from `errors.ts`,
3
4
  // which keeps the code registry; this module loads it, so every title is registered first.
4
5
 
5
- import { UltimateError } from '@ultimat3/core';
6
+ import { renderFixShellArg, UltimateError } from '@ultimat3/core';
6
7
  // why a side-effect import: the codes these classes raise are REGISTERED by `errors.ts`, and a
7
8
  // process that imports only a transport must still render their titles.
8
9
  import './errors';
@@ -16,7 +17,7 @@ import './errors';
16
17
  * one: the peer sent more in one message than this end agreed to hold, and the two answers must
17
18
  * name the same code so an agent learns it once.
18
19
  *
19
- * Measured through ai-maxxing's `POST /mcp` on 2026-09-07: the 413 was a bare `-32600` reading
20
+ * Measured through one adopter's `POST /mcp` on 2026-09-07: the 413 was a bare `-32600` reading
20
21
  * `request body is at least N bytes, limit is M` — two numbers and no next step, while the 401,
21
22
  * 403 and 429 beside it all carried `{ code, cause, fix }`. A box agent sending a large
22
23
  * `promptSession` had nothing to act on. The fix names both moves, send less or raise the cap,
@@ -92,3 +93,83 @@ export class McpOAuthInvalidError extends UltimateError {
92
93
  });
93
94
  }
94
95
  }
96
+
97
+ /**
98
+ * A request naming a revision this server does not serve — MCP's `UnsupportedProtocolVersionError`
99
+ * (`-32022`, HTTP 400). `supported` travels as data so a modern client retries without a human: a
100
+ * dual-era client that reads this body knows the server is modern and stays modern.
101
+ */
102
+ export class McpProtocolUnsupportedError extends UltimateError {
103
+ constructor(input: { requested: string | null; supported: readonly string[] }) {
104
+ super({
105
+ code: 'X_MCP_PROTOCOL_UNSUPPORTED',
106
+ cause:
107
+ input.requested === null
108
+ ? 'the request names its protocol version with a value that is not a string'
109
+ : `the request names protocol version "${input.requested}", which this server does not serve`,
110
+ fix: `{ "_meta": { "io.modelcontextprotocol/protocolVersion": "${input.supported[0] ?? ''}" } } in params, with the MCP-Protocol-Version header equal to it; served: ${input.supported.join(', ')}`,
111
+ meta: { supported: input.supported, requested: input.requested },
112
+ });
113
+ }
114
+ }
115
+
116
+ /** The mirrored request headers, by the body field each must equal. */
117
+ export type McpMirroredHeader = 'MCP-Protocol-Version' | 'Mcp-Method' | 'Mcp-Name';
118
+
119
+ /**
120
+ * A modern request whose mirrored header is absent or disagrees with its body — MCP's
121
+ * `HeaderMismatch` (`-32020`, HTTP 400). Refused because a load balancer may route on the header
122
+ * while this server runs the body. The header's VALUE is never echoed: it is the caller's input.
123
+ */
124
+ export class McpHeaderMismatchError extends UltimateError {
125
+ constructor(input: { header: McpMirroredHeader; absent: boolean }) {
126
+ super({
127
+ code: 'X_MCP_HEADER_MISMATCH',
128
+ cause: input.absent
129
+ ? `the ${input.header} header is absent from a request that carries a protocol version in _meta`
130
+ : `the ${input.header} header does not equal the body's ${BODY_FIELD[input.header]}`,
131
+ fix: `{ "MCP-Protocol-Version": "<params._meta version>", "Mcp-Method": "<method>", "Mcp-Name": "<params.name or params.uri>" } as the request headers — ${input.header} equal to the body's ${BODY_FIELD[input.header]}, a non-ASCII Mcp-Name as =?base64?<utf-8 base64>?=`,
132
+ meta: { header: input.header },
133
+ });
134
+ }
135
+ }
136
+
137
+ const BODY_FIELD: Readonly<Record<McpMirroredHeader, string>> = {
138
+ 'MCP-Protocol-Version': 'params._meta["io.modelcontextprotocol/protocolVersion"]',
139
+ 'Mcp-Method': 'method',
140
+ 'Mcp-Name': 'params.name or params.uri',
141
+ };
142
+
143
+ /**
144
+ * A request carrying an `Origin` that core's `proveSameOrigin` cannot show is this app's — not the
145
+ * route's own public origin, not listed in `http.cors.origins` — refused 403 before the token is read
146
+ * (MCP Streamable HTTP: "If the Origin header is present and invalid, servers MUST respond with
147
+ * HTTP 403"). It does NOT catch a DNS-rebound name: that page's Host and Origin agree, so a server
148
+ * that serves only this machine refuses the Host first (`X_MCP_HOST_REFUSED`).
149
+ */
150
+ export class McpOriginRefusedError extends UltimateError {
151
+ constructor(input: { reason: string; endpoint: string }) {
152
+ super({
153
+ code: 'X_MCP_ORIGIN_REFUSED',
154
+ cause: `a browser page called POST /mcp and could not be shown to be this app: ${input.reason}`,
155
+ fix: `curl -X POST ${renderFixShellArg(input.endpoint, 'http://localhost:3000/mcp')} -H 'authorization: Bearer <token>' — no Origin header; a page on a sibling origin is listed in http.cors.origins`,
156
+ });
157
+ }
158
+ }
159
+
160
+ /**
161
+ * A request naming a Host that is not this machine, on a server that only ever serves this machine
162
+ * (`x mcp serve`). The `Origin` cannot carry this check: a DNS-rebound page's Host and Origin agree.
163
+ * The host decides what is loopback (the CLI's `isLoopbackHostname`, `/_x`'s rule); this renders it.
164
+ * Never echoes the Host it was sent.
165
+ */
166
+ export class McpHostRefusedError extends UltimateError {
167
+ constructor(input: { endpoint: string }) {
168
+ super({
169
+ code: 'X_MCP_HOST_REFUSED',
170
+ cause:
171
+ 'the request named a Host that is not localhost, a *.localhost name or a loopback address — the shape of a DNS-rebinding page, whose Host and Origin agree',
172
+ fix: `curl -X POST ${renderFixShellArg(input.endpoint, 'http://localhost:9229/mcp')} -H 'authorization: Bearer <token>'`,
173
+ });
174
+ }
175
+ }
package/src/errors.ts CHANGED
@@ -40,6 +40,27 @@ export const MCP_ERROR_CODES = [
40
40
  'X_MCP_EFFECT_CONFLICT',
41
41
  'X_MCP_WRONG_TOOL',
42
42
  'X_MCP_USER_CONFIRMATION_REQUIRED',
43
+ 'X_MCP_PROTOCOL_UNSUPPORTED',
44
+ 'X_MCP_HEADER_MISMATCH',
45
+ 'X_MCP_ORIGIN_REFUSED',
46
+ 'X_MCP_HOST_REFUSED',
47
+ 'X_MCP_REMOTE_TOOL_CHANGED',
48
+ 'X_MCP_REMOTE_REFUSED',
49
+ 'X_MCP_JOB_TOOL_INVALID',
50
+ 'X_MCP_RECIPE_TOOL_UNKNOWN',
51
+ 'X_MCP_RECIPE_EXAMPLE_INVALID',
52
+ 'X_MCP_RECIPE_UNKNOWN',
53
+ 'X_MCP_RECIPE_URI_RESERVED',
54
+ 'X_MCP_REMOTE_AUTH_REQUIRED',
55
+ 'X_MCP_RECIPE_LINK_DANGLING',
56
+ 'X_MCP_CONFIRMATION_QUORUM_PENDING',
57
+ 'X_MCP_CONFIRMATION_EVIDENCE_INVALID',
58
+ 'X_MCP_CONFIRMATION_QUORUM_INVALID',
59
+ 'X_MCP_CATALOG_TOOL_DUPLICATE',
60
+ 'X_MCP_CATALOG_UNRESOLVED',
61
+ 'X_MCP_TENANT_REQUIRED',
62
+ 'X_MCP_TENANT_UNRESOLVED',
63
+ 'X_MCP_TENANT_INVALID',
43
64
  ] as const;
44
65
 
45
66
  export type McpErrorCode = (typeof MCP_ERROR_CODES)[number];
@@ -84,6 +105,31 @@ export const MCP_ERROR_TITLES: Readonly<Record<McpErrorCode, string>> = {
84
105
  X_MCP_WRONG_TOOL: 'a meta-split action was called through the wrong dispatcher',
85
106
  X_MCP_USER_CONFIRMATION_REQUIRED:
86
107
  'a delete_resource commit did not carry confirmed_by_user: true',
108
+ X_MCP_PROTOCOL_UNSUPPORTED:
109
+ 'the request names an MCP protocol version this server does not serve',
110
+ X_MCP_HEADER_MISMATCH: 'an MCP request header is absent or disagrees with the body',
111
+ X_MCP_ORIGIN_REFUSED: 'an MCP request came from a browser page on another origin',
112
+ X_MCP_HOST_REFUSED: 'an MCP request named a Host that is not this machine',
113
+ X_MCP_REMOTE_TOOL_CHANGED: "a remote MCP server's tool no longer matches tools.lock.json",
114
+ X_MCP_REMOTE_REFUSED: 'a remote MCP server failed or refused the call',
115
+ X_MCP_JOB_TOOL_INVALID: 'jobTool() was declared with something it cannot run',
116
+ X_MCP_RECIPE_TOOL_UNKNOWN: 'an MCP recipe step names a tool this server does not project',
117
+ X_MCP_RECIPE_EXAMPLE_INVALID: "an MCP recipe step's example fails its tool's input",
118
+ X_MCP_RECIPE_UNKNOWN: 'an error links to a docs://recipes/ URI no recipe serves',
119
+ X_MCP_RECIPE_URI_RESERVED: 'docs://recipes/ is owned by recipes:',
120
+ X_MCP_REMOTE_AUTH_REQUIRED: 'a remote MCP server needs authorization this app does not hold',
121
+ X_MCP_RECIPE_LINK_DANGLING: 'a recipe links to a docs://recipes/ URI no recipe serves',
122
+ X_MCP_CONFIRMATION_QUORUM_PENDING:
123
+ 'an MCP confirmation needs more approvers before the call runs',
124
+ X_MCP_CONFIRMATION_EVIDENCE_INVALID:
125
+ 'an MCP confirmation approval carries no valid signed evidence',
126
+ X_MCP_CONFIRMATION_QUORUM_INVALID:
127
+ 'mcpConfirmations approvers resolved a quorum no approver set can meet',
128
+ X_MCP_CATALOG_TOOL_DUPLICATE: 'a per-caller MCP catalog names one tool twice',
129
+ X_MCP_CATALOG_UNRESOLVED: 'a per-caller MCP catalog could not be resolved',
130
+ X_MCP_TENANT_REQUIRED: 'an MCP call names no tenant',
131
+ X_MCP_TENANT_UNRESOLVED: 'the tenant of an MCP call could not be resolved',
132
+ X_MCP_TENANT_INVALID: 'defineAppMcp declares its tenant argument inconsistently',
87
133
  };
88
134
 
89
135
  // Titles must be registered for `format()` to render the contract's first line. Every code above is
package/src/exposed.ts CHANGED
@@ -10,16 +10,26 @@
10
10
  // shortcut buys convenience while changing no execution path.
11
11
 
12
12
  import { listActions } from '@ultimat3/action';
13
+ import { isMcpExposed } from '@ultimat3/core';
13
14
  import { listQueries } from '@ultimat3/query';
14
15
  import type { ProjectablePrimitive } from './from-action';
15
16
  import { primitiveFromAction, primitiveFromQuery } from './projectable';
16
17
 
17
18
  /**
18
- * Every registered action and query, as projectable primitives. `toolsFrom` applies the opt-in
19
- * filter, so this deliberately does NOT filter: one place decides what "exposed" means.
19
+ * Every registered action and query that opted in, as projectable primitives — asked with core's
20
+ * `isMcpExposed`, the one predicate `toolsFrom` asks again. Filtered BEFORE projecting: projecting
21
+ * reserves the `idempotencyKey` argument and builds the wire schema, so an action no surface
22
+ * serves could refuse the boot (`X_MCP_IDEMPOTENCY_KEY_SHADOWED`) of every tool that is served.
20
23
  *
21
24
  * Read eagerly, at the moment `defineAppMcp` runs — register the app's primitives first.
22
25
  */
23
26
  export function exposedPrimitives(): readonly ProjectablePrimitive[] {
24
- return [...listActions().map(primitiveFromAction), ...listQueries().map(primitiveFromQuery)];
27
+ return [
28
+ ...listActions()
29
+ .filter((target) => isMcpExposed(target.mcp))
30
+ .map(primitiveFromAction),
31
+ ...listQueries()
32
+ .filter((target) => isMcpExposed(target.mcp))
33
+ .map(primitiveFromQuery),
34
+ ];
25
35
  }
@@ -15,6 +15,7 @@ import {
15
15
  stringField,
16
16
  } from '@ultimat3/core';
17
17
  import { statusFor } from '@ultimat3/http';
18
+ import { screenRecipeLink } from './recipe-links';
18
19
 
19
20
  export interface FrameworkError {
20
21
  readonly code: string;
@@ -64,10 +65,16 @@ export function asFrameworkError(error: unknown): FrameworkError | undefined {
64
65
  // above, so the substitute is the one command that explains exactly this code.
65
66
  fix: stringField(error, 'fix') ?? `x errors explain ${code}`,
66
67
  ...(callerFix === undefined ? {} : { callerFix }),
67
- ...(docs === undefined || docs === '' || docs === ERROR_DOCS_URL ? {} : { docs }),
68
+ // A recipe link nothing serves is dropped (and logged): an agent is never sent nowhere.
69
+ ...(docs === undefined || docs === '' || docs === ERROR_DOCS_URL
70
+ ? {}
71
+ : withLink(screenRecipeLink(docs, code))),
68
72
  };
69
73
  }
70
74
 
75
+ const withLink = (docs: string | undefined): { readonly docs?: string } =>
76
+ docs === undefined ? {} : { docs };
77
+
71
78
  /**
72
79
  * The fixed sentence a remote caller reads in place of a hidden cause. The real one is in the
73
80
  * audit line this call wrote and in the error monitor, never on the wire.
@@ -20,7 +20,7 @@
20
20
  // import this one to return it. `cross-surface.test.ts` pins `toolFrom` to the served entry.
21
21
 
22
22
  import type { Actor, McpExposureDeclaration } from '@ultimat3/core';
23
- import { isMcpExposed } from '@ultimat3/core';
23
+ import { isMcpExposed, toolDescription } from '@ultimat3/core';
24
24
  import { McpToolUndeclaredError } from './errors';
25
25
  import type { ListedPrimitive } from './projectable';
26
26
  import { asProjectable } from './projectable';
@@ -93,8 +93,7 @@ export function toolFrom(listed: ListedPrimitive): AnyMcpTool {
93
93
  // The primitive's own name and nothing else: `mcp.name` was a second naming field no
94
94
  // declaration could set, deleted in 25.0.0 (plan 101, M4).
95
95
  const name = primitive.name;
96
- const description =
97
- primitive.mcp?.description ?? primitive.description ?? `Run the "${primitive.name}" action.`;
96
+ const description = toolDescription(primitive);
98
97
  const mutates = primitive.mutates ?? true;
99
98
  const visibleTo = primitive.mcp?.visibleTo;
100
99
  const listParams = primitive.mcp?.listParams;