@ultimat3/mcp 31.48.0 → 31.50.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.
package/src/index.ts CHANGED
@@ -138,9 +138,16 @@ export {
138
138
  McpGroupConflictError,
139
139
  McpGroupUnknownError,
140
140
  McpListParamsInvalidError,
141
+ McpSplitInvalidError,
141
142
  McpSurfaceInvalidError,
142
143
  } from './meta-errors';
143
144
  export type { McpEffectClass } from './meta-split';
145
+ export type {
146
+ McpSplitCall,
147
+ McpSplitDispatcher,
148
+ McpSplitField,
149
+ McpSplitOptions,
150
+ } from './meta-split-options';
144
151
  export type {
145
152
  McpResourceGroup,
146
153
  McpResourceGroups,
@@ -165,15 +172,17 @@ export { markdownRecipes } from './recipe-markdown';
165
172
  export type { ReplayOptions, ReplayReport } from './recipe-replay';
166
173
  export { replayRecipes } from './recipe-replay';
167
174
  export type { McpRecipe, McpRecipeStep } from './recipes';
168
- export type { ExtraRecipes } from './recipes-tool';
175
+ export type { DocsToolOptions, ExtraRecipes } from './recipes-tool';
169
176
  export type {
170
177
  AnyMcpTool,
171
178
  ContentBlock,
172
179
  McpCaller,
180
+ McpDoor,
173
181
  McpRole,
174
182
  McpTool,
175
183
  McpToolAnnotations,
176
184
  McpToolResult,
185
+ McpUrlElicitation,
177
186
  McpVerbClass,
178
187
  McpVisibility,
179
188
  ToolArgs,
@@ -248,6 +257,7 @@ export { MCP_RATE_LIMITS, MCP_UNAUTHENTICATED_LIMIT, mcpHttpRoute } from './tran
248
257
  export { mcpHostRefused } from './transport-http-answers';
249
258
  export type { StdioTransportInput } from './transport-stdio';
250
259
  export { serveStdio } from './transport-stdio';
260
+ export { URL_ELICITATION_KEY, withUrlElicitation } from './url-elicitation';
251
261
  export type { ArgIssue, ArgValidation } from './validate-args';
252
262
  export { validateArgs } from './validate-args';
253
263
  export type {
package/src/meta-call.ts CHANGED
@@ -8,7 +8,7 @@ import { META_UNKNOWN_FIX } from './meta-errors';
8
8
  import type { MetaHost } from './meta-host';
9
9
  import { resolveAddressed } from './meta-host';
10
10
  import { splitCall } from './meta-split-call';
11
- import { DESCRIBE_RESOURCE, LIST_RESOURCES, MetaSurface } from './meta-surface';
11
+ import { DESCRIBE_RESOURCE, LIST_RESOURCES, type MetaSurface } from './meta-surface';
12
12
  import type { McpCaller } from './registry';
13
13
  import { jsonResult, textResult } from './registry';
14
14
  import { validateArgs } from './validate-args';
@@ -32,7 +32,7 @@ export async function metaCall(
32
32
  ): Promise<JsonRpcResponse | undefined> {
33
33
  const { id, name, caller } = request;
34
34
  const surface = meta.surfaceFor(caller) === 'meta-split' ? 'meta-split' : 'meta';
35
- const entry = MetaSurface.entriesFor(surface).find((tool) => tool.name === name);
35
+ const entry = meta.entries(surface).find((tool) => tool.name === name);
36
36
  if (entry === undefined) {
37
37
  return meta.isGrouped(name) ? host.notFound(id, name, caller, META_UNKNOWN_FIX) : undefined;
38
38
  }
@@ -93,15 +93,39 @@ export class McpEffectConflictError extends UltimateError {
93
93
  }
94
94
  }
95
95
 
96
- /** The right action, the wrong dispatcher. Names the dispatcher that runs it; nothing ran. */
96
+ /** `split:` cannot be served as declared — see `meta-split-options.ts`. */
97
+ export class McpSplitInvalidError extends UltimateError {
98
+ constructor(input: { cause: string }) {
99
+ super({
100
+ code: 'X_MCP_SPLIT_INVALID',
101
+ cause: input.cause,
102
+ fix: "defineAppMcp({ surface: 'meta-split', split: { fields: { reason: { description: 'Why this call is made.' } }, stricter: (call) => false } }) — the cause names the entry to fix; a field is a plain name other than resource, action, params, live and confirmed_by_user",
103
+ });
104
+ }
105
+ }
106
+
107
+ /**
108
+ * The right action, the wrong dispatcher. Names the dispatcher that runs it; nothing ran.
109
+ * `demanded`: the app's `stricter` hook sent THIS call to the stricter door, by its arguments.
110
+ */
97
111
  export class McpWrongToolError extends UltimateError {
98
112
  readonly useTool: string;
99
113
 
100
- constructor(input: { resource: string; action: string; called: string; useTool: string }) {
114
+ constructor(input: {
115
+ resource: string;
116
+ action: string;
117
+ called: string;
118
+ useTool: string;
119
+ demanded?: boolean;
120
+ }) {
101
121
  const call = `${input.useTool}({ resource: "${input.resource}", action: "${input.action}", params })`;
122
+ const subject =
123
+ input.demanded === true
124
+ ? `this call of ${input.resource}.${input.action}`
125
+ : `${input.resource}.${input.action}`;
102
126
  super({
103
127
  code: 'X_MCP_WRONG_TOOL',
104
- cause: `${input.resource}.${input.action} is not run by ${input.called}; it is run by ${input.useTool} (wrong_tool_for_action). Nothing ran`,
128
+ cause: `${subject} is not run by ${input.called}; it is run by ${input.useTool} (wrong_tool_for_action). Nothing ran`,
105
129
  fix: `${call} # the same params, on ${input.useTool}`,
106
130
  callerFix: `call ${call} with the same params`,
107
131
  meta: {
@@ -2,6 +2,9 @@
2
2
  // visibility gate) → the tool its effect names, else `X_MCP_WRONG_TOOL` → the shared resolver →
3
3
  // for `delete_resource`, preview unless `live: true`, and commit only with `confirmed_by_user:
4
4
  // true` → the server's `dispatch`. Every call that runs goes through the flat path's one dispatch.
5
+ //
6
+ // `delete_resource` is the STRICTER door, so it also takes a write, and a read the app's
7
+ // `stricter` hook demands it for (`meta-split-options.ts`). The other two are never widened.
5
8
 
6
9
  import { isJsonObject } from '@ultimat3/core';
7
10
  import {
@@ -12,6 +15,7 @@ import {
12
15
  import type { MetaHost } from './meta-host';
13
16
  import { resolveAddressed } from './meta-host';
14
17
  import { DELETE_RESOURCE, effectOf, toolForEffect } from './meta-split';
18
+ import { demandsStricter, fieldsOf } from './meta-split-options';
15
19
  import type { MetaSurface } from './meta-surface';
16
20
  import { schemaOf } from './meta-surface';
17
21
  import type { AnyMcpTool, McpCaller, ToolArgs } from './registry';
@@ -38,24 +42,54 @@ export async function splitCall(
38
42
  meta: MetaSurface,
39
43
  request: SplitRequest,
40
44
  ): Promise<JsonRpcResponse> {
41
- const { id, name, caller, args } = request;
45
+ const { id, name, args } = request;
42
46
  const resource = args['resource'] as string;
43
47
  const action = args['action'] as string;
48
+ // The door rides on the caller from here on, so every audit entry of this call names it and a
49
+ // handler can read the envelope's declared fields — which are never part of the action input.
50
+ const door = { tool: name, fields: fieldsOf(meta.split, name, args) };
51
+ const caller: McpCaller = { ...request.caller, door };
44
52
  const tool = meta.locate(resource, action, caller);
45
53
  if (tool === undefined) return host.notFound(id, action, caller, META_UNKNOWN_FIX);
46
54
  // `assertEffects` refused an undeclared write at boot, so `effectOf` answers for a served tool.
47
55
  const effect = effectOf(tool) ?? 'delete';
48
56
  const useTool = toolForEffect(effect);
49
- if (useTool !== name) {
57
+ const wrongTool = (use: string, demanded = false): JsonRpcResponse =>
50
58
  // Visibility already passed, and the effect is what `list_resources` shows this caller: the
51
59
  // refusal names nothing the catalog did not.
52
- const wrong = new McpWrongToolError({ resource, action, called: name, useTool });
53
- return host.refuse(id, action, wrong, caller);
54
- }
60
+ host.refuse(
61
+ id,
62
+ action,
63
+ new McpWrongToolError({ resource, action, called: name, useTool: use, demanded }),
64
+ caller,
65
+ );
55
66
  const params = isJsonObject(args['params']) ? args['params'] : {};
67
+ const hooked = meta.split?.stricter !== undefined;
68
+ /** Whether the app sends THIS call to `delete_resource`; its throw is the call's refusal. */
69
+ const demanded = async (valid: ToolArgs): Promise<boolean | JsonRpcResponse> => {
70
+ try {
71
+ const asking = { caller, tool: name, resource, action, effect, params: valid };
72
+ return await demandsStricter(meta.split, { ...asking, fields: door.fields });
73
+ } catch (thrown) {
74
+ return host.refuse(id, action, thrown, caller);
75
+ }
76
+ };
56
77
  if (name !== DELETE_RESOURCE) {
57
- return host.dispatch(id, action, resolveAddressed(host, tool, params, caller), caller);
78
+ if (useTool !== name) return wrongTool(useTool);
79
+ const resolved = resolveAddressed(host, tool, params, caller);
80
+ if (!hooked || resolved.kind !== 'ok') return host.dispatch(id, action, resolved, caller);
81
+ // The hook is asked only about a call that would otherwise run: in scope, valid, admitted.
82
+ const refused = admitted(tool, caller);
83
+ if (refused !== undefined) return host.refuse(id, action, refused, caller);
84
+ const stricter = await demanded(resolved.args);
85
+ if (typeof stricter !== 'boolean') return stricter;
86
+ return stricter
87
+ ? wrongTool(DELETE_RESOURCE, true)
88
+ : host.dispatch(id, action, resolved, caller);
58
89
  }
90
+ // The stricter door: a delete's own, a write's whenever it is sent here, and a read's only when
91
+ // the app demands it for this call — a read nobody gated has one door, `read_resource`.
92
+ if (effect === 'read' && !hooked) return wrongTool(useTool);
59
93
  const lifted = liftToolArgs(args, params, tool);
60
94
  const resolved = resolveAddressed(host, tool, lifted.params, caller);
61
95
  if (resolved.kind !== 'ok') return host.dispatch(id, action, resolved, caller);
@@ -63,6 +97,11 @@ export async function splitCall(
63
97
  // this gets the denial, never an answer that rehearses the call.
64
98
  const refused = admitted(tool, caller);
65
99
  if (refused !== undefined) return host.refuse(id, action, refused, caller);
100
+ if (effect === 'read') {
101
+ const stricter = await demanded(resolved.args);
102
+ if (typeof stricter !== 'boolean') return stricter;
103
+ if (!stricter) return wrongTool(useTool);
104
+ }
66
105
  if (lifted.live && lifted.confirmed !== true) {
67
106
  return host.refuse(
68
107
  id,
@@ -0,0 +1,180 @@
1
+ // `split:` — what an app adds to the `'meta-split'` dispatchers: string fields of its own on their
2
+ // envelopes (a `reason`, a change ticket), and a `stricter` hook that sends one call to
3
+ // `delete_resource` by its arguments.
4
+ //
5
+ // A field belongs to the CALL, never to the action: it is validated on the envelope and handed on
6
+ // as `caller.door.fields`, so no action input ever carries it. Boot check and the published
7
+ // entries here; the dispatch is `meta-split-call.ts`.
8
+
9
+ import { renderCauseValue } from '@ultimat3/core';
10
+ import { McpSplitInvalidError } from './meta-errors';
11
+ import type { McpEffectClass } from './meta-split';
12
+ import { SPLIT_DISPATCHERS, SPLIT_TOOL_ENTRIES } from './meta-split';
13
+ import type { McpCaller, ToolArgs, ToolListEntry } from './registry';
14
+ import type { JsonSchema } from './wire';
15
+
16
+ /** One of `read_resource`, `write_resource`, `delete_resource`. */
17
+ export type McpSplitDispatcher = 'read_resource' | 'write_resource' | 'delete_resource';
18
+
19
+ /** One app-declared string field of a dispatcher envelope. */
20
+ export interface McpSplitField {
21
+ /** What the field is for. Published by `tools/list`; an agent reads only this. */
22
+ readonly description: string;
23
+ /** The dispatchers that take it. Absent: all three. */
24
+ readonly tools?: readonly McpSplitDispatcher[];
25
+ /** A call through those dispatchers without it is refused as invalid arguments. Default `false`. */
26
+ readonly required?: boolean;
27
+ /** The longest value accepted. */
28
+ readonly maxLength?: number;
29
+ }
30
+
31
+ /** One call, as the `stricter` hook is asked about it: located, in scope, valid, admitted. */
32
+ export interface McpSplitCall {
33
+ readonly caller: McpCaller;
34
+ /** The dispatcher the call came through. */
35
+ readonly tool: string;
36
+ readonly resource: string;
37
+ readonly action: string;
38
+ /** What the action is: a read, or its declared effect. */
39
+ readonly effect: McpEffectClass;
40
+ /** The action's parameters, validated against its schema. */
41
+ readonly params: ToolArgs;
42
+ /** The declared envelope fields this call carried. */
43
+ readonly fields: Readonly<Record<string, string>>;
44
+ }
45
+
46
+ export interface McpSplitOptions {
47
+ /** Field name → its declaration. A name the envelope already owns is refused at boot. */
48
+ readonly fields?: Readonly<Record<string, McpSplitField>>;
49
+ /**
50
+ * Whether THIS call must come through `delete_resource`, where it previews unless `live: true`
51
+ * and commits only with `confirmed_by_user: true`. Asked for a read on `read_resource` and a
52
+ * write on `write_resource` — demanded there, the call is refused `X_MCP_WRONG_TOOL` naming
53
+ * `delete_resource` and nothing runs — and for a read on `delete_resource`, which runs there
54
+ * only when demanded. Fail-closed: anything but the literal `false` demands it, and a throw
55
+ * fails the call. A write may always come through `delete_resource`; nothing widens
56
+ * `write_resource` or `read_resource`.
57
+ */
58
+ readonly stricter?: (call: McpSplitCall) => boolean | Promise<boolean>;
59
+ }
60
+
61
+ const FIELD_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
62
+ /** What the envelopes already mean by these names. */
63
+ const OWNED: readonly string[] = [
64
+ 'resource',
65
+ 'action',
66
+ 'params',
67
+ 'live',
68
+ 'confirmed_by_user',
69
+ // A plain name by the pattern, and never a key: assigning it sets a prototype.
70
+ '__proto__',
71
+ ];
72
+
73
+ /** Boot: the options can be served, and every field is a plain name the envelope does not own. */
74
+ export function assertSplit(split: McpSplitOptions, canSplit: boolean): void {
75
+ const refuse = (cause: string): never => {
76
+ throw new McpSplitInvalidError({ cause });
77
+ };
78
+ if (!canSplit) {
79
+ refuse(
80
+ "split: is declared, and surface is never 'meta-split', so no caller is served a dispatcher",
81
+ );
82
+ }
83
+ const stricter: unknown = split.stricter;
84
+ if (stricter !== undefined && typeof stricter !== 'function') {
85
+ refuse(`split.stricter is ${renderCauseValue(stricter)}, and it has to be a function`);
86
+ }
87
+ for (const [name, field] of Object.entries(split.fields ?? {})) {
88
+ const shown = renderCauseValue(name);
89
+ if (!FIELD_NAME.test(name) || OWNED.includes(name)) {
90
+ refuse(
91
+ `split.fields names ${shown}, which is not a plain argument name, or is one the dispatcher envelope already owns`,
92
+ );
93
+ }
94
+ const declared: Partial<McpSplitField> = field ?? {};
95
+ if (typeof declared.description !== 'string' || declared.description.trim() === '') {
96
+ refuse(`split.fields[${shown}] has no description, and an agent reads only that`);
97
+ }
98
+ const tools: unknown = declared.tools ?? SPLIT_DISPATCHERS;
99
+ if (!Array.isArray(tools)) {
100
+ refuse(`split.fields[${shown}].tools is ${renderCauseValue(tools)}, and it has to be a list`);
101
+ }
102
+ for (const tool of tools as readonly unknown[]) {
103
+ if (typeof tool !== 'string' || !SPLIT_DISPATCHERS.includes(tool)) {
104
+ refuse(
105
+ `split.fields[${shown}].tools names ${renderCauseValue(tool)}, which is not a dispatcher`,
106
+ );
107
+ }
108
+ }
109
+ const max: unknown = declared.maxLength;
110
+ if (max !== undefined && (typeof max !== 'number' || !Number.isInteger(max) || max < 1)) {
111
+ refuse(
112
+ `split.fields[${shown}].maxLength is ${renderCauseValue(max)}, and it has to be a positive integer`,
113
+ );
114
+ }
115
+ }
116
+ }
117
+
118
+ /** The fields `dispatcher` takes, in declaration order. */
119
+ function fieldsFor(
120
+ split: McpSplitOptions,
121
+ dispatcher: string,
122
+ ): readonly (readonly [string, McpSplitField])[] {
123
+ return Object.entries(split.fields ?? {}).filter(
124
+ ([, field]) => field.tools === undefined || field.tools.some((tool) => tool === dispatcher),
125
+ );
126
+ }
127
+
128
+ /** The three dispatchers as THIS server publishes them: the constant entries plus its fields. */
129
+ export function splitEntries(split: McpSplitOptions | undefined): readonly ToolListEntry[] {
130
+ if (split?.fields === undefined) return SPLIT_TOOL_ENTRIES;
131
+ return SPLIT_TOOL_ENTRIES.map((entry) => {
132
+ const fields = fieldsFor(split, entry.name);
133
+ if (fields.length === 0) return entry;
134
+ const properties: Record<string, JsonSchema> = { ...entry.inputSchema.properties };
135
+ for (const [name, field] of fields) {
136
+ const value: JsonSchema = {
137
+ type: 'string',
138
+ description: field.description,
139
+ ...(field.maxLength === undefined ? {} : { maxLength: field.maxLength }),
140
+ };
141
+ Object.defineProperty(properties, name, { value, enumerable: true });
142
+ }
143
+ const required = fields.filter(([, field]) => field.required === true).map(([name]) => name);
144
+ return {
145
+ ...entry,
146
+ inputSchema: {
147
+ ...entry.inputSchema,
148
+ properties,
149
+ required: [...(entry.inputSchema.required ?? []), ...required],
150
+ },
151
+ };
152
+ });
153
+ }
154
+
155
+ /** The declared fields one validated envelope carried — what `caller.door.fields` holds. */
156
+ export function fieldsOf(
157
+ split: McpSplitOptions | undefined,
158
+ dispatcher: string,
159
+ args: ToolArgs,
160
+ ): Readonly<Record<string, string>> {
161
+ const out: Record<string, string> = {};
162
+ if (split === undefined) return out;
163
+ for (const [name] of fieldsFor(split, dispatcher)) {
164
+ const value = Object.hasOwn(args, name) ? args[name] : undefined;
165
+ if (typeof value === 'string') Object.defineProperty(out, name, { value, enumerable: true });
166
+ }
167
+ return out;
168
+ }
169
+
170
+ /**
171
+ * Ask the hook. Anything but the literal `false` demands the stricter door: a hook that forgets
172
+ * to answer must not be the one that lets a call through the lighter one.
173
+ */
174
+ export async function demandsStricter(
175
+ split: McpSplitOptions | undefined,
176
+ call: McpSplitCall,
177
+ ): Promise<boolean> {
178
+ if (split?.stricter === undefined) return false;
179
+ return (await split.stricter(call)) !== false;
180
+ }
package/src/meta-split.ts CHANGED
@@ -3,7 +3,8 @@
3
3
  //
4
4
  // A client decides whether to ask its user from a TOOL's annotations alone, and a directory refuses
5
5
  // a tool that both reads and writes — so the split is by tool, never by a flag inside the envelope.
6
- // Catalog and boot check here; the dispatch is `meta-split-call.ts`, on the shared path.
6
+ // Catalog and boot check here; the dispatch is `meta-split-call.ts`, on the shared path. What an
7
+ // app adds to the envelopes is `meta-split-options.ts`.
7
8
 
8
9
  import type { McpEffect } from '@ultimat3/core';
9
10
  import { McpEffectConflictError, McpEffectUndeclaredError } from './meta-errors';
@@ -96,7 +97,7 @@ export const SPLIT_TOOL_ENTRIES: readonly ToolListEntry[] = [
96
97
  name: DELETE_RESOURCE,
97
98
  title: 'Delete, send or spend',
98
99
  description:
99
- "Runs one action that archives, cancels or deletes, sends something outside the app, or commits money: { resource, action, params, live, confirmed_by_user }. live: false or absent answers a preview — the framework's, which runs nothing, or the action's own when its input declares live; live: true runs it, only with confirmed_by_user: true. Runs the actions list_resources tags (delete).",
100
+ "Runs one action that archives, cancels or deletes, sends something outside the app, or commits money: { resource, action, params, live, confirmed_by_user }. live: false or absent answers a preview — the framework's, which runs nothing, or the action's own when its input declares live; live: true runs it, only with confirmed_by_user: true. Runs the actions list_resources tags (delete), and a (write) action sent here for the same preview and confirmation.",
100
101
  inputSchema: envelope(
101
102
  {
102
103
  live: {
@@ -16,6 +16,8 @@ import { assertListParams, listParamsSchema } from './list-params';
16
16
  import { oneLineParams } from './meta-catalog-render';
17
17
  import { McpGroupConflictError, McpGroupUnknownError, McpSurfaceInvalidError } from './meta-errors';
18
18
  import { assertEffects, SPLIT_DISPATCHERS, SPLIT_TOOL_ENTRIES } from './meta-split';
19
+ import type { McpSplitOptions } from './meta-split-options';
20
+ import { assertSplit, splitEntries } from './meta-split-options';
19
21
  import type { AnyMcpTool, McpCaller, ToolListEntry } from './registry';
20
22
  import { visibleToCaller } from './registry';
21
23
  import type { JsonSchema } from './wire';
@@ -150,6 +152,8 @@ export class MetaSurface {
150
152
  readonly #tools: ReadonlyMap<string, AnyMcpTool>;
151
153
  /** Every grouped tool's effect was checked at boot, so `'meta-split'` may be served. */
152
154
  readonly #split: boolean;
155
+ /** The app's `split:` — its envelope fields and `stricter` hook. Read by the split dispatch. */
156
+ readonly split: McpSplitOptions | undefined;
153
157
 
154
158
  private constructor(
155
159
  option: McpSurfaceOption,
@@ -157,8 +161,10 @@ export class MetaSurface {
157
161
  home: ReadonlyMap<string, string>,
158
162
  tools: ReadonlyMap<string, AnyMcpTool>,
159
163
  split: boolean,
164
+ options: McpSplitOptions | undefined,
160
165
  ) {
161
166
  this.#split = split;
167
+ this.split = options;
162
168
  this.#option = option;
163
169
  this.#groups = groups;
164
170
  this.#home = home;
@@ -173,6 +179,7 @@ export class MetaSurface {
173
179
  readonly surface?: McpSurfaceOption | undefined;
174
180
  readonly groups?: McpResourceGroups | undefined;
175
181
  readonly tools: readonly AnyMcpTool[];
182
+ readonly split?: McpSplitOptions | undefined;
176
183
  }): MetaSurface | undefined {
177
184
  for (const tool of input.tools) {
178
185
  if (tool.listParams !== undefined) {
@@ -182,6 +189,7 @@ export class MetaSurface {
182
189
  const option = input.surface ?? 'flat';
183
190
  const entries = Object.entries(input.groups ?? {});
184
191
  if (option === 'flat') {
192
+ if (input.split !== undefined) assertSplit(input.split, false);
185
193
  if (entries.length === 0) return undefined;
186
194
  throw new McpSurfaceInvalidError({
187
195
  cause: `groups: declares ${entries.length} resource(s), and surface is 'flat' for every caller, so no caller would ever see them`,
@@ -221,7 +229,8 @@ export class MetaSurface {
221
229
  option === 'meta-split' ||
222
230
  (typeof option === 'function' && grouped.some((tool) => tool.effect !== undefined));
223
231
  if (split) assertEffects(grouped);
224
- return new MetaSurface(option, new Map(entries), home, tools, split);
232
+ if (input.split !== undefined) assertSplit(input.split, split);
233
+ return new MetaSurface(option, new Map(entries), home, tools, split, input.split);
225
234
  }
226
235
 
227
236
  /**
@@ -245,6 +254,13 @@ export class MetaSurface {
245
254
  return surface === 'meta' ? META_TOOL_ENTRIES : [...CATALOG_ENTRIES, ...SPLIT_TOOL_ENTRIES];
246
255
  }
247
256
 
257
+ /** `entriesFor` as THIS server publishes it: the dispatchers carry the app's `split.fields`. */
258
+ entries(surface: Exclude<McpSurface, 'flat'>): readonly ToolListEntry[] {
259
+ return surface === 'meta' || this.split?.fields === undefined
260
+ ? MetaSurface.entriesFor(surface)
261
+ : [...CATALOG_ENTRIES, ...splitEntries(this.split)];
262
+ }
263
+
248
264
  /** True when a META caller must reach this tool through a dispatcher, not by its name. */
249
265
  isGrouped(name: string): boolean {
250
266
  return this.#home.has(name);
@@ -139,7 +139,8 @@ export function stamped(
139
139
  const meta = isJsonObject(result['_meta']) ? result['_meta'] : {};
140
140
  return resultResponse(response.id, {
141
141
  ...result,
142
- resultType: 'complete',
142
+ // `input_required` is the one other type this server answers (`url-elicitation.ts`).
143
+ resultType: result['resultType'] === 'input_required' ? 'input_required' : 'complete',
143
144
  _meta: { ...meta, [META_SERVER_INFO]: serverInfo },
144
145
  ...(CACHEABLE.has(method) ? { ttlMs: 0, cacheScope: 'private' } : {}),
145
146
  });
@@ -30,10 +30,15 @@
30
30
  * - CONTROL THE SERVER (`pg_reload_*`, `pg_rotate_*`, `pg_switch_*`, `pg_promote`,
31
31
  * `pg_wal_replay_*`) — the family `pg_cancel_backend`/`pg_terminate_backend` established;
32
32
  * - CONSUME THE REPLICATION STREAM (`pg_create_*`, `pg_drop_*`, `pg_replication_*`,
33
- * `pg_logical_*`) — `pg_logical_slot_get_changes` advances a slot's confirmed position. The
34
- * catalog VIEWS beside them (`pg_replication_slots`) are read `from`, never called;
33
+ * `pg_logical_*`, `pg_copy_*`, `pg_sync_replication_*`) — `pg_logical_slot_get_changes` advances
34
+ * a slot's confirmed position, and copying or syncing a slot creates one outside the
35
+ * transaction. The catalog VIEWS beside them (`pg_replication_slots`) are read `from`, never
36
+ * called;
37
+ * - RUN A BASE BACKUP (`pg_backup_*`, and `pg_start_backup`/`pg_stop_backup` before 15) — server
38
+ * control again, forcing a checkpoint;
35
39
  * - WRITE A FILE (`pg_file_*`) — the other half of `pg_read_*`;
36
- * - WRITE THE CATALOG (`pg_import_*`) — `pg_import_system_collations` inserts `pg_collation` rows;
40
+ * - WRITE THE CATALOG (`pg_import_*`, `pg_restore_*`, `pg_clear_*`) — `pg_import_system_collations`
41
+ * inserts `pg_collation` rows; 18's `pg_restore_relation_stats` rewrites `pg_class`;
37
42
  * - RUN A QUERY HANDED TO IT AS TEXT (`query_to_xml*`, `cursor_to_xml*`, `table_to_xml*`,
38
43
  * `schema_to_xml*`, `database_to_xml*`, `ts_stat`, `ts_rewrite`) — the statement is a string
39
44
  * literal, which every pass of the scan blanks by design, so whatever it calls is invisible.
@@ -50,7 +55,10 @@ const FORBIDDEN_FUNCTIONS = [
50
55
  'lo_',
51
56
  'nextval',
52
57
  'pg_advisory_',
58
+ 'pg_backup_',
53
59
  'pg_cancel_backend',
60
+ 'pg_clear_',
61
+ 'pg_copy_',
54
62
  'pg_create_',
55
63
  'pg_current_xact_id',
56
64
  'pg_drop_',
@@ -63,14 +71,18 @@ const FORBIDDEN_FUNCTIONS = [
63
71
  'pg_read_',
64
72
  'pg_reload_',
65
73
  'pg_replication_',
74
+ 'pg_restore_',
66
75
  'pg_rotate_',
67
76
  'pg_sleep',
77
+ 'pg_start_backup',
68
78
  'pg_stat_file',
69
79
  'pg_stat_reset',
70
80
  // Not reachable from `pg_stat_reset`: the extension spells the same reset with the statistics
71
81
  // view's name in the middle, so a prefix of one is not a prefix of the other.
72
82
  'pg_stat_statements_reset',
83
+ 'pg_stop_backup',
73
84
  'pg_switch_',
85
+ 'pg_sync_replication_',
74
86
  'pg_terminate_backend',
75
87
  'pg_try_advisory_',
76
88
  'pg_wal_replay_',
@@ -19,11 +19,13 @@ const READ_LEADERS = new Set(['select', 'with', 'explain', 'show', 'table', 'val
19
19
  /**
20
20
  * Keywords that make a statement a write. Includes transaction control (a session the tool
21
21
  * left open is a lock held on a shared dev DB), `set`/`copy` (session mutation, file I/O),
22
- * and `analyze` — `EXPLAIN ANALYZE` executes the plan and `ANALYZE t` rewrites statistics,
23
- * so both are refused rather than special-cased. One rule, no exceptions to remember.
22
+ * and `analyze` (with `analyse`, the spelling Postgres also accepts) — `EXPLAIN ANALYZE` executes
23
+ * the plan and `ANALYZE t` rewrites statistics, so both are refused rather than special-cased. One
24
+ * rule, no exceptions to remember.
24
25
  */
25
26
  const WRITE_KEYWORDS = new Set([
26
27
  'alter',
28
+ 'analyse',
27
29
  'analyze',
28
30
  'begin',
29
31
  'call',
@@ -121,6 +123,18 @@ export function assertReadOnlyQuery(sql: string): string {
121
123
  );
122
124
  }
123
125
  }
126
+ // `explain ("analyze")` is `explain (analyze)`: the option list names options, and a quoted
127
+ // name is the same option — so it is read in the form that keeps identifier content. Only the
128
+ // option list: a column quoted as `"analyze"` elsewhere is a column.
129
+ if (
130
+ leader === 'explain' &&
131
+ explainOptions(stripLiteralsAndComments(sql, 'keep')).some(ANALYZES)
132
+ ) {
133
+ throw rejected(
134
+ 'the statement contains the mutating keyword "analyze" as a quoted EXPLAIN option',
135
+ 'SELECT * FROM <table> LIMIT 10 -- or EXPLAIN with no ANALYZE: db.query never executes the plan it describes',
136
+ );
137
+ }
124
138
  // A family refuses a CALL, never a bare word: scanning every word rejected a column named
125
139
  // `pg_sleep_for_seconds`, and scanning the blanked form missed `"pg_advisory_lock"(1)`, which
126
140
  // is the same call wearing quotes. So this pass reads the form that keeps identifier content.
@@ -147,6 +161,14 @@ export function assertReadOnlyQuery(sql: string): string {
147
161
  return verbatim(sql);
148
162
  }
149
163
 
164
+ const ANALYZES = (word: string): boolean => word === 'analyze' || word === 'analyse';
165
+
166
+ /** The words of `explain ( … )`'s option list, lower-cased; none when it has no list. */
167
+ function explainOptions(kept: string): readonly string[] {
168
+ const list = /^\s*explain\s*\(([^)]*)\)/i.exec(kept)?.[1] ?? '';
169
+ return list.toLowerCase().match(WORD) ?? [];
170
+ }
171
+
150
172
  /**
151
173
  * The caller's bytes, minus surrounding whitespace and one trailing `;`. Anything past that
152
174
  * semicolon is whitespace or a comment — the single-statement check above already proved the
@@ -44,17 +44,22 @@ export class McpRecipeUnknownError extends UltimateError {
44
44
  }
45
45
 
46
46
  export class McpRecipeUriReservedError extends UltimateError {
47
- constructor(input: { readonly uri: string; readonly reason: 'resource' | 'duplicate' | 'name' }) {
47
+ constructor(input: {
48
+ readonly uri: string;
49
+ readonly reason: 'resource' | 'duplicate' | 'name' | 'section';
50
+ }) {
48
51
  const why =
49
52
  input.reason === 'resource'
50
- ? 'resources: holds it beside recipes:, and docs://recipes/ is owned by recipes:'
53
+ ? 'resources: holds it beside recipes:, and every docs://<section>/ a recipe uses is owned by recipes:'
51
54
  : input.reason === 'duplicate'
52
- ? 'two recipes share that name'
53
- : 'a recipe name is lowercase letters, digits and -';
55
+ ? 'two recipes share that URI'
56
+ : input.reason === 'section'
57
+ ? 'a recipe section is lowercase letters and digits in groups joined by single -'
58
+ : 'a recipe name is lowercase letters and digits in groups joined by single -';
54
59
  super({
55
60
  code: 'X_MCP_RECIPE_URI_RESERVED',
56
61
  cause: `${renderCauseValue(input.uri)}: ${why}`,
57
- fix: "recipes: [{ name: 'issue-a-credit-note', title, description, steps }] # one name each, [a-z0-9-]; move a hand-written docs://recipes/ resource here",
62
+ fix: "recipes: [{ name: 'issue-a-credit-note', section: 'billing', title, description, steps }] # one URI each; section is optional (default recipes); name and section are a-z0-9 groups joined by single -; move a hand-written docs://<section>/ resource here",
58
63
  meta: { uri: input.uri },
59
64
  });
60
65
  }
@@ -64,11 +69,18 @@ export class McpRecipeLinkDanglingError extends UltimateError {
64
69
  constructor(input: {
65
70
  readonly offenders: readonly string[];
66
71
  readonly recipes: readonly string[];
72
+ /** `unread`: replay could not read it as its caller — missing, or hidden from that caller. */
73
+ readonly at?: 'boot' | 'unread';
67
74
  }) {
75
+ const unread = input.at === 'unread';
68
76
  super({
69
77
  code: 'X_MCP_RECIPE_LINK_DANGLING',
70
- cause: `a recipe links to a docs://recipes/ URI no recipe on this server serves: ${input.offenders.join('; ')} (served: ${input.recipes.join(', ') || 'none'})`,
71
- fix: 'recipes: [...(await markdownRecipes({ dir })), <the missing recipe>] # or correct the link in the recipe the cause names',
78
+ cause: unread
79
+ ? `a recipe links to a docs://<section>/ URI its replay caller could not read — no recipe serves it, or one does that this caller cannot see: ${input.offenders.join('; ')} (replayed: ${input.recipes.join(', ') || 'none'})`
80
+ : `a recipe links to a docs://<section>/ URI, in a section this server's recipes serve, that no recipe serves: ${input.offenders.join('; ')} (served: ${input.recipes.join(', ') || 'none'})`,
81
+ fix: unread
82
+ ? 'replayRecipes(server, recipes, { ...options, caller: <one who can follow every linked recipe> }) # keep sections and placeholders; or correct the link in the recipe the cause names'
83
+ : 'recipes: [...(await markdownRecipes({ dir })), <the missing recipe>] # or correct the link in the recipe the cause names',
72
84
  meta: { offenders: [...input.offenders] },
73
85
  });
74
86
  }