@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/recipes.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* MCP recipes — "how do I do X here" as structure the boot checks: every step names a projected
|
|
3
|
-
* tool and its example must pass that tool's input. Served as `docs
|
|
4
|
-
* `docs`, only to a caller who can see and call every tool a
|
|
3
|
+
* tool and its example must pass that tool's input. Served as `docs://<section>/<name>` (section
|
|
4
|
+
* `recipes` unless set) and through `docs`, only to a caller who can see and call every tool a
|
|
5
|
+
* recipe names.
|
|
5
6
|
*/
|
|
6
7
|
|
|
7
8
|
import {
|
|
@@ -17,7 +18,30 @@ import type { McpResource } from './resources';
|
|
|
17
18
|
import { validateArgs } from './validate-args';
|
|
18
19
|
|
|
19
20
|
export const RECIPE_URI_PREFIX = 'docs://recipes/';
|
|
20
|
-
|
|
21
|
+
/** The section a recipe that names none is served under. */
|
|
22
|
+
export const DEFAULT_SECTION = 'recipes';
|
|
23
|
+
/**
|
|
24
|
+
* A name and a section alike: lowercase letters and digits in groups joined by single `-`
|
|
25
|
+
* (`ref-v2`, never `-ref`, `ref-` or `ref--v2`) — closed, so neither steps out of `docs://<section>/`.
|
|
26
|
+
*/
|
|
27
|
+
export const NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
28
|
+
/**
|
|
29
|
+
* A `docs://<section>/` link and its whole destination, up to whitespace or the Markdown that
|
|
30
|
+
* closes it (brackets, quotes, `*` emphasis, a table's `|`): `docs://ref/errors/old`, `.html`,
|
|
31
|
+
* `%65rrors` and `errors+old` are not `docs://ref/errors`. Less a sentence's end (`LINK_TAIL`).
|
|
32
|
+
*/
|
|
33
|
+
const SECTIONED_LINK = /(\]\()?docs:\/\/([a-z0-9]+(?:-[a-z0-9]+)*)\/([^\s()<>[\]{}"'`*|]+)/g;
|
|
34
|
+
/** Trimmed from a link in prose only: a `[text](…)` destination is taken whole. */
|
|
35
|
+
const LINK_TAIL = new Set(['.', ',', ';', ':', '!', '?', '…']);
|
|
36
|
+
|
|
37
|
+
/** `path` less its trailing sentence punctuation, in one backward pass (no regex backtracking). */
|
|
38
|
+
function withoutLinkTail(path: string): string {
|
|
39
|
+
let end = path.length;
|
|
40
|
+
while (end > 0 && LINK_TAIL.has(path[end - 1] as string)) end -= 1;
|
|
41
|
+
return path.slice(0, end);
|
|
42
|
+
}
|
|
43
|
+
/** The section a `docs://<section>/…` URI sits in. */
|
|
44
|
+
const SECTION_OF_URI = /^docs:\/\/([^/]*)\//;
|
|
21
45
|
|
|
22
46
|
export interface McpRecipeStep {
|
|
23
47
|
/** A tool THIS server projects, by name. Checked at boot. */
|
|
@@ -29,21 +53,48 @@ export interface McpRecipeStep {
|
|
|
29
53
|
}
|
|
30
54
|
|
|
31
55
|
export interface McpRecipe {
|
|
32
|
-
/** `
|
|
56
|
+
/** Lowercase letters and digits in `-`-joined groups (`NAME`); the URI is `docs://<section>/<name>`. */
|
|
33
57
|
readonly name: string;
|
|
58
|
+
/** Spelled like `name`, `recipes` when unset: one `docs({})` group and one `docs://<section>/` prefix. */
|
|
59
|
+
readonly section?: string;
|
|
60
|
+
/** Other words for it: `docs({ q })` scores each as it scores the title. */
|
|
61
|
+
readonly aliases?: readonly string[];
|
|
34
62
|
readonly title: string;
|
|
35
63
|
readonly description: string;
|
|
36
64
|
readonly steps: readonly McpRecipeStep[];
|
|
37
65
|
/** Free text, unchecked: where a tool is named, it is a step. */
|
|
38
66
|
readonly notes?: string;
|
|
39
67
|
/**
|
|
40
|
-
* Markdown served
|
|
41
|
-
* builds from a file
|
|
68
|
+
* Markdown served as given in place of the rendered steps — what `markdownRecipes({ dir })`
|
|
69
|
+
* builds from a file (LF line ends, outer blank lines dropped), its ```call fences becoming
|
|
70
|
+
* `steps`, so they are checked all the same.
|
|
42
71
|
*/
|
|
43
72
|
readonly body?: string;
|
|
44
73
|
}
|
|
45
74
|
|
|
46
|
-
export const recipeUri = (name: string): string =>
|
|
75
|
+
export const recipeUri = (name: string, section: string = DEFAULT_SECTION): string =>
|
|
76
|
+
`docs://${section}/${name}`;
|
|
77
|
+
|
|
78
|
+
/** The URI one recipe is served at. */
|
|
79
|
+
export const uriOf = (recipe: McpRecipe): string => recipeUri(recipe.name, recipe.section);
|
|
80
|
+
|
|
81
|
+
/** The section one recipe is listed under. */
|
|
82
|
+
export const sectionOf = (recipe: McpRecipe): string => recipe.section ?? DEFAULT_SECTION;
|
|
83
|
+
|
|
84
|
+
/** `docs({ name })`'s spelling: the bare name in `recipes`, `<section>/<name>` elsewhere. */
|
|
85
|
+
export const recipeKey = (recipe: McpRecipe): string =>
|
|
86
|
+
sectionOf(recipe) === DEFAULT_SECTION ? recipe.name : `${sectionOf(recipe)}/${recipe.name}`;
|
|
87
|
+
|
|
88
|
+
/** The URI a `docs({ name })` / `docs({ uri })` argument names: a URI, `<section>/<name>` or a name. */
|
|
89
|
+
export const uriOfKey = (key: string): string =>
|
|
90
|
+
key.startsWith('docs://') ? key : key.includes('/') ? `docs://${key}` : recipeUri(key);
|
|
91
|
+
|
|
92
|
+
/** A section outside the closed pattern is refused before it becomes part of a URI. */
|
|
93
|
+
export function assertSection(recipe: McpRecipe): void {
|
|
94
|
+
if (recipe.section !== undefined && !NAME.test(recipe.section)) {
|
|
95
|
+
throw new McpRecipeUriReservedError({ uri: uriOf(recipe), reason: 'section' });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
47
98
|
|
|
48
99
|
/** The recipe a `docs://recipes/<name>` names, or `undefined` for any other URI. */
|
|
49
100
|
export const recipeNameOf = (uri: string): string | undefined =>
|
|
@@ -56,10 +107,11 @@ export const recipeNameOf = (uri: string): string | undefined =>
|
|
|
56
107
|
export function checkRecipes(recipes: readonly McpRecipe[], catalog: readonly AnyMcpTool[]): void {
|
|
57
108
|
const seen = new Set<string>();
|
|
58
109
|
for (const recipe of recipes) {
|
|
59
|
-
const uri =
|
|
110
|
+
const uri = uriOf(recipe);
|
|
60
111
|
if (!NAME.test(recipe.name)) throw new McpRecipeUriReservedError({ uri, reason: 'name' });
|
|
61
|
-
|
|
62
|
-
seen.
|
|
112
|
+
assertSection(recipe);
|
|
113
|
+
if (seen.has(uri)) throw new McpRecipeUriReservedError({ uri, reason: 'duplicate' });
|
|
114
|
+
seen.add(uri);
|
|
63
115
|
}
|
|
64
116
|
const tools = new Map(catalog.map((tool) => [tool.name, tool]));
|
|
65
117
|
const unknown: string[] = [];
|
|
@@ -90,30 +142,53 @@ export function checkRecipes(recipes: readonly McpRecipe[], catalog: readonly An
|
|
|
90
142
|
assertRecipeBodyLinks(recipes);
|
|
91
143
|
}
|
|
92
144
|
|
|
93
|
-
/**
|
|
94
|
-
export
|
|
145
|
+
/** `recipes`, then every section `recipes` holds: the `docs://` prefixes this set owns. */
|
|
146
|
+
export const sectionsOf = (recipes: readonly McpRecipe[]): ReadonlySet<string> =>
|
|
147
|
+
new Set([DEFAULT_SECTION, ...recipes.map(sectionOf)]);
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Every recipe URI a recipe's text names, as written — in a section `sections` holds. A link into
|
|
151
|
+
* any other `docs://` prefix is somebody else's resource, and not judged here.
|
|
152
|
+
*/
|
|
153
|
+
export function recipeLinks(recipe: McpRecipe, sections: ReadonlySet<string>): readonly string[] {
|
|
95
154
|
const text = `${recipe.body ?? ''}\n${recipe.notes ?? ''}`;
|
|
96
|
-
return [...text.matchAll(
|
|
97
|
-
(match) => match[
|
|
98
|
-
|
|
155
|
+
return [...text.matchAll(SECTIONED_LINK)]
|
|
156
|
+
.filter((match) => sections.has(match[2] as string))
|
|
157
|
+
.map((match) => ({
|
|
158
|
+
section: match[2] as string,
|
|
159
|
+
path: match[1] === undefined ? withoutLinkTail(match[3] as string) : (match[3] as string),
|
|
160
|
+
}))
|
|
161
|
+
.filter((link) => link.path !== '')
|
|
162
|
+
.map((link) => recipeUri(link.path, link.section));
|
|
99
163
|
}
|
|
100
164
|
|
|
101
165
|
/** A recipe pointing at one that does not exist is the stale link this whole file refuses. */
|
|
102
166
|
function assertRecipeBodyLinks(recipes: readonly McpRecipe[]): void {
|
|
103
|
-
const
|
|
167
|
+
const uris = new Set(recipes.map(uriOf));
|
|
168
|
+
const sections = sectionsOf(recipes);
|
|
104
169
|
const offenders = recipes.flatMap((recipe) =>
|
|
105
|
-
recipeLinks(recipe)
|
|
106
|
-
.filter((
|
|
107
|
-
.map((
|
|
170
|
+
recipeLinks(recipe, sections)
|
|
171
|
+
.filter((uri) => !uris.has(uri))
|
|
172
|
+
.map((uri) => `recipe "${recipe.name}" links to ${uri}`),
|
|
108
173
|
);
|
|
109
174
|
if (offenders.length > 0) {
|
|
110
|
-
throw new McpRecipeLinkDanglingError({
|
|
175
|
+
throw new McpRecipeLinkDanglingError({
|
|
176
|
+
offenders,
|
|
177
|
+
recipes: recipes.map(recipeKey).sort(),
|
|
178
|
+
});
|
|
111
179
|
}
|
|
112
180
|
}
|
|
113
181
|
|
|
114
|
-
/** A hand-written resource may not take
|
|
115
|
-
export function assertNoRecipeResources(
|
|
116
|
-
|
|
182
|
+
/** A hand-written resource may not take a `docs://<section>/` prefix `recipes:` owns. */
|
|
183
|
+
export function assertNoRecipeResources(
|
|
184
|
+
resources: readonly McpResource[],
|
|
185
|
+
recipes: readonly McpRecipe[],
|
|
186
|
+
): void {
|
|
187
|
+
const sections = sectionsOf(recipes);
|
|
188
|
+
const taken = resources.find((resource) => {
|
|
189
|
+
const section = SECTION_OF_URI.exec(resource.uri)?.[1];
|
|
190
|
+
return section !== undefined && sections.has(section);
|
|
191
|
+
});
|
|
117
192
|
if (taken !== undefined)
|
|
118
193
|
throw new McpRecipeUriReservedError({ uri: taken.uri, reason: 'resource' });
|
|
119
194
|
}
|
|
@@ -157,7 +232,7 @@ export function recipeResources(
|
|
|
157
232
|
): readonly McpResource[] {
|
|
158
233
|
const tools = new Map(catalog.map((tool) => [tool.name, tool]));
|
|
159
234
|
return recipes.map((recipe) => ({
|
|
160
|
-
uri:
|
|
235
|
+
uri: uriOf(recipe),
|
|
161
236
|
name: recipe.title,
|
|
162
237
|
description: recipe.description,
|
|
163
238
|
mimeType: 'text/markdown',
|
package/src/registry.ts
CHANGED
|
@@ -47,6 +47,19 @@ export interface McpCaller {
|
|
|
47
47
|
* belongs to the server, and `ToolRegistry` is where it lives.
|
|
48
48
|
*/
|
|
49
49
|
readonly tenant?: string;
|
|
50
|
+
/**
|
|
51
|
+
* The `'meta-split'` dispatcher THIS call came through — set by `meta-split-call.ts` for one
|
|
52
|
+
* call. Absent on every other path. The audit line carries its `tool`, never its `fields`.
|
|
53
|
+
*/
|
|
54
|
+
readonly door?: McpDoor;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The dispatcher one call came through, and the app-declared envelope fields it carried. */
|
|
58
|
+
export interface McpDoor {
|
|
59
|
+
/** `read_resource`, `write_resource` or `delete_resource`. */
|
|
60
|
+
readonly tool: string;
|
|
61
|
+
/** `split.fields` as this call sent them: a `reason`, a ticket. Never part of the action input. */
|
|
62
|
+
readonly fields: Readonly<Record<string, string>>;
|
|
50
63
|
}
|
|
51
64
|
|
|
52
65
|
/**
|
|
@@ -67,6 +80,17 @@ export type ContentBlock =
|
|
|
67
80
|
| { readonly type: 'text'; readonly text: string }
|
|
68
81
|
| { readonly type: 'resource'; readonly uri: string; readonly mimeType?: string };
|
|
69
82
|
|
|
83
|
+
/**
|
|
84
|
+
* A URL-mode elicitation (MCP 2026-07-28, `client/elicitation`): a page the person opens in their
|
|
85
|
+
* own browser, for what must not pass through the client or the model — a credential, a consent.
|
|
86
|
+
*/
|
|
87
|
+
export interface McpUrlElicitation {
|
|
88
|
+
/** Absolute `https:` (`http:` on this machine only), no `user:password@`, nothing secret in it. */
|
|
89
|
+
readonly url: string;
|
|
90
|
+
/** Why the page is needed, shown to the person beside the URL. */
|
|
91
|
+
readonly message: string;
|
|
92
|
+
}
|
|
93
|
+
|
|
70
94
|
/**
|
|
71
95
|
* `tools/call` result. `isError` flags an EXPECTED tool-level failure (a policy denied the
|
|
72
96
|
* action, a queue was unreachable) so the model sees it as an outcome to reason about.
|
|
@@ -91,6 +115,12 @@ export interface McpToolResult {
|
|
|
91
115
|
* through. Absent keeps the conservative reading.
|
|
92
116
|
*/
|
|
93
117
|
readonly code?: string;
|
|
118
|
+
/**
|
|
119
|
+
* A page the person is asked to open (`url-elicitation.ts`). NEVER a wire field of this result:
|
|
120
|
+
* a modern client that declared `elicitation.url` is answered an `InputRequiredResult` carrying
|
|
121
|
+
* it instead of `content`; every other caller gets `content`, which says the same in text.
|
|
122
|
+
*/
|
|
123
|
+
readonly urlElicitation?: McpUrlElicitation;
|
|
94
124
|
}
|
|
95
125
|
|
|
96
126
|
export type ToolArgs = Record<string, unknown>;
|
package/src/remote-client.ts
CHANGED
|
@@ -33,7 +33,17 @@ export interface McpClientOptions {
|
|
|
33
33
|
readonly auth?: () =>
|
|
34
34
|
| Readonly<Record<string, string>>
|
|
35
35
|
| Promise<Readonly<Record<string, string>>>;
|
|
36
|
-
/**
|
|
36
|
+
/**
|
|
37
|
+
* The largest answer one call reads, in bytes; past it the read stops, `X_MCP_REMOTE_REFUSED`
|
|
38
|
+
* (`meta.failure: 'transport'`, source `X_OUTBOUND_TOO_LARGE`). Default 16 MiB, `outbound()`'s.
|
|
39
|
+
*/
|
|
40
|
+
readonly maxBytes?: number;
|
|
41
|
+
/**
|
|
42
|
+
* The transport: a test double, or a production one. Default `fetch`. It sits under `outbound()`,
|
|
43
|
+
* so the dial screen, deadline, `maxBytes` and redirect refusal stay this client's whatever it
|
|
44
|
+
* does; one that dials anywhere but the url it is handed takes the screen over
|
|
45
|
+
* (`OutboundFetch`).
|
|
46
|
+
*/
|
|
37
47
|
readonly fetch?: OutboundFetch;
|
|
38
48
|
/**
|
|
39
49
|
* The server said `notifications/tools/list_changed` — on a response stream, or on the `GET`
|
|
@@ -76,12 +86,19 @@ const DEFAULT_DEADLINE_MS = 30_000;
|
|
|
76
86
|
const DEFAULT_LISTEN_MS = 300_000;
|
|
77
87
|
const MODERN = MCP_MODERN_VERSIONS[0];
|
|
78
88
|
const LEGACY = MCP_LEGACY_VERSIONS[0];
|
|
89
|
+
const MAX_TOOL_PAGES = 50;
|
|
79
90
|
|
|
80
91
|
export function mcpClient(options: McpClientOptions): McpClient {
|
|
81
92
|
const state: { era?: 'modern' | 'legacy'; session?: string | null; next: number } = { next: 1 };
|
|
82
93
|
const listenMs = finiteCount('mcpClient', 'listenMs', options.listenMs ?? DEFAULT_LISTEN_MS, 1);
|
|
94
|
+
const maxBytes =
|
|
95
|
+
options.maxBytes === undefined
|
|
96
|
+
? undefined
|
|
97
|
+
: finiteCount('mcpClient', 'maxBytes', options.maxBytes, 1);
|
|
83
98
|
/** The open `GET` stream; `'unsupported'` once the server answered it 405, `'closed'` after close(). */
|
|
84
99
|
let listener: Listener | 'unsupported' | 'closed' | undefined;
|
|
100
|
+
/** The one handshake in flight: concurrent calls that need a session share it, never race two. */
|
|
101
|
+
let negotiating: Promise<void> | undefined;
|
|
85
102
|
const refused = (
|
|
86
103
|
reason: string,
|
|
87
104
|
failure: McpRemoteFailure,
|
|
@@ -124,6 +141,7 @@ export function mcpClient(options: McpClientOptions): McpClient {
|
|
|
124
141
|
...headers,
|
|
125
142
|
},
|
|
126
143
|
body: JSON.stringify(body),
|
|
144
|
+
...(maxBytes === undefined ? {} : { maxBytes }),
|
|
127
145
|
...(signal === undefined ? {} : { signal }),
|
|
128
146
|
},
|
|
129
147
|
options.fetch === undefined ? {} : { fetch: options.fetch },
|
|
@@ -132,7 +150,11 @@ export function mcpClient(options: McpClientOptions): McpClient {
|
|
|
132
150
|
if (!isUltimateError(error)) throw error;
|
|
133
151
|
// An abort is the caller's decision, never the server's fault: it passes through.
|
|
134
152
|
if (error.code === 'X_ABORTED') throw error;
|
|
135
|
-
|
|
153
|
+
const reason =
|
|
154
|
+
error.code === 'X_OUTBOUND_TOO_LARGE'
|
|
155
|
+
? `answered past the client's byte cap (${error.code})`
|
|
156
|
+
: `was not reachable (${error.code})`;
|
|
157
|
+
throw refused(reason, 'transport', undefined, error);
|
|
136
158
|
}
|
|
137
159
|
// A token is wanted, or the one sent is no longer good: never an era to fall back from.
|
|
138
160
|
if (answer.status === 401) {
|
|
@@ -157,8 +179,10 @@ export function mcpClient(options: McpClientOptions): McpClient {
|
|
|
157
179
|
method: string,
|
|
158
180
|
params: Record<string, unknown>,
|
|
159
181
|
signal: AbortSignal | undefined,
|
|
182
|
+
sent?: { id?: number },
|
|
160
183
|
): Promise<Record<string, unknown>> => {
|
|
161
184
|
const id = state.next++;
|
|
185
|
+
if (sent !== undefined) sent.id = id;
|
|
162
186
|
let body: Record<string, unknown>;
|
|
163
187
|
let headers: Record<string, string>;
|
|
164
188
|
if (state.era === 'legacy') {
|
|
@@ -192,9 +216,8 @@ export function mcpClient(options: McpClientOptions): McpClient {
|
|
|
192
216
|
return message['result'];
|
|
193
217
|
};
|
|
194
218
|
|
|
219
|
+
/** The legacy handshake. The era is decided only once it succeeds: a failure leaves it open. */
|
|
195
220
|
const initialize = async (signal: AbortSignal | undefined): Promise<void> => {
|
|
196
|
-
state.era = 'legacy';
|
|
197
|
-
state.session = null;
|
|
198
221
|
const id = state.next++;
|
|
199
222
|
const answer = await post(
|
|
200
223
|
{
|
|
@@ -217,10 +240,32 @@ export function mcpClient(options: McpClientOptions): McpClient {
|
|
|
217
240
|
'malformed',
|
|
218
241
|
);
|
|
219
242
|
}
|
|
220
|
-
|
|
243
|
+
const opened = answer.headers.get('mcp-session-id');
|
|
221
244
|
const notify = { jsonrpc: '2.0', method: 'notifications/initialized' };
|
|
222
|
-
const session =
|
|
245
|
+
const session = opened === null ? {} : { 'mcp-session-id': opened };
|
|
223
246
|
await post(notify, { 'mcp-protocol-version': LEGACY, ...session }, signal);
|
|
247
|
+
state.era = 'legacy';
|
|
248
|
+
state.session = opened;
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Joins the handshake in flight, or starts one. A handshake another caller's abort ended is
|
|
253
|
+
* started again under this caller's own signal — someone else's abort is never this call's.
|
|
254
|
+
*/
|
|
255
|
+
const negotiate = async (signal: AbortSignal | undefined): Promise<void> => {
|
|
256
|
+
for (;;) {
|
|
257
|
+
negotiating ??= initialize(signal).finally(() => {
|
|
258
|
+
negotiating = undefined;
|
|
259
|
+
});
|
|
260
|
+
const shared = negotiating;
|
|
261
|
+
try {
|
|
262
|
+
await shared;
|
|
263
|
+
return;
|
|
264
|
+
} catch (error) {
|
|
265
|
+
const theirs = isUltimateError(error) && error.code === 'X_ABORTED';
|
|
266
|
+
if (!theirs || signal?.aborted === true) throw error;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
224
269
|
};
|
|
225
270
|
|
|
226
271
|
/**
|
|
@@ -265,21 +310,26 @@ export function mcpClient(options: McpClientOptions): McpClient {
|
|
|
265
310
|
method: string,
|
|
266
311
|
params: Record<string, unknown>,
|
|
267
312
|
signal: AbortSignal | undefined,
|
|
313
|
+
sent?: { id?: number },
|
|
268
314
|
): Promise<Record<string, unknown>> => {
|
|
269
315
|
listen();
|
|
270
|
-
if (state.era === undefined) {
|
|
316
|
+
if (state.era === undefined && negotiating === undefined) {
|
|
271
317
|
try {
|
|
272
|
-
const result = await rpc(method, params, signal);
|
|
318
|
+
const result = await rpc(method, params, signal, sent);
|
|
273
319
|
state.era = 'modern';
|
|
274
320
|
return result;
|
|
275
321
|
} catch (error) {
|
|
276
322
|
if (!(error instanceof McpRemoteRefusedError) || !eraRefusal(error)) throw error;
|
|
277
|
-
|
|
278
|
-
|
|
323
|
+
// A sibling's first call settled the era while this one was out: its answer stands.
|
|
324
|
+
if (state.era === 'modern') throw error;
|
|
279
325
|
}
|
|
280
326
|
}
|
|
327
|
+
if (state.era === undefined) {
|
|
328
|
+
await negotiate(signal);
|
|
329
|
+
listen();
|
|
330
|
+
}
|
|
281
331
|
try {
|
|
282
|
-
return await rpc(method, params, signal);
|
|
332
|
+
return await rpc(method, params, signal, sent);
|
|
283
333
|
} catch (error) {
|
|
284
334
|
// A legacy session the server forgot (404) is re-opened ONCE, as the transport spec says.
|
|
285
335
|
if (!(error instanceof McpRemoteRefusedError) || error.meta?.['status'] !== 404) throw error;
|
|
@@ -289,9 +339,9 @@ export function mcpClient(options: McpClientOptions): McpClient {
|
|
|
289
339
|
listener.close();
|
|
290
340
|
listener = undefined;
|
|
291
341
|
}
|
|
292
|
-
await
|
|
342
|
+
await negotiate(signal);
|
|
293
343
|
listen();
|
|
294
|
-
return rpc(method, params, signal);
|
|
344
|
+
return rpc(method, params, signal, sent);
|
|
295
345
|
}
|
|
296
346
|
};
|
|
297
347
|
|
|
@@ -301,8 +351,9 @@ export function mcpClient(options: McpClientOptions): McpClient {
|
|
|
301
351
|
async listTools(listOptions = {}) {
|
|
302
352
|
const tools: RemoteTool[] = [];
|
|
303
353
|
let cursor: string | undefined;
|
|
304
|
-
// Paged; bounded so a server that loops its cursor cannot hold the boot forever
|
|
305
|
-
|
|
354
|
+
// Paged; bounded so a server that loops its cursor cannot hold the boot forever — and a list
|
|
355
|
+
// still unfinished at the bound is refused, never handed back as if it were whole.
|
|
356
|
+
for (let page = 0; page < MAX_TOOL_PAGES; page += 1) {
|
|
306
357
|
const result = await call(
|
|
307
358
|
'tools/list',
|
|
308
359
|
cursor === undefined ? {} : { cursor },
|
|
@@ -312,9 +363,12 @@ export function mcpClient(options: McpClientOptions): McpClient {
|
|
|
312
363
|
if (isJsonObject(tool) && typeof tool['name'] === 'string') tools.push(remoteTool(tool));
|
|
313
364
|
}
|
|
314
365
|
cursor = typeof result['nextCursor'] === 'string' ? result['nextCursor'] : undefined;
|
|
315
|
-
if (cursor === undefined)
|
|
366
|
+
if (cursor === undefined) return tools;
|
|
316
367
|
}
|
|
317
|
-
|
|
368
|
+
throw refused(
|
|
369
|
+
`paged past ${String(MAX_TOOL_PAGES)} tools/list pages without an end`,
|
|
370
|
+
'malformed',
|
|
371
|
+
);
|
|
318
372
|
},
|
|
319
373
|
close() {
|
|
320
374
|
if (typeof listener === 'object') listener.close();
|
|
@@ -322,23 +376,28 @@ export function mcpClient(options: McpClientOptions): McpClient {
|
|
|
322
376
|
},
|
|
323
377
|
async callTool(tool, args, callOptions = {}) {
|
|
324
378
|
const { signal } = callOptions;
|
|
379
|
+
const sent: { id?: number } = {};
|
|
325
380
|
try {
|
|
326
|
-
const result = await call('tools/call', { name: tool, arguments: args }, signal);
|
|
381
|
+
const result = await call('tools/call', { name: tool, arguments: args }, signal, sent);
|
|
327
382
|
return { isError: result['isError'] === true, text: resultText(result) };
|
|
328
|
-
}
|
|
329
|
-
|
|
383
|
+
} catch (error) {
|
|
384
|
+
// Only an abort that interrupted a request already sent is news to the server.
|
|
385
|
+
if (signal?.aborted === true && state.era === 'legacy' && sent.id !== undefined) {
|
|
386
|
+
cancelled(tool, sent.id);
|
|
387
|
+
}
|
|
388
|
+
throw error;
|
|
330
389
|
}
|
|
331
390
|
},
|
|
332
391
|
};
|
|
333
392
|
|
|
334
393
|
/** Legacy servers hear a cancellation as a notification; best effort, and said so in the log. */
|
|
335
|
-
function cancelled(tool: string): void {
|
|
394
|
+
function cancelled(tool: string, requestId: number): void {
|
|
336
395
|
const headers: Record<string, string> = { 'mcp-protocol-version': LEGACY };
|
|
337
396
|
if (typeof state.session === 'string') headers['mcp-session-id'] = state.session;
|
|
338
397
|
const notice = {
|
|
339
398
|
jsonrpc: '2.0',
|
|
340
399
|
method: 'notifications/cancelled',
|
|
341
|
-
params: { requestId
|
|
400
|
+
params: { requestId },
|
|
342
401
|
};
|
|
343
402
|
post(notice, headers, undefined).catch((error: unknown) => {
|
|
344
403
|
tryUseContext()?.logger.warn('mcp.remote.cancel_unsent', {
|
|
@@ -361,18 +420,19 @@ function remoteTool(raw: Record<string, unknown>): RemoteTool {
|
|
|
361
420
|
}
|
|
362
421
|
|
|
363
422
|
/**
|
|
364
|
-
* Whether a first modern request was refused for its ERA —
|
|
365
|
-
* shape, a body that is no answer, or the codes for an unknown version, method or request —
|
|
366
|
-
* than for its content. Only then is the legacy handshake tried; a modern server's own
|
|
367
|
-
* (`-32603`, a 503)
|
|
423
|
+
* Whether a first modern request was refused for its ERA — the 400/404/405 a legacy server gives an
|
|
424
|
+
* unknown shape, a body that is no answer, or the codes for an unknown version, method or request —
|
|
425
|
+
* rather than for its content. Only then is the legacy handshake tried; a modern server's own
|
|
426
|
+
* failure (`-32603`, a 503) and a refusal of the moment (429, 408, 403) are that failure.
|
|
368
427
|
*/
|
|
369
428
|
const ERA_RPC_CODES: ReadonlySet<number> = new Set([-32022, -32601, -32600, -32602]);
|
|
429
|
+
const ERA_STATUSES: ReadonlySet<number> = new Set([400, 404, 405]);
|
|
370
430
|
|
|
371
431
|
function eraRefusal(error: McpRemoteRefusedError): boolean {
|
|
372
432
|
const failure = error.meta?.['failure'];
|
|
373
433
|
const status = error.meta?.['status'];
|
|
374
434
|
const code = error.meta?.['rpcCode'];
|
|
375
435
|
if (failure === 'malformed') return true;
|
|
376
|
-
if (failure === 'status') return typeof status === 'number' && status
|
|
436
|
+
if (failure === 'status') return typeof status === 'number' && ERA_STATUSES.has(status);
|
|
377
437
|
return failure === 'rpc' && typeof code === 'number' && ERA_RPC_CODES.has(code);
|
|
378
438
|
}
|
package/src/remote-oauth.ts
CHANGED
|
@@ -146,6 +146,9 @@ export function mcpOAuthClient(options: McpOAuthClientOptions): McpOAuthClient {
|
|
|
146
146
|
async begin(serverUrl) {
|
|
147
147
|
const resource = urlOf(serverUrl);
|
|
148
148
|
if (resource === null) throw refused(serverUrl, 'is not an absolute URL');
|
|
149
|
+
// Discovery decides where the person consents: over cleartext, whoever sits on the path
|
|
150
|
+
// answers it (RFC 8414 §2 wants https for the issuer; loopback as below).
|
|
151
|
+
if (!secureEndpoint(resource)) throw refused(serverUrl, 'is not an https: URL');
|
|
149
152
|
const prm = await firstOf(serverUrl, wellKnown(resource, 'oauth-protected-resource'));
|
|
150
153
|
// RFC 9728 §3.3: metadata naming another resource is not this server's — a document copied
|
|
151
154
|
// from elsewhere would send the person's consent, and `resource`, to that server's issuer.
|
|
@@ -163,6 +166,9 @@ export function mcpOAuthClient(options: McpOAuthClientOptions): McpOAuthClient {
|
|
|
163
166
|
const issuerUrl = urlOf(issuer);
|
|
164
167
|
if (issuerUrl === null)
|
|
165
168
|
throw refused(serverUrl, 'names an authorization server that is no URL');
|
|
169
|
+
if (!secureEndpoint(issuerUrl)) {
|
|
170
|
+
throw refused(serverUrl, 'names an authorization server that is not https:');
|
|
171
|
+
}
|
|
166
172
|
const as = await firstOf(issuer, authServerCandidates(issuerUrl));
|
|
167
173
|
// RFC 8414 §3.3: a document answering for another issuer is not this issuer's.
|
|
168
174
|
if (as['issuer'] !== issuer) throw refused(issuer, 'published metadata for another issuer');
|
|
@@ -232,8 +238,8 @@ export function mcpOAuthClient(options: McpOAuthClientOptions): McpOAuthClient {
|
|
|
232
238
|
);
|
|
233
239
|
},
|
|
234
240
|
|
|
235
|
-
refresh
|
|
236
|
-
token(
|
|
241
|
+
async refresh(handshake, refreshToken) {
|
|
242
|
+
const tokens = await token(
|
|
237
243
|
handshake.tokenEndpoint,
|
|
238
244
|
new URLSearchParams({
|
|
239
245
|
grant_type: 'refresh_token',
|
|
@@ -241,7 +247,11 @@ export function mcpOAuthClient(options: McpOAuthClientOptions): McpOAuthClient {
|
|
|
241
247
|
client_id: options.clientId,
|
|
242
248
|
resource: handshake.resource,
|
|
243
249
|
}),
|
|
244
|
-
)
|
|
250
|
+
);
|
|
251
|
+
// RFC 6749 §6: the server MAY issue a new refresh token; when it does not, the one sent is
|
|
252
|
+
// still the one to keep — answered here so an app storing the answer cannot lose it.
|
|
253
|
+
return { ...tokens, refreshToken: tokens.refreshToken ?? refreshToken };
|
|
254
|
+
},
|
|
245
255
|
};
|
|
246
256
|
}
|
|
247
257
|
|
package/src/remote-tools.ts
CHANGED
|
@@ -40,6 +40,9 @@ export interface McpToolsDef {
|
|
|
40
40
|
readonly deadlineMs?: number;
|
|
41
41
|
/** The longest answer handed to a model; the middle of a longer one is cut. Default 20,000. */
|
|
42
42
|
readonly maxResultChars?: number;
|
|
43
|
+
/** The largest answer one call reads off the wire, in bytes (`mcpClient`'s). Default 16 MiB. */
|
|
44
|
+
readonly maxBytes?: number;
|
|
45
|
+
/** The transport under `outbound()` (`mcpClient`'s `fetch`). Default `fetch`. */
|
|
43
46
|
readonly fetch?: OutboundFetch;
|
|
44
47
|
/**
|
|
45
48
|
* Whether this app's OWN MCP surface (`include: 'exposed'`) and its in-app `agent()`s are offered
|
|
@@ -113,6 +116,7 @@ export function mcpTools(def: McpToolsDef): McpTools {
|
|
|
113
116
|
...(def.dial === undefined ? {} : { dial: def.dial }),
|
|
114
117
|
...(def.deadlineMs === undefined ? {} : { deadlineMs: def.deadlineMs }),
|
|
115
118
|
...(def.auth === undefined ? {} : { auth: def.auth }),
|
|
119
|
+
...(def.maxBytes === undefined ? {} : { maxBytes: def.maxBytes }),
|
|
116
120
|
...(def.fetch === undefined ? {} : { fetch: def.fetch }),
|
|
117
121
|
// The server's list moved: forget the verdict, so the next call re-lists and is held to the
|
|
118
122
|
// lock again — a drift there is `X_MCP_REMOTE_TOOL_CHANGED`, never a quietly new tool.
|
package/src/remote-wire.ts
CHANGED
|
@@ -3,8 +3,13 @@
|
|
|
3
3
|
// read out of it. No state lives here — `remote-client.ts` holds the era and the session.
|
|
4
4
|
|
|
5
5
|
import { isJsonObject } from '@ultimat3/core';
|
|
6
|
+
import { takeFrames } from '@ultimat3/core/internal/sse-frames';
|
|
6
7
|
import { META_PROTOCOL_VERSION } from './wire';
|
|
7
8
|
|
|
9
|
+
/** Each frame's data of a whole SSE body, parsed: core's frame reader, the last frame unterminated. */
|
|
10
|
+
const sseData = (text: string): readonly unknown[] =>
|
|
11
|
+
takeFrames(`${text}\n\n`).frames.map((frame) => parseJson(frame.data));
|
|
12
|
+
|
|
8
13
|
/** The answer body a streamable-HTTP server may send: a JSON-RPC response, or SSE carrying one. */
|
|
9
14
|
export function readRpcAnswer(
|
|
10
15
|
contentType: string | null,
|
|
@@ -12,13 +17,7 @@ export function readRpcAnswer(
|
|
|
12
17
|
id: number,
|
|
13
18
|
): Record<string, unknown> | undefined {
|
|
14
19
|
if (contentType?.toLowerCase().startsWith('text/event-stream') === true) {
|
|
15
|
-
for (const
|
|
16
|
-
const data = event
|
|
17
|
-
.split(/\r?\n/)
|
|
18
|
-
.filter((line) => line.startsWith('data:'))
|
|
19
|
-
.map((line) => line.slice(5).replace(/^ /, ''))
|
|
20
|
-
.join('\n');
|
|
21
|
-
const parsed = parseJson(data);
|
|
20
|
+
for (const parsed of sseData(text)) {
|
|
22
21
|
// A server may interleave its own requests and notifications; only OUR answer counts.
|
|
23
22
|
if (isJsonObject(parsed) && parsed['id'] === id) return parsed;
|
|
24
23
|
}
|
|
@@ -32,13 +31,7 @@ export function readRpcAnswer(
|
|
|
32
31
|
export function readNotifications(contentType: string | null, text: string): readonly string[] {
|
|
33
32
|
if (contentType?.toLowerCase().startsWith('text/event-stream') !== true) return [];
|
|
34
33
|
const methods: string[] = [];
|
|
35
|
-
for (const
|
|
36
|
-
const data = event
|
|
37
|
-
.split(/\r?\n/)
|
|
38
|
-
.filter((line) => line.startsWith('data:'))
|
|
39
|
-
.map((line) => line.slice(5).replace(/^ /, ''))
|
|
40
|
-
.join('\n');
|
|
41
|
-
const parsed = parseJson(data);
|
|
34
|
+
for (const parsed of sseData(text)) {
|
|
42
35
|
if (
|
|
43
36
|
isJsonObject(parsed) &&
|
|
44
37
|
parsed['id'] === undefined &&
|
package/src/runtime-tool.ts
CHANGED
|
@@ -11,8 +11,8 @@ import type { KnownPermission } from '@ultimat3/policy';
|
|
|
11
11
|
import { can } from '@ultimat3/policy';
|
|
12
12
|
import { McpCatalogUnresolvedError } from './catalog-errors';
|
|
13
13
|
import { McpToolUnsafeError } from './errors';
|
|
14
|
-
import { toolFrom } from './from-action';
|
|
15
|
-
import type { AnyMcpTool, McpToolAnnotations } from './registry';
|
|
14
|
+
import { throughDoor, toolFrom } from './from-action';
|
|
15
|
+
import type { AnyMcpTool, McpDoor, McpToolAnnotations } from './registry';
|
|
16
16
|
import { runtimeInputSchema } from './runtime-schema';
|
|
17
17
|
import type { JsonSchema } from './wire';
|
|
18
18
|
|
|
@@ -21,6 +21,11 @@ export interface RuntimeToolArgs {
|
|
|
21
21
|
readonly input: Readonly<Record<string, unknown>>;
|
|
22
22
|
/** The ambient request context, `actor` set to the MCP caller — the tenant's, on a `tenant` server. */
|
|
23
23
|
readonly ctx: Ctx;
|
|
24
|
+
/**
|
|
25
|
+
* The `'meta-split'` dispatcher this call came through, and the `split.fields` its envelope
|
|
26
|
+
* carried. Absent on every other path.
|
|
27
|
+
*/
|
|
28
|
+
readonly door?: McpDoor;
|
|
24
29
|
}
|
|
25
30
|
|
|
26
31
|
export interface RuntimeToolDefinition {
|
|
@@ -92,15 +97,16 @@ export function runtimeTool(def: RuntimeToolDefinition): McpRuntimeTool {
|
|
|
92
97
|
const ctx = useContext();
|
|
93
98
|
guardActionBeforeInput(policy, { actor: actorOf(ctx), ctx, action: name }, 'mcp');
|
|
94
99
|
}),
|
|
95
|
-
|
|
100
|
+
...throughDoor(({ input, actor, door }) =>
|
|
96
101
|
// The caller is the actor for the whole call, exactly as `app-tool.ts` runs one.
|
|
97
102
|
asCallerContext(actor, async () => {
|
|
98
103
|
const ctx = useContext();
|
|
99
104
|
guardActionBeforeInput(policy, { actor: actorOf(ctx), ctx, action: name }, 'mcp');
|
|
100
105
|
const args = input as Readonly<Record<string, unknown>>;
|
|
101
106
|
guardAction(policy, { actor: actorOf(ctx), input: args, ctx, action: name }, 'mcp');
|
|
102
|
-
return def.run({ input: args, ctx });
|
|
107
|
+
return def.run({ input: args, ctx, ...(door === undefined ? {} : { door }) });
|
|
103
108
|
}),
|
|
109
|
+
),
|
|
104
110
|
});
|
|
105
111
|
const handle: McpRuntimeTool = Object.freeze({ name, scope: def.scope });
|
|
106
112
|
BUILT.set(handle, tool);
|