@ultimat3/mcp 29.4.0 → 30.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CLAUDE.md +54 -59
  2. package/README.md +259 -2
  3. package/package.json +21 -10
  4. package/src/app-catalog.ts +84 -0
  5. package/src/app-tool.ts +6 -2
  6. package/src/app-tools.ts +80 -5
  7. package/src/audit-hook.ts +7 -1
  8. package/src/audit.ts +12 -1
  9. package/src/catalog-errors.ts +97 -0
  10. package/src/confirmation-approvers.ts +85 -0
  11. package/src/confirmation-decide.ts +78 -8
  12. package/src/confirmation-evidence.ts +118 -0
  13. package/src/confirmation-gate.ts +147 -44
  14. package/src/confirmation-postgres.ts +88 -7
  15. package/src/confirmation-quorum-errors.ts +102 -0
  16. package/src/confirmation-schema.ts +13 -2
  17. package/src/confirmation-store.ts +54 -19
  18. package/src/confirmations.ts +77 -8
  19. package/src/dev-graph-tool.ts +62 -0
  20. package/src/dev-server.ts +10 -2
  21. package/src/errors-transport.ts +84 -3
  22. package/src/errors.ts +46 -0
  23. package/src/exposed.ts +13 -3
  24. package/src/framework-error.ts +8 -1
  25. package/src/from-action.ts +2 -3
  26. package/src/index.ts +102 -1
  27. package/src/job-status-tool.ts +66 -0
  28. package/src/job-tool-errors.ts +15 -0
  29. package/src/job-tool.ts +167 -0
  30. package/src/oauth-metadata.ts +2 -2
  31. package/src/oauth-server.ts +80 -0
  32. package/src/projectable.ts +15 -10
  33. package/src/protocol-era.ts +270 -0
  34. package/src/recipe-errors.ts +75 -0
  35. package/src/recipe-links.ts +49 -0
  36. package/src/recipe-markdown.ts +143 -0
  37. package/src/recipe-replay.ts +101 -0
  38. package/src/recipe-search.ts +82 -0
  39. package/src/recipes-surface.ts +55 -0
  40. package/src/recipes-tool.ts +123 -0
  41. package/src/recipes.ts +167 -0
  42. package/src/registry.ts +5 -0
  43. package/src/remote-client.ts +378 -0
  44. package/src/remote-errors.ts +76 -0
  45. package/src/remote-listen.ts +108 -0
  46. package/src/remote-lock.ts +139 -0
  47. package/src/remote-oauth.ts +258 -0
  48. package/src/remote-schema.ts +51 -0
  49. package/src/remote-tools.ts +157 -0
  50. package/src/remote-wire.ts +121 -0
  51. package/src/resources.ts +84 -13
  52. package/src/runtime-schema.ts +132 -0
  53. package/src/runtime-tool.ts +115 -0
  54. package/src/scopes.ts +8 -1
  55. package/src/server-catalog.ts +200 -0
  56. package/src/server-resources.ts +117 -0
  57. package/src/server-voice.ts +10 -5
  58. package/src/server.ts +149 -168
  59. package/src/tenant.ts +189 -0
  60. package/src/transport-http-answers.ts +124 -0
  61. package/src/transport-http.ts +50 -94
  62. package/src/wire.ts +18 -4
  63. package/src/caller-context.ts +0 -22
@@ -0,0 +1,270 @@
1
+ // Which protocol era one request speaks, and what each era answers: the `_meta` read, the methods
2
+ // per era and the rate-limit class of each, `initialize`'s negotiation, `server/discover`, the stamp
3
+ // every modern result carries, and the mirrored-header check HTTP owes a modern request. Split from
4
+ // `server.ts` so that file stays a dispatch. MCP 2026-07-28, `basic/versioning`.
5
+
6
+ import { McpHeaderMismatchError, McpProtocolUnsupportedError } from './errors-transport';
7
+ import { SPLIT_DISPATCHERS } from './meta-split';
8
+ import type { MetaSurface } from './meta-surface';
9
+ import { MANAGE_RESOURCE, META_TOOL_NAMES } from './meta-surface';
10
+ import type { McpVerbClass, ToolRegistry } from './registry';
11
+ import type { JsonRpcId, JsonRpcRequest, JsonRpcResponse, ServerInfo } from './wire';
12
+ import {
13
+ errorResponse,
14
+ HEADER_MISMATCH,
15
+ INVALID_PARAMS,
16
+ INVALID_REQUEST,
17
+ isJsonRpcRequest,
18
+ isNotification,
19
+ MCP_LEGACY_VERSIONS,
20
+ MCP_MODERN_VERSIONS,
21
+ META_PROTOCOL_VERSION,
22
+ META_SERVER_INFO,
23
+ METHOD_NOT_FOUND,
24
+ paramsOf,
25
+ refusalMessage,
26
+ resultResponse,
27
+ UNSUPPORTED_PROTOCOL_VERSION,
28
+ } from './wire';
29
+
30
+ /** Modern: stateless, versioned per request. Legacy: the `initialize` handshake. */
31
+ export type McpEra = 'modern' | 'legacy';
32
+
33
+ /** Every revision this server speaks: what `-32022` and `server/discover` both name. */
34
+ export const MCP_SUPPORTED_VERSIONS: readonly string[] = [
35
+ ...MCP_MODERN_VERSIONS,
36
+ ...MCP_LEGACY_VERSIONS,
37
+ ];
38
+
39
+ const SHARED = [
40
+ 'tools/list',
41
+ 'tools/call',
42
+ 'resources/list',
43
+ 'resources/read',
44
+ 'resources/templates/list',
45
+ 'prompts/list',
46
+ 'prompts/get',
47
+ ] as const;
48
+
49
+ /** The methods each era answers. `METHODS` and `classifyBody` move with every new one. */
50
+ export const METHODS: Readonly<Record<McpEra, readonly string[]>> = {
51
+ legacy: ['initialize', 'ping', ...SHARED],
52
+ // `ping` and `initialize` do not exist in the modern revision; `server/discover` is mandatory.
53
+ modern: ['server/discover', ...SHARED],
54
+ };
55
+
56
+ /** Each answer is one caller's, so nothing may be shared by an intermediary. */
57
+ const CACHEABLE = new Set([
58
+ 'server/discover',
59
+ 'tools/list',
60
+ 'prompts/list',
61
+ 'resources/list',
62
+ 'resources/read',
63
+ 'resources/templates/list',
64
+ ]);
65
+
66
+ /** What `initialize` and `server/discover` advertise. Every `listChanged` is false: none is sent. */
67
+ export const CAPABILITIES = {
68
+ tools: { listChanged: false },
69
+ resources: { subscribe: false, listChanged: false },
70
+ prompts: { listChanged: false },
71
+ } as const;
72
+
73
+ /** The `_meta` version a request names, or `undefined` for one that names none. */
74
+ export function requestedVersion(body: JsonRpcRequest): unknown {
75
+ const meta = paramsOf(body)?.['_meta'];
76
+ return isRecord(meta) ? meta[META_PROTOCOL_VERSION] : undefined;
77
+ }
78
+
79
+ /**
80
+ * The era of one request. No `_meta` version: legacy, today's behaviour. A modern version: modern.
81
+ * A legacy version in `_meta` is served as that legacy revision — `-32022` lists it as supported,
82
+ * and a client retrying with it must not be refused again. Anything else: unsupported.
83
+ */
84
+ export function eraOf(body: JsonRpcRequest): McpEra | { readonly unsupported: string | null } {
85
+ const version = requestedVersion(body);
86
+ if (version === undefined) return 'legacy';
87
+ if (typeof version !== 'string') return { unsupported: null };
88
+ if ((MCP_MODERN_VERSIONS as readonly string[]).includes(version)) return 'modern';
89
+ if ((MCP_LEGACY_VERSIONS as readonly string[]).includes(version)) return 'legacy';
90
+ return { unsupported: version };
91
+ }
92
+
93
+ /** `UnsupportedProtocolVersionError`: the spec's `{ supported, requested }`, plus our contract. */
94
+ export function unsupportedVersion(id: JsonRpcId, requested: string | null): JsonRpcResponse {
95
+ const error = new McpProtocolUnsupportedError({ requested, supported: MCP_SUPPORTED_VERSIONS });
96
+ return errorResponse(id, UNSUPPORTED_PROTOCOL_VERSION, refusalMessage(error), {
97
+ supported: MCP_SUPPORTED_VERSIONS,
98
+ requested,
99
+ code: error.code,
100
+ fix: error.fix,
101
+ docs: error.docs,
102
+ });
103
+ }
104
+
105
+ /** `initialize`: the client's revision echoed when served, else the newest legacy one. */
106
+ export function initializeResult(
107
+ params: Record<string, unknown> | null,
108
+ serverInfo: ServerInfo,
109
+ instructions: string | undefined,
110
+ ): Record<string, unknown> {
111
+ const offered = params?.['protocolVersion'];
112
+ const served = MCP_LEGACY_VERSIONS.find((version) => version === offered);
113
+ return {
114
+ protocolVersion: served ?? MCP_LEGACY_VERSIONS[0],
115
+ capabilities: CAPABILITIES,
116
+ serverInfo,
117
+ ...(instructions === undefined ? {} : { instructions }),
118
+ };
119
+ }
120
+
121
+ /** `server/discover`'s own fields; `stamped` adds `resultType`, `_meta` and the cache pair. */
122
+ export function discoverResult(instructions: string | undefined): Record<string, unknown> {
123
+ return {
124
+ supportedVersions: MCP_SUPPORTED_VERSIONS,
125
+ capabilities: CAPABILITIES,
126
+ ...(instructions === undefined ? {} : { instructions }),
127
+ };
128
+ }
129
+
130
+ /** A modern result: `resultType`, `serverInfo` in `_meta`, and `ttlMs: 0` where the spec caches. */
131
+ export function stamped(
132
+ response: JsonRpcResponse,
133
+ method: string,
134
+ serverInfo: ServerInfo,
135
+ ): JsonRpcResponse {
136
+ const result = response.result;
137
+ if (!isRecord(result)) return response;
138
+ const meta = isRecord(result['_meta']) ? result['_meta'] : {};
139
+ return resultResponse(response.id, {
140
+ ...result,
141
+ resultType: 'complete',
142
+ _meta: { ...meta, [META_SERVER_INFO]: serverInfo },
143
+ ...(CACHEABLE.has(method) ? { ttlMs: 0, cacheScope: 'private' } : {}),
144
+ });
145
+ }
146
+
147
+ /** Absent and hidden stay one answer per era: `-32602` modern, `-32601` legacy, never `data`. */
148
+ export const resourceNotFoundCode = (era: McpEra): number =>
149
+ era === 'modern' ? INVALID_PARAMS : METHOD_NOT_FOUND;
150
+
151
+ /**
152
+ * Rate-limit class of a body WITHOUT executing it, and WITHOUT a caller — bucket selection is
153
+ * metering, not authorization. All MCP traffic is one `POST /mcp`, so a coarse per-route rule would
154
+ * charge `initialize` and every read to the write bucket and throttle an agent on its handshake.
155
+ * KEEP IN SYNC with `METHODS`: only `tools/call` can reach a tool, on either era.
156
+ */
157
+ export function classifyBody(
158
+ body: unknown,
159
+ meta: MetaSurface | undefined,
160
+ tools: ToolRegistry,
161
+ ): McpVerbClass {
162
+ if (!isJsonRpcRequest(body) || body.method !== 'tools/call') return 'read';
163
+ const params = paramsOf(body);
164
+ const name = params?.['name'];
165
+ // An unresolvable call is refused before it runs, so charging it the strict bucket only costs a
166
+ // broken client — it never hands an unproven verb the cheap one.
167
+ if (typeof name !== 'string') return 'write';
168
+ if (meta !== undefined && (name === MANAGE_RESOURCE || SPLIT_DISPATCHERS.includes(name))) {
169
+ // Billed as the tool it reaches, so the dispatcher is never a cheap door to a write.
170
+ const args = params?.['arguments'];
171
+ const action = isRecord(args) ? args['action'] : undefined;
172
+ return typeof action === 'string' ? tools.verbClass(action) : 'write';
173
+ }
174
+ if (meta !== undefined && META_TOOL_NAMES.includes(name)) return 'read';
175
+ return tools.verbClass(name);
176
+ }
177
+
178
+ /** Methods whose `Mcp-Name` mirrors a body field, and the field. */
179
+ const NAMED: Readonly<Record<string, string>> = {
180
+ 'tools/call': 'name',
181
+ 'prompts/get': 'name',
182
+ 'resources/read': 'uri',
183
+ };
184
+
185
+ /**
186
+ * Over HTTP, a versioned request mirrors its body into headers; one absent or unequal is `-32020`.
187
+ * Also the legacy header check: an `MCP-Protocol-Version` naming no served revision is `-32022`.
188
+ * `undefined`: carry on. Notifications are exempt — the revision defines no header rule for them.
189
+ */
190
+ export function headerRefusal(body: unknown, headers: Headers): JsonRpcResponse | undefined {
191
+ if (!isJsonRpcRequest(body) || isNotification(body)) return undefined;
192
+ const id = body.id ?? null;
193
+ const header = headers.get('mcp-protocol-version');
194
+ const version = requestedVersion(body);
195
+ if (version === undefined) {
196
+ if (header === null || (MCP_LEGACY_VERSIONS as readonly string[]).includes(header)) {
197
+ return undefined;
198
+ }
199
+ // A modern version with no `_meta` is a body that disagrees with its header.
200
+ if ((MCP_MODERN_VERSIONS as readonly string[]).includes(header)) {
201
+ return mismatch(id, 'MCP-Protocol-Version', false);
202
+ }
203
+ return unsupportedVersion(id, header);
204
+ }
205
+ // A non-string `_meta` version is the dispatch's `-32022`, never a header question.
206
+ if (typeof version !== 'string') return undefined;
207
+ if (header !== version) return mismatch(id, 'MCP-Protocol-Version', header === null);
208
+ if (eraOf(body) !== 'modern') return undefined;
209
+ const method = headers.get('mcp-method');
210
+ if (method !== body.method) return mismatch(id, 'Mcp-Method', method === null);
211
+ const field = Object.hasOwn(NAMED, body.method) ? NAMED[body.method] : undefined;
212
+ const expected = field === undefined ? undefined : paramsOf(body)?.[field];
213
+ // A body missing its name is the dispatch's `-32602`; there is nothing to compare against.
214
+ if (typeof expected !== 'string') return undefined;
215
+ const name = headers.get('mcp-name');
216
+ if (name === null) return mismatch(id, 'Mcp-Name', true);
217
+ return decodeHeader(name) === expected ? undefined : mismatch(id, 'Mcp-Name', false);
218
+ }
219
+
220
+ const SENTINEL = /^=\?base64\?(.*)\?=$/;
221
+
222
+ /** `=?base64?…?=` decoded as UTF-8; the value itself otherwise; `undefined` for broken base64. */
223
+ export function decodeHeader(value: string): string | undefined {
224
+ const encoded = SENTINEL.exec(value)?.[1];
225
+ if (encoded === undefined) return value;
226
+ try {
227
+ const bytes = Uint8Array.from(atob(encoded), (char) => char.charCodeAt(0));
228
+ return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
229
+ } catch {
230
+ return undefined;
231
+ }
232
+ }
233
+
234
+ function mismatch(
235
+ id: JsonRpcId,
236
+ header: 'MCP-Protocol-Version' | 'Mcp-Method' | 'Mcp-Name',
237
+ absent: boolean,
238
+ ): JsonRpcResponse {
239
+ const error = new McpHeaderMismatchError({ header, absent });
240
+ return errorResponse(id, HEADER_MISMATCH, refusalMessage(error), {
241
+ code: error.code,
242
+ header,
243
+ fix: error.fix,
244
+ docs: error.docs,
245
+ });
246
+ }
247
+
248
+ /**
249
+ * The HTTP status of one answer: a refused envelope, a version or a header is 400; a method a
250
+ * modern request names and this server does not answer is 404 (the spec's, so a dual-era client
251
+ * can tell it from a legacy server's bare 404); every other JSON-RPC error is a 200.
252
+ */
253
+ export function httpStatusOf(body: unknown, response: JsonRpcResponse): number {
254
+ const code = response.error?.code;
255
+ if (code === undefined) return 200;
256
+ if (code === INVALID_REQUEST && response.id === null) return 400;
257
+ if (code === UNSUPPORTED_PROTOCOL_VERSION || code === HEADER_MISMATCH) return 400;
258
+ if (
259
+ code === METHOD_NOT_FOUND &&
260
+ isJsonRpcRequest(body) &&
261
+ eraOf(body) === 'modern' &&
262
+ !METHODS.modern.includes(body.method)
263
+ ) {
264
+ return 404;
265
+ }
266
+ return 200;
267
+ }
268
+
269
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
270
+ typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -0,0 +1,75 @@
1
+ // The four refusals that keep a recipe from naming a tool, an argument or a URI that is not there.
2
+ // All raised at boot: a stale recipe is a load failure, never an agent following it into nothing.
3
+
4
+ import { renderCauseValue, UltimateError } from '@ultimat3/core';
5
+
6
+ export class McpRecipeToolUnknownError extends UltimateError {
7
+ constructor(input: {
8
+ readonly offenders: readonly string[];
9
+ readonly catalog: readonly string[];
10
+ }) {
11
+ super({
12
+ code: 'X_MCP_RECIPE_TOOL_UNKNOWN',
13
+ cause: `a recipe step names a tool this server does not project: ${input.offenders.join('; ')} (the catalog: ${input.catalog.join(', ')})`,
14
+ fix: 'steps: [{ tool: <a name the cause lists>, why }] # rename step.tool in the recipe the cause names, or expose the tool',
15
+ meta: { offenders: [...input.offenders] },
16
+ });
17
+ }
18
+ }
19
+
20
+ export class McpRecipeExampleInvalidError extends UltimateError {
21
+ constructor(input: { readonly offenders: readonly string[] }) {
22
+ super({
23
+ code: 'X_MCP_RECIPE_EXAMPLE_INVALID',
24
+ cause: `a recipe step's example fails its tool's input: ${input.offenders.join('; ')}`,
25
+ fix: 'example: { … } # correct step.example in the recipe the cause names; the issues name the field',
26
+ meta: { offenders: [...input.offenders] },
27
+ });
28
+ }
29
+ }
30
+
31
+ export class McpRecipeUnknownError extends UltimateError {
32
+ constructor(input: {
33
+ readonly uri: string;
34
+ readonly code?: string;
35
+ readonly recipes: readonly string[];
36
+ }) {
37
+ super({
38
+ code: 'X_MCP_RECIPE_UNKNOWN',
39
+ cause: `${input.code === undefined ? 'an error' : input.code} links to ${renderCauseValue(input.uri)}, and no endpoint's recipes: serves it (served: ${input.recipes.join(', ') || 'none'})`,
40
+ fix: "recipes: [{ name: '<name>', title, description, steps }] # add it to defineAppMcp, or drop docs: from the error",
41
+ meta: { uri: input.uri, ...(input.code === undefined ? {} : { errorCode: input.code }) },
42
+ });
43
+ }
44
+ }
45
+
46
+ export class McpRecipeUriReservedError extends UltimateError {
47
+ constructor(input: { readonly uri: string; readonly reason: 'resource' | 'duplicate' | 'name' }) {
48
+ const why =
49
+ input.reason === 'resource'
50
+ ? 'resources: holds it beside recipes:, and docs://recipes/ is owned by recipes:'
51
+ : input.reason === 'duplicate'
52
+ ? 'two recipes share that name'
53
+ : 'a recipe name is lowercase letters, digits and -';
54
+ super({
55
+ code: 'X_MCP_RECIPE_URI_RESERVED',
56
+ 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",
58
+ meta: { uri: input.uri },
59
+ });
60
+ }
61
+ }
62
+
63
+ export class McpRecipeLinkDanglingError extends UltimateError {
64
+ constructor(input: {
65
+ readonly offenders: readonly string[];
66
+ readonly recipes: readonly string[];
67
+ }) {
68
+ super({
69
+ 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',
72
+ meta: { offenders: [...input.offenders] },
73
+ });
74
+ }
75
+ }
@@ -0,0 +1,49 @@
1
+ // Whether a `docs://recipes/<name>` link on an error goes anywhere. `defineAppMcp` notes the recipes
2
+ // each endpoint serves; the CLI's load check holds every DECLARED link (`defineError({ docs })`) to
3
+ // the union of them, and the render drops — and logs — a link built at a throw site that names none.
4
+ // With no `recipes:` anywhere in the process nothing is judged: the prefix is not claimed yet.
5
+
6
+ import { listErrorCodes, tryUseContext } from '@ultimat3/core';
7
+ import { McpRecipeUnknownError } from './recipe-errors';
8
+ import { recipeNameOf } from './recipes';
9
+
10
+ const SERVED = new Set<string>();
11
+
12
+ export function noteServedRecipes(names: readonly string[]): void {
13
+ for (const name of names) SERVED.add(name);
14
+ }
15
+
16
+ /** Every recipe any endpoint of this process serves. */
17
+ export const servedRecipes = (): ReadonlySet<string> => SERVED;
18
+
19
+ /** The link to render: itself, or `undefined` for a recipe URI nothing serves (logged). */
20
+ export function screenRecipeLink(docs: string, code: string): string | undefined {
21
+ const name = recipeNameOf(docs);
22
+ if (name === undefined || SERVED.size === 0 || SERVED.has(name)) return docs;
23
+ tryUseContext()?.logger.warn('mcp.recipe.link-dropped', { code, uri: docs });
24
+ return undefined;
25
+ }
26
+
27
+ /**
28
+ * Every registered error code whose declared `docs` is a recipe URI none of `served` names. The
29
+ * first is thrown, every one is in its `meta.unresolved`. `served` is the union over endpoints.
30
+ */
31
+ export function assertRecipeLinks(served: ReadonlySet<string>): void {
32
+ if (served.size === 0) return;
33
+ const unresolved = listErrorCodes().filter((entry) => {
34
+ const name = recipeNameOf(entry.docs);
35
+ return name !== undefined && !served.has(name);
36
+ });
37
+ const first = unresolved[0];
38
+ if (first === undefined) return;
39
+ throw new McpRecipeUnknownError({
40
+ uri: first.docs,
41
+ code: unresolved.map((entry) => entry.code).join(', '),
42
+ recipes: [...served].sort(),
43
+ });
44
+ }
45
+
46
+ /** Test seam: forget every noted recipe, so one file's servers do not judge the next file's links. */
47
+ export function resetServedRecipes(): void {
48
+ SERVED.clear();
49
+ }
@@ -0,0 +1,143 @@
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.
6
+ */
7
+
8
+ // why: Bun exposes no path-join primitive; the folder is the app's.
9
+ import { join } from 'node:path';
10
+ import { McpRecipeExampleInvalidError } from './recipe-errors';
11
+ import type { McpRecipe, McpRecipeStep } from './recipes';
12
+
13
+ /** A whole-string `"<name>"` in a fenced call: a value `replay` substitutes, any value at boot. */
14
+ export const PLACEHOLDER = /^<([A-Za-z][\w-]*)>$/;
15
+
16
+ const FENCE = /^```call[^\S\n]*\n([\s\S]*?)\n```[^\S\n]*$/gm;
17
+
18
+ /** Every `*.md` under `dir`, sorted by name: the same folder is the same recipes, in order. */
19
+ export async function markdownRecipes(input: { readonly dir: string }): Promise<McpRecipe[]> {
20
+ const files = [...new Bun.Glob('*.md').scanSync({ cwd: input.dir })].sort();
21
+ const recipes: McpRecipe[] = [];
22
+ for (const file of files) {
23
+ const text = await Bun.file(join(input.dir, file)).text();
24
+ recipes.push(recipeFromMarkdown(file.replace(/\.md$/, ''), text));
25
+ }
26
+ return recipes;
27
+ }
28
+
29
+ /** 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 {
31
+ const { fields, body } = frontMatter(text.replace(/\r\n/g, '\n'));
32
+ const lines = body.split('\n');
33
+ const heading = lines
34
+ .find((line) => line.startsWith('# '))
35
+ ?.slice(2)
36
+ .trim();
37
+ const paragraph = firstParagraph(lines);
38
+ return {
39
+ name,
40
+ title: fields.get('title') ?? heading ?? name,
41
+ description: fields.get('description') ?? paragraph ?? '',
42
+ steps: fencedCalls(name, body),
43
+ body: body.trim() === '' ? '' : `${body.trim()}\n`,
44
+ };
45
+ }
46
+
47
+ function frontMatter(text: string): {
48
+ readonly fields: ReadonlyMap<string, string>;
49
+ readonly body: string;
50
+ } {
51
+ const fields = new Map<string, string>();
52
+ if (!text.startsWith('---\n')) return { fields, body: text };
53
+ const end = text.indexOf('\n---\n', 4);
54
+ if (end === -1) return { fields, body: text };
55
+ for (const line of text.slice(4, end).split('\n')) {
56
+ const colon = line.indexOf(':');
57
+ if (colon > 0) fields.set(line.slice(0, colon).trim(), line.slice(colon + 1).trim());
58
+ }
59
+ return { fields, body: text.slice(end + 5) };
60
+ }
61
+
62
+ function firstParagraph(lines: readonly string[]): string | undefined {
63
+ const start = lines.findIndex(
64
+ (line) => line.trim() !== '' && !line.startsWith('#') && !line.startsWith('```'),
65
+ );
66
+ if (start === -1) return undefined;
67
+ const end = lines.findIndex((line, index) => index > start && line.trim() === '');
68
+ return lines
69
+ .slice(start, end === -1 ? undefined : end)
70
+ .join(' ')
71
+ .trim();
72
+ }
73
+
74
+ /** ```call fences: `tool` then an optional JSON object, which may span lines. */
75
+ function fencedCalls(name: string, body: string): McpRecipeStep[] {
76
+ const steps: McpRecipeStep[] = [];
77
+ const offenders: string[] = [];
78
+ let index = 0;
79
+ for (const match of body.matchAll(FENCE)) {
80
+ index += 1;
81
+ const content = (match[1] ?? '').trim();
82
+ const space = content.search(/\s/);
83
+ const tool = space === -1 ? content : content.slice(0, space);
84
+ const rest = space === -1 ? '' : content.slice(space).trim();
85
+ const example = rest === '' ? {} : parseObject(rest);
86
+ if (tool === '' || example === undefined) {
87
+ offenders.push(
88
+ `recipe "${name}" call fence ${String(index)}: write \`tool {"arg": "value"}\``,
89
+ );
90
+ continue;
91
+ }
92
+ steps.push({ tool, why: `fenced call ${String(index)}`, example });
93
+ }
94
+ if (offenders.length > 0) throw new McpRecipeExampleInvalidError({ offenders });
95
+ return steps;
96
+ }
97
+
98
+ function parseObject(text: string): Record<string, unknown> | undefined {
99
+ try {
100
+ const parsed = JSON.parse(text) as unknown;
101
+ return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
102
+ ? (parsed as Record<string, unknown>)
103
+ : undefined;
104
+ } catch {
105
+ // Not JSON: the caller names the fence.
106
+ return undefined;
107
+ }
108
+ }
109
+
110
+ /** Paths (validate-args' spelling) whose value is a whole `"<name>"` placeholder. */
111
+ export function placeholderPaths(value: unknown, path = ''): readonly string[] {
112
+ if (typeof value === 'string') return PLACEHOLDER.test(value) ? [path] : [];
113
+ if (Array.isArray(value)) {
114
+ return value.flatMap((item, index) => placeholderPaths(item, `${path}[${String(index)}]`));
115
+ }
116
+ if (typeof value !== 'object' || value === null) return [];
117
+ return Object.entries(value).flatMap(([key, item]) =>
118
+ placeholderPaths(item, path === '' ? key : `${path}.${key}`),
119
+ );
120
+ }
121
+
122
+ /** `"<postId>"` → `placeholders.get('postId')`; a placeholder with no value stays as written. */
123
+ export function fillPlaceholders(
124
+ value: unknown,
125
+ placeholders: ReadonlyMap<string, unknown>,
126
+ ): unknown {
127
+ if (typeof value === 'string') {
128
+ const key = PLACEHOLDER.exec(value)?.[1];
129
+ return key !== undefined && placeholders.has(key) ? placeholders.get(key) : value;
130
+ }
131
+ if (Array.isArray(value)) return value.map((item) => fillPlaceholders(item, placeholders));
132
+ if (typeof value !== 'object' || value === null) return value;
133
+ const out: Record<string, unknown> = {};
134
+ for (const [key, item] of Object.entries(value)) {
135
+ Object.defineProperty(out, key, {
136
+ value: fillPlaceholders(item, placeholders),
137
+ enumerable: true,
138
+ writable: true,
139
+ configurable: true,
140
+ });
141
+ }
142
+ return out;
143
+ }
@@ -0,0 +1,101 @@
1
+ /**
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
4
+ * arguments, a refusing policy or a dangling link fail it; a tool's own refusal is the tool working.
5
+ */
6
+
7
+ import { isJsonObject, renderCauseValue } from '@ultimat3/core';
8
+ import { McpRecipeExampleInvalidError, McpRecipeLinkDanglingError } from './recipe-errors';
9
+ import { fillPlaceholders } from './recipe-markdown';
10
+ import type { McpRecipe } from './recipes';
11
+ import { recipeLinks, recipeUri } from './recipes';
12
+ import type { McpCaller } from './registry';
13
+ import type { McpServer } from './server';
14
+
15
+ export interface ReplayOptions {
16
+ readonly caller: McpCaller;
17
+ /** `"<postId>"` in an example becomes `placeholders.postId`. */
18
+ readonly placeholders?: Readonly<Record<string, unknown>>;
19
+ }
20
+
21
+ export interface ReplayReport {
22
+ /** `<recipe> step <n> (<tool>)`, one per call made. */
23
+ readonly calls: readonly string[];
24
+ /** Every link read. */
25
+ readonly links: readonly string[];
26
+ }
27
+
28
+ /**
29
+ * The codes that mean the call never reached a tool that took it: no such tool, arguments it
30
+ * refuses, or a caller its policy refuses — a replay as somebody who cannot follow the recipe
31
+ * proves nothing about it. Anything else (`X_NOT_FOUND` for a sample id) is the tool answering.
32
+ */
33
+ const UNREACHED = new Set([
34
+ 'X_MCP_TOOL_UNKNOWN',
35
+ 'X_INPUT_INVALID',
36
+ 'X_FORBIDDEN',
37
+ 'X_UNAUTHENTICATED',
38
+ ]);
39
+
40
+ export async function replayRecipes(
41
+ server: McpServer,
42
+ recipes: readonly McpRecipe[],
43
+ options: ReplayOptions,
44
+ ): Promise<ReplayReport> {
45
+ const placeholders = new Map(Object.entries(options.placeholders ?? {}));
46
+ const calls: string[] = [];
47
+ const links: string[] = [];
48
+ const failed: string[] = [];
49
+ const dangling: string[] = [];
50
+ let id = 0;
51
+ const rpc = async (method: string, params: Record<string, unknown>) => {
52
+ id += 1;
53
+ return server.handle({ jsonrpc: '2.0', id, method, params }, options.caller);
54
+ };
55
+ for (const recipe of recipes) {
56
+ for (const [index, step] of recipe.steps.entries()) {
57
+ if (step.example === undefined) continue;
58
+ const at = `recipe "${recipe.name}" step ${String(index + 1)} (${step.tool})`;
59
+ const args = fillPlaceholders(step.example, placeholders);
60
+ const answer = await rpc('tools/call', { name: step.tool, arguments: args });
61
+ calls.push(at);
62
+ const reason = unreached(answer);
63
+ if (reason !== undefined) failed.push(`${at}: ${reason}`);
64
+ }
65
+ for (const name of recipeLinks(recipe)) {
66
+ const uri = recipeUri(name);
67
+ const answer = await rpc('resources/read', { uri });
68
+ links.push(uri);
69
+ if (answer === null || 'error' in answer) {
70
+ dangling.push(`recipe "${recipe.name}" links to ${uri}`);
71
+ }
72
+ }
73
+ }
74
+ if (failed.length > 0) throw new McpRecipeExampleInvalidError({ offenders: failed });
75
+ if (dangling.length > 0) {
76
+ throw new McpRecipeLinkDanglingError({
77
+ offenders: dangling,
78
+ recipes: recipes.map((recipe) => recipe.name).sort(),
79
+ });
80
+ }
81
+ return { calls, links };
82
+ }
83
+
84
+ /** Why a `tools/call` answer never reached a tool that accepted its arguments, or nothing. */
85
+ function unreached(answer: unknown): string | undefined {
86
+ if (!isJsonObject(answer)) return 'no answer';
87
+ const error = answer['error'];
88
+ if (isJsonObject(error)) {
89
+ return `JSON-RPC ${renderCauseValue(error['code'])}: ${renderCauseValue(error['message'])}`;
90
+ }
91
+ const result = answer['result'];
92
+ if (!isJsonObject(result) || result['isError'] !== true) return undefined;
93
+ const content = Array.isArray(result['content']) ? result['content'] : [];
94
+ const text = content
95
+ .map((block: unknown) =>
96
+ isJsonObject(block) && typeof block['text'] === 'string' ? block['text'] : '',
97
+ )
98
+ .join('\n');
99
+ const code = /\b(X_[A-Z0-9_]+)\b/.exec(text)?.[1];
100
+ return code !== undefined && UNREACHED.has(code) ? text.split('\n')[0] : undefined;
101
+ }