@ultimat3/mcp 31.49.0 → 31.51.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/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
  });
@@ -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
  }
@@ -1,12 +1,12 @@
1
1
  /**
2
- * Recipes from a folder of markdown, one file per recipe, its body served verbatim. The file name
3
- * is the recipe's name; an optional `---` block sets `title:` and `description:`, else the first
4
- * `# ` heading and the first paragraph do. Its steps are its ```call fences — `tool {json}` — so
5
- * the boot check holds a markdown recipe to the catalog exactly as a structured one.
2
+ * Recipes from a folder of markdown, one file per recipe, body as written (LF line ends, outer
3
+ * blank lines trimmed): file name = name, a
4
+ * sub-folder = section, `---` sets `title:`/`description:`/`aliases:` (else heading, paragraph).
5
+ * Its ```call fences — `tool {json}` — are its steps, boot-checked like a structured recipe's.
6
6
  */
7
7
 
8
- // why: Bun exposes no path-join primitive; the folder is the app's.
9
- import { join } from 'node:path';
8
+ // why: Bun exposes no path-join primitive; `sep` says whether `\` separates paths here.
9
+ import { join, sep } from 'node:path';
10
10
  import { McpRecipeExampleInvalidError } from './recipe-errors';
11
11
  import type { McpRecipe, McpRecipeStep } from './recipes';
12
12
 
@@ -15,19 +15,33 @@ export const PLACEHOLDER = /^<([A-Za-z][\w-]*)>$/;
15
15
 
16
16
  const FENCE = /^```call[^\S\n]*\n([\s\S]*?)\n```[^\S\n]*$/gm;
17
17
 
18
- /** Every `*.md` under `dir`, sorted by name: the same folder is the same recipes, in order. */
18
+ /**
19
+ * Every `*.md` in `dir` (section `recipes`), then every `<section>/*.md` one folder down, each
20
+ * sorted by path: the same folder is the same recipes, in order. `recipes/<name>.md` and
21
+ * `<name>.md` are one URI. A folder name that is not lowercase letters and digits in
22
+ * `-`-separated groups is refused at boot, like a name. The file opened is the path the glob
23
+ * returned: on POSIX `\` is a file-name character, so only Windows' separator is normalised.
24
+ */
19
25
  export async function markdownRecipes(input: { readonly dir: string }): Promise<McpRecipe[]> {
20
- const files = [...new Bun.Glob('*.md').scanSync({ cwd: input.dir })].sort();
26
+ const top = [...new Bun.Glob('*.md').scanSync({ cwd: input.dir })].sort();
27
+ const nested = [...new Bun.Glob('*/*.md').scanSync({ cwd: input.dir })].sort();
21
28
  const recipes: McpRecipe[] = [];
22
- for (const file of files) {
29
+ for (const file of [...top, ...nested]) {
23
30
  const text = await Bun.file(join(input.dir, file)).text();
24
- recipes.push(recipeFromMarkdown(file.replace(/\.md$/, ''), text));
31
+ const path = sep === '\\' ? file.replaceAll('\\', '/') : file;
32
+ const slash = path.indexOf('/');
33
+ const name = path.slice(slash + 1).replace(/\.md$/, '');
34
+ recipes.push(
35
+ slash === -1
36
+ ? recipeFromMarkdown(name, text)
37
+ : recipeFromMarkdown(name, text, path.slice(0, slash)),
38
+ );
25
39
  }
26
40
  return recipes;
27
41
  }
28
42
 
29
43
  /** One file's recipe. A fenced call that does not parse is refused naming the file and fence. */
30
- export function recipeFromMarkdown(name: string, text: string): McpRecipe {
44
+ export function recipeFromMarkdown(name: string, text: string, section?: string): McpRecipe {
31
45
  const { fields, body } = frontMatter(text.replace(/\r\n/g, '\n'));
32
46
  const lines = body.split('\n');
33
47
  const heading = lines
@@ -35,15 +49,28 @@ export function recipeFromMarkdown(name: string, text: string): McpRecipe {
35
49
  ?.slice(2)
36
50
  .trim();
37
51
  const paragraph = firstParagraph(lines);
52
+ const aliases = fields.get('aliases');
38
53
  return {
39
54
  name,
55
+ ...(section === undefined ? {} : { section }),
56
+ ...(aliases === undefined ? {} : { aliases: aliasList(aliases) }),
40
57
  title: fields.get('title') ?? heading ?? name,
41
58
  description: fields.get('description') ?? paragraph ?? '',
42
59
  steps: fencedCalls(name, body),
43
- body: body.trim() === '' ? '' : `${body.trim()}\n`,
60
+ body: withoutOuterBlankLines(body),
44
61
  };
45
62
  }
46
63
 
64
+ /** Whole blank lines only: a content line's own spaces are Markdown (an indented code block). */
65
+ function withoutOuterBlankLines(body: string): string {
66
+ const lines = body.split('\n');
67
+ // Spaces and tabs only: a no-break space is content.
68
+ const blank = (line: string | undefined) => line !== undefined && /^[ \t]*$/.test(line);
69
+ while (blank(lines[0])) lines.shift();
70
+ while (blank(lines.at(-1))) lines.pop();
71
+ return lines.length === 0 ? '' : `${lines.join('\n')}\n`;
72
+ }
73
+
47
74
  function frontMatter(text: string): {
48
75
  readonly fields: ReadonlyMap<string, string>;
49
76
  readonly body: string;
@@ -59,6 +86,31 @@ function frontMatter(text: string): {
59
86
  return { fields, body: text.slice(end + 5) };
60
87
  }
61
88
 
89
+ /** `aliases: refund, money back` or `aliases: [refund, "money, back"]`: a quoted comma stays. */
90
+ function aliasList(value: string): readonly string[] {
91
+ const entries: string[] = [];
92
+ let entry = '';
93
+ let started = false;
94
+ let quote: string | undefined;
95
+ for (const char of value.replace(/^\[(.*)\]$/, '$1')) {
96
+ if (quote === undefined && char === ',') {
97
+ entries.push(entry);
98
+ entry = '';
99
+ started = false;
100
+ continue;
101
+ }
102
+ // A quote opens only at an entry's start: `customer's invoice` is one plain alias.
103
+ if (char === quote) quote = undefined;
104
+ else if (quote === undefined && (char === '"' || char === "'") && !started) quote = char;
105
+ if (char.trim() !== '') started = true;
106
+ entry += char;
107
+ }
108
+ entries.push(entry);
109
+ return entries
110
+ .map((alias) => alias.trim().replace(/^(["'])(.*)\1$/, '$2'))
111
+ .filter((alias) => alias !== '');
112
+ }
113
+
62
114
  function firstParagraph(lines: readonly string[]): string | undefined {
63
115
  const start = lines.findIndex(
64
116
  (line) => line.trim() !== '' && !line.startsWith('#') && !line.startsWith('```'),
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * `replayRecipes()` — a recipe's contract test: every step's example CALLED through the real server
3
- * as `caller` (placeholders filled), every `docs://recipes/` link read. No such tool, refused
3
+ * as `caller` (placeholders filled), every link into `recipes`, the sections of `recipes` or
4
+ * `sections` read — replaying a subset, pass the server's other sections. No such tool, refused
4
5
  * arguments, a refusing policy or a dangling link fail it; a tool's own refusal is the tool working.
5
6
  */
6
7
 
@@ -8,7 +9,7 @@ import { isJsonObject, renderCauseValue } from '@ultimat3/core';
8
9
  import { McpRecipeExampleInvalidError, McpRecipeLinkDanglingError } from './recipe-errors';
9
10
  import { fillPlaceholders } from './recipe-markdown';
10
11
  import type { McpRecipe } from './recipes';
11
- import { recipeLinks, recipeUri } from './recipes';
12
+ import { recipeKey, recipeLinks, sectionsOf } from './recipes';
12
13
  import type { McpCaller } from './registry';
13
14
  import type { McpServer } from './server';
14
15
 
@@ -16,6 +17,11 @@ export interface ReplayOptions {
16
17
  readonly caller: McpCaller;
17
18
  /** `"<postId>"` in an example becomes `placeholders.postId`. */
18
19
  readonly placeholders?: Readonly<Record<string, unknown>>;
20
+ /**
21
+ * More sections the server's recipes serve, beyond those `recipes` holds: links into them are
22
+ * read too. Replaying a subset, a link into a section only the rest use is otherwise unread.
23
+ */
24
+ readonly sections?: readonly string[];
19
25
  }
20
26
 
21
27
  export interface ReplayReport {
@@ -47,6 +53,7 @@ export async function replayRecipes(
47
53
  const links: string[] = [];
48
54
  const failed: string[] = [];
49
55
  const dangling: string[] = [];
56
+ const sections = new Set([...sectionsOf(recipes), ...(options.sections ?? [])]);
50
57
  let id = 0;
51
58
  const rpc = async (method: string, params: Record<string, unknown>) => {
52
59
  id += 1;
@@ -62,8 +69,7 @@ export async function replayRecipes(
62
69
  const reason = unreached(answer);
63
70
  if (reason !== undefined) failed.push(`${at}: ${reason}`);
64
71
  }
65
- for (const name of recipeLinks(recipe)) {
66
- const uri = recipeUri(name);
72
+ for (const uri of recipeLinks(recipe, sections)) {
67
73
  const answer = await rpc('resources/read', { uri });
68
74
  links.push(uri);
69
75
  if (answer === null || 'error' in answer) {
@@ -75,7 +81,8 @@ export async function replayRecipes(
75
81
  if (dangling.length > 0) {
76
82
  throw new McpRecipeLinkDanglingError({
77
83
  offenders: dangling,
78
- recipes: recipes.map((recipe) => recipe.name).sort(),
84
+ recipes: recipes.map(recipeKey).sort(),
85
+ at: 'unread',
79
86
  });
80
87
  }
81
88
  return { calls, links };