@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/CLAUDE.md +5 -5
- package/README.md +139 -16
- package/package.json +11 -11
- package/src/app-tool.ts +10 -3
- package/src/app-tools.ts +29 -7
- package/src/audit.ts +2 -0
- package/src/catalog-errors.ts +11 -5
- package/src/errors.ts +6 -1
- package/src/from-action.ts +33 -3
- package/src/index.ts +11 -1
- package/src/meta-call.ts +2 -2
- package/src/meta-errors.ts +27 -3
- package/src/meta-split-call.ts +45 -6
- package/src/meta-split-options.ts +180 -0
- package/src/meta-split.ts +3 -2
- package/src/meta-surface.ts +17 -1
- package/src/protocol-era.ts +2 -1
- package/src/readonly-sql-calls.ts +15 -3
- package/src/readonly-sql.ts +24 -2
- package/src/recipe-errors.ts +19 -7
- package/src/recipe-markdown.ts +64 -12
- package/src/recipe-replay.ts +12 -5
- package/src/recipe-search.ts +31 -9
- package/src/recipes-surface.ts +19 -6
- package/src/recipes-tool.ts +74 -16
- package/src/recipes.ts +99 -24
- package/src/registry.ts +30 -0
- package/src/remote-client.ts +87 -27
- package/src/remote-oauth.ts +13 -3
- package/src/remote-tools.ts +4 -0
- package/src/remote-wire.ts +7 -14
- package/src/runtime-tool.ts +10 -4
- package/src/server-catalog.ts +10 -1
- package/src/server-input.ts +61 -0
- package/src/server-resources.ts +59 -21
- package/src/server-voice.ts +17 -0
- package/src/server.ts +52 -88
- package/src/tenant-discover.ts +167 -0
- package/src/tenant.ts +94 -21
- package/src/url-elicitation.ts +153 -0
- package/src/wire.ts +2 -0
package/src/recipe-markdown.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Recipes from a folder of markdown, one file per recipe,
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
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;
|
|
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
|
-
/**
|
|
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
|
|
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
|
|
29
|
+
for (const file of [...top, ...nested]) {
|
|
23
30
|
const text = await Bun.file(join(input.dir, file)).text();
|
|
24
|
-
|
|
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:
|
|
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('```'),
|
package/src/recipe-replay.ts
CHANGED
|
@@ -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 `
|
|
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,
|
|
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
|
|
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(
|
|
84
|
+
recipes: recipes.map(recipeKey).sort(),
|
|
85
|
+
at: 'unread',
|
|
79
86
|
});
|
|
80
87
|
}
|
|
81
88
|
return { calls, links };
|
package/src/recipe-search.ts
CHANGED
|
@@ -1,14 +1,19 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `docs({ q })`'s ranking, stated so it can be argued with: a recipe scores the query words it
|
|
3
|
-
* contains — 3
|
|
3
|
+
* contains — 3 in name, title or aliases, 2 in description, 1 in body — each word once.
|
|
4
4
|
* The best positive score is the hit. With none, the nearest names by edit distance are offered,
|
|
5
5
|
* so a miss is never an empty answer while any recipe exists.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import type { McpRecipe } from './recipes';
|
|
9
|
-
import { renderRecipe } from './recipes';
|
|
9
|
+
import { renderRecipe, uriOf } from './recipes';
|
|
10
10
|
|
|
11
11
|
const NEAREST = 3;
|
|
12
|
+
/** A recipe name is a few dozen characters; a longer probe is no nearer to one for its tail. */
|
|
13
|
+
const MAX_PROBE_LENGTH = 64;
|
|
14
|
+
const MAX_PROBES = 16;
|
|
15
|
+
/** `docs`' schema refuses a longer `q`; `words` and `closeness` stay linear below it and above. */
|
|
16
|
+
export const MAX_QUERY_LENGTH = 1000;
|
|
12
17
|
|
|
13
18
|
const words = (text: string): ReadonlySet<string> =>
|
|
14
19
|
new Set(
|
|
@@ -30,19 +35,25 @@ export function rankRecipes(recipes: readonly McpRecipe[], q: string): RecipeRan
|
|
|
30
35
|
const scored = recipes
|
|
31
36
|
.map((recipe) => ({ recipe, score: scoreOf(recipe, asked) }))
|
|
32
37
|
.filter((entry) => entry.score > 0)
|
|
33
|
-
.sort((a, b) => b.score - a.score || a.recipe
|
|
38
|
+
.sort((a, b) => b.score - a.score || byName(a.recipe, b.recipe));
|
|
34
39
|
if (scored.length > 0) return { matches: scored.map((entry) => entry.recipe), nearest: [] };
|
|
35
40
|
const target = q.toLowerCase().trim();
|
|
36
41
|
const nearest = recipes
|
|
37
42
|
.map((recipe) => ({ recipe, distance: closeness(recipe, target, asked) }))
|
|
38
|
-
.sort((a, b) => a.distance - b.distance || a.recipe
|
|
43
|
+
.sort((a, b) => a.distance - b.distance || byName(a.recipe, b.recipe))
|
|
39
44
|
.slice(0, NEAREST)
|
|
40
45
|
.map((entry) => entry.recipe);
|
|
41
46
|
return { matches: [], nearest };
|
|
42
47
|
}
|
|
43
48
|
|
|
49
|
+
/** Ties by name, then by URI: one name may sit in two sections. */
|
|
50
|
+
const byName = (a: McpRecipe, b: McpRecipe): number =>
|
|
51
|
+
a.name.localeCompare(b.name) || uriOf(a).localeCompare(uriOf(b));
|
|
52
|
+
|
|
53
|
+
const aliasText = (recipe: McpRecipe): string => (recipe.aliases ?? []).join(' ');
|
|
54
|
+
|
|
44
55
|
function scoreOf(recipe: McpRecipe, asked: readonly string[]): number {
|
|
45
|
-
const named = words(`${recipe.name} ${recipe.title}`);
|
|
56
|
+
const named = words(`${recipe.name} ${recipe.title} ${aliasText(recipe)}`);
|
|
46
57
|
const described = words(recipe.description);
|
|
47
58
|
const body = words(renderRecipe(recipe));
|
|
48
59
|
let score = 0;
|
|
@@ -54,17 +65,28 @@ function scoreOf(recipe: McpRecipe, asked: readonly string[]): number {
|
|
|
54
65
|
return score;
|
|
55
66
|
}
|
|
56
67
|
|
|
57
|
-
/**
|
|
68
|
+
/**
|
|
69
|
+
* The smallest edit distance from the query, or any of its words, to the name or a title or alias
|
|
70
|
+
* word.
|
|
71
|
+
* Bounded: the query is caller input and the distance is |probe| x |candidate|, so only the first
|
|
72
|
+
* `MAX_PROBES` words count, each cut to `MAX_PROBE_LENGTH`, and a pair whose lengths already differ
|
|
73
|
+
* by the best distance found is skipped — it cannot beat it.
|
|
74
|
+
*/
|
|
58
75
|
function closeness(recipe: McpRecipe, target: string, asked: readonly string[]): number {
|
|
59
|
-
const candidates = [recipe.name, ...words(recipe.title)];
|
|
60
|
-
const probes = [target, ...asked];
|
|
76
|
+
const candidates = [recipe.name, ...words(`${recipe.title} ${aliasText(recipe)}`)].map(clamped);
|
|
77
|
+
const probes = [target, ...asked.slice(0, MAX_PROBES)].map(clamped);
|
|
61
78
|
let best = Number.POSITIVE_INFINITY;
|
|
62
79
|
for (const probe of probes) {
|
|
63
|
-
for (const candidate of candidates)
|
|
80
|
+
for (const candidate of candidates) {
|
|
81
|
+
if (Math.abs(probe.length - candidate.length) >= best) continue;
|
|
82
|
+
best = Math.min(best, distance(probe, candidate));
|
|
83
|
+
}
|
|
64
84
|
}
|
|
65
85
|
return best;
|
|
66
86
|
}
|
|
67
87
|
|
|
88
|
+
const clamped = (text: string): string => text.slice(0, MAX_PROBE_LENGTH);
|
|
89
|
+
|
|
68
90
|
/** Levenshtein, two rows. */
|
|
69
91
|
function distance(a: string, b: string): number {
|
|
70
92
|
let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
|
package/src/recipes-surface.ts
CHANGED
|
@@ -1,14 +1,20 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* What `recipes:` and `extraRecipes:` add to a `defineAppMcp` server, after the boot checks: the
|
|
3
|
-
* `docs` tool, one `docs
|
|
3
|
+
* `docs` tool, one `docs://<section>/<name>` resource per recipe, and — for a caller's own — a
|
|
4
4
|
* per-caller resource source. Nothing at all without either option.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
import { McpToolDuplicateError } from './errors';
|
|
8
8
|
import { noteServedRecipes } from './recipe-links';
|
|
9
9
|
import type { McpRecipe } from './recipes';
|
|
10
|
-
import {
|
|
11
|
-
|
|
10
|
+
import {
|
|
11
|
+
assertNoRecipeResources,
|
|
12
|
+
checkRecipes,
|
|
13
|
+
DEFAULT_SECTION,
|
|
14
|
+
recipeResources,
|
|
15
|
+
sectionOf,
|
|
16
|
+
} from './recipes';
|
|
17
|
+
import type { DocsToolOptions, ExtraRecipes } from './recipes-tool';
|
|
12
18
|
import { DOCS_TOOL, recipesFor, recipesTool } from './recipes-tool';
|
|
13
19
|
import type { AnyMcpTool } from './registry';
|
|
14
20
|
import type { McpResource, McpResourceSource } from './resources';
|
|
@@ -24,19 +30,26 @@ export function withRecipes(
|
|
|
24
30
|
resources: readonly McpResource[],
|
|
25
31
|
recipes: readonly McpRecipe[] | undefined,
|
|
26
32
|
extra: ExtraRecipes | undefined,
|
|
33
|
+
options: DocsToolOptions = {},
|
|
27
34
|
): RecipeSurface {
|
|
28
35
|
const declared = recipes ?? [];
|
|
29
36
|
if (declared.length === 0 && extra === undefined) {
|
|
30
37
|
return { tools, resources, resourceSources: [] };
|
|
31
38
|
}
|
|
32
|
-
assertNoRecipeResources(resources);
|
|
39
|
+
assertNoRecipeResources(resources, declared);
|
|
33
40
|
checkRecipes(declared, tools);
|
|
34
41
|
// The one name this adds; an app tool already called `docs` is a duplicate, never a shadow.
|
|
35
42
|
if (tools.some((tool) => tool.name === DOCS_TOOL)) {
|
|
36
43
|
throw new McpToolDuplicateError({ name: DOCS_TOOL, declaredBy: ['tools:', 'recipes:'] });
|
|
37
44
|
}
|
|
38
|
-
const final: readonly AnyMcpTool[] = [
|
|
39
|
-
|
|
45
|
+
const final: readonly AnyMcpTool[] = [
|
|
46
|
+
...tools,
|
|
47
|
+
recipesTool(declared, () => final, extra, options),
|
|
48
|
+
];
|
|
49
|
+
// Error links name `docs://recipes/<name>` only: the other sections are not theirs to judge.
|
|
50
|
+
noteServedRecipes(
|
|
51
|
+
declared.filter((recipe) => sectionOf(recipe) === DEFAULT_SECTION).map((recipe) => recipe.name),
|
|
52
|
+
);
|
|
40
53
|
const source: McpResourceSource | undefined =
|
|
41
54
|
extra === undefined
|
|
42
55
|
? undefined
|
package/src/recipes-tool.ts
CHANGED
|
@@ -1,13 +1,22 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `docs` — recipes for clients that ignore resources: `{}` lists,
|
|
3
|
-
* `{ q }` inlines the best match or names the nearest.
|
|
4
|
-
* hidden and unknown are one not-found; a caller's own
|
|
2
|
+
* `docs` — recipes for clients that ignore resources: `{}` lists (JSON, or a text map grouped by
|
|
3
|
+
* section), `{ name }` / `{ uri }` reads one, `{ q }` inlines the best match or names the nearest.
|
|
4
|
+
* Gated per recipe by the tools it names, so hidden and unknown are one not-found; a caller's own
|
|
5
|
+
* recipes are marked `source: 'caller'`.
|
|
5
6
|
*/
|
|
6
7
|
|
|
7
8
|
import { renderCauseValue, UltimateError } from '@ultimat3/core';
|
|
8
|
-
import { rankRecipes } from './recipe-search';
|
|
9
|
+
import { MAX_QUERY_LENGTH, rankRecipes } from './recipe-search';
|
|
9
10
|
import type { McpRecipe } from './recipes';
|
|
10
|
-
import {
|
|
11
|
+
import {
|
|
12
|
+
assertSection,
|
|
13
|
+
recipeKey,
|
|
14
|
+
recipeVisible,
|
|
15
|
+
renderRecipe,
|
|
16
|
+
sectionOf,
|
|
17
|
+
uriOf,
|
|
18
|
+
uriOfKey,
|
|
19
|
+
} from './recipes';
|
|
11
20
|
import type { AnyMcpTool, McpCaller, McpToolResult } from './registry';
|
|
12
21
|
|
|
13
22
|
export const DOCS_TOOL = 'docs';
|
|
@@ -17,13 +26,25 @@ export type ExtraRecipes = (
|
|
|
17
26
|
caller: McpCaller,
|
|
18
27
|
) => Promise<readonly McpRecipe[]> | readonly McpRecipe[];
|
|
19
28
|
|
|
29
|
+
/** How `docs` presents itself: the app's own description, and the shape `docs({})` answers. */
|
|
30
|
+
export interface DocsToolOptions {
|
|
31
|
+
/** Replaces the default tool description. */
|
|
32
|
+
readonly description?: string;
|
|
33
|
+
/**
|
|
34
|
+
* `'json'` (default): `{ recipes: [{ name, title, description, uri, source }] }` — `name` is the
|
|
35
|
+
* bare name, so outside `recipes` read by `uri` or `<section>/<name>`. `'map'`: plain
|
|
36
|
+
* text, one `# <section>` heading per section, then one `<uri> <title>` line per recipe.
|
|
37
|
+
*/
|
|
38
|
+
readonly index?: 'json' | 'map';
|
|
39
|
+
}
|
|
40
|
+
|
|
20
41
|
/** One recipe this caller may follow, and where it came from. */
|
|
21
42
|
export interface SourcedRecipe {
|
|
22
43
|
readonly recipe: McpRecipe;
|
|
23
44
|
readonly source: 'app' | 'caller';
|
|
24
45
|
}
|
|
25
46
|
|
|
26
|
-
/** The app's recipes, then the caller's (a
|
|
47
|
+
/** The app's recipes, then the caller's (a URI the app holds is never shadowed), all gated. */
|
|
27
48
|
export async function recipesFor(
|
|
28
49
|
recipes: readonly McpRecipe[],
|
|
29
50
|
extra: ExtraRecipes | undefined,
|
|
@@ -31,12 +52,13 @@ export async function recipesFor(
|
|
|
31
52
|
caller: McpCaller,
|
|
32
53
|
): Promise<readonly SourcedRecipe[]> {
|
|
33
54
|
const tools = new Map(catalog.map((tool) => [tool.name, tool]));
|
|
34
|
-
const taken = new Set(recipes.map(
|
|
55
|
+
const taken = new Set(recipes.map(uriOf));
|
|
35
56
|
const own = extra === undefined ? [] : await extra(caller);
|
|
57
|
+
for (const recipe of own) assertSection(recipe);
|
|
36
58
|
return [
|
|
37
59
|
...recipes.map((recipe) => ({ recipe, source: 'app' as const })),
|
|
38
60
|
...own
|
|
39
|
-
.filter((recipe) => !taken.has(recipe
|
|
61
|
+
.filter((recipe) => !taken.has(uriOf(recipe)))
|
|
40
62
|
.map((recipe) => ({ recipe, source: 'caller' as const })),
|
|
41
63
|
].filter((entry) => recipeVisible(entry.recipe, tools, caller));
|
|
42
64
|
}
|
|
@@ -45,17 +67,31 @@ export function recipesTool(
|
|
|
45
67
|
recipes: readonly McpRecipe[],
|
|
46
68
|
catalog: () => readonly AnyMcpTool[],
|
|
47
69
|
extra?: ExtraRecipes,
|
|
70
|
+
options: DocsToolOptions = {},
|
|
48
71
|
): AnyMcpTool {
|
|
49
72
|
return {
|
|
50
73
|
name: DOCS_TOOL,
|
|
51
74
|
description:
|
|
75
|
+
options.description ??
|
|
52
76
|
'How-to recipes for this server. docs({}) lists the ones you can follow; docs({ q }) finds one by words and reads it; docs({ name }) or docs({ uri }) reads one: which tools to call, in order, with example arguments.',
|
|
53
77
|
inputSchema: {
|
|
54
78
|
type: 'object',
|
|
55
79
|
properties: {
|
|
56
|
-
name: {
|
|
57
|
-
|
|
58
|
-
|
|
80
|
+
name: {
|
|
81
|
+
type: 'string',
|
|
82
|
+
description:
|
|
83
|
+
'A recipe name: bare in the recipes section, <section>/<name> in any other. The uri docs({}) lists always works.',
|
|
84
|
+
},
|
|
85
|
+
uri: {
|
|
86
|
+
type: 'string',
|
|
87
|
+
description: 'A docs://<section>/<name> URI exactly as docs({}) or an error gives it.',
|
|
88
|
+
},
|
|
89
|
+
// A miss quotes `q` back and ranks every recipe against it: a megabyte of it is refused.
|
|
90
|
+
q: {
|
|
91
|
+
type: 'string',
|
|
92
|
+
maxLength: MAX_QUERY_LENGTH,
|
|
93
|
+
description: 'Words describing the task.',
|
|
94
|
+
},
|
|
59
95
|
},
|
|
60
96
|
additionalProperties: false,
|
|
61
97
|
},
|
|
@@ -67,16 +103,18 @@ export function recipesTool(
|
|
|
67
103
|
typeof args['name'] === 'string'
|
|
68
104
|
? args['name']
|
|
69
105
|
: typeof args['uri'] === 'string'
|
|
70
|
-
?
|
|
106
|
+
? args['uri']
|
|
71
107
|
: undefined;
|
|
72
108
|
if (named !== undefined) {
|
|
73
|
-
const
|
|
109
|
+
const uri = uriOfKey(named);
|
|
110
|
+
const found = visible.find((entry) => uriOf(entry.recipe) === uri);
|
|
74
111
|
if (found === undefined) throw notFound(named);
|
|
75
112
|
return text(renderRecipe(found.recipe));
|
|
76
113
|
}
|
|
77
114
|
if (typeof args['q'] === 'string' && args['q'].trim() !== '') {
|
|
78
115
|
return text(answerQuery(visible, args['q']));
|
|
79
116
|
}
|
|
117
|
+
if (options.index === 'map') return text(renderMap(visible));
|
|
80
118
|
return text(JSON.stringify({ recipes: visible.map(row) }));
|
|
81
119
|
},
|
|
82
120
|
};
|
|
@@ -86,19 +124,39 @@ const row = (entry: SourcedRecipe) => ({
|
|
|
86
124
|
name: entry.recipe.name,
|
|
87
125
|
title: entry.recipe.title,
|
|
88
126
|
description: entry.recipe.description,
|
|
89
|
-
uri:
|
|
127
|
+
uri: uriOf(entry.recipe),
|
|
90
128
|
source: entry.source,
|
|
91
129
|
});
|
|
92
130
|
|
|
131
|
+
/** A line-per-entry answer: a title's own line breaks would split its entry. */
|
|
132
|
+
const oneLine = (title: string): string =>
|
|
133
|
+
title.replace(/[\s\u0085]+/g, (space) =>
|
|
134
|
+
/[\r\n\v\f\u0085\u2028\u2029]/.test(space) ? ' ' : space,
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
const yours = (entry: SourcedRecipe): string => (entry.source === 'caller' ? ' (yours)' : '');
|
|
138
|
+
|
|
139
|
+
/** Sections in first-seen order, each its `<uri> <title>` lines: no tables, no nesting. */
|
|
140
|
+
function renderMap(visible: readonly SourcedRecipe[]): string {
|
|
141
|
+
if (visible.length === 0) return 'No recipes are available to this caller.\n';
|
|
142
|
+
const sections = new Map<string, string[]>();
|
|
143
|
+
for (const entry of visible) {
|
|
144
|
+
const lines = sections.get(sectionOf(entry.recipe)) ?? [];
|
|
145
|
+
lines.push(`${uriOf(entry.recipe)} ${oneLine(entry.recipe.title)}${yours(entry)}`);
|
|
146
|
+
sections.set(sectionOf(entry.recipe), lines);
|
|
147
|
+
}
|
|
148
|
+
return `${[...sections].map(([section, lines]) => `# ${section}\n${lines.join('\n')}`).join('\n\n')}\n`;
|
|
149
|
+
}
|
|
150
|
+
|
|
93
151
|
/** The best match inlined, with the runners-up named; a miss names the nearest instead. */
|
|
94
152
|
function answerQuery(visible: readonly SourcedRecipe[], q: string): string {
|
|
95
|
-
const sources = new Map(visible.map((entry) => [entry.recipe
|
|
153
|
+
const sources = new Map(visible.map((entry) => [uriOf(entry.recipe), entry.source]));
|
|
96
154
|
const { matches, nearest } = rankRecipes(
|
|
97
155
|
visible.map((entry) => entry.recipe),
|
|
98
156
|
q,
|
|
99
157
|
);
|
|
100
158
|
const line = (recipe: McpRecipe) =>
|
|
101
|
-
`- docs({ name: '${recipe
|
|
159
|
+
`- docs({ name: '${recipeKey(recipe)}' }) — ${oneLine(recipe.title)}${sources.get(uriOf(recipe)) === 'caller' ? ' (yours)' : ''}`;
|
|
102
160
|
const [best, ...rest] = matches;
|
|
103
161
|
if (best !== undefined) {
|
|
104
162
|
const related = rest.slice(0, 4);
|