@ultimat3/mcp 31.47.1 → 31.49.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/README.md CHANGED
@@ -47,7 +47,7 @@ reads only the catalog still knows what it is holding.
47
47
  | 3. Parse | one statement, a read leader, no mutating keyword at statement level, no lock — clause **or** `pg_advisory_*` call — and no call into a banned function family, matched by prefix of the called name — quoted and schema-qualified spellings included — so a new spelling is refused by default and a column sharing a prefix is not; on a form with literals and comments blanked | `readonly-sql.ts` |
48
48
  | 4. Limits | `SET LOCAL statement_timeout`, a hard 1000-row ceiling (`limit` clamps into it, never past it) and a 256 KiB byte cap | `query-limits.ts` |
49
49
 
50
- **Banned function families** — each is a ban already made elsewhere in another spelling: `pg_notify` (= `NOTIFY`, a write keyword); server control (`pg_cancel_backend`, `pg_terminate_backend`, `pg_reload_*`, `pg_rotate_*`, `pg_switch_*`, `pg_promote`, `pg_wal_replay_*`); replication (`pg_logical_*`, `pg_create_*`, `pg_drop_*`, `pg_replication_*` — advancing a slot is a write no `ROLLBACK` undoes); `pg_file_*`; `txid_current` / `pg_current_xact_id`; `pg_import_*`; SQL run from a string (`*_to_xml*`, `ts_stat`, `ts_rewrite`). `U&"…"` is refused, never decoded; a keyword is a whole identifier (`set2` is a column). Catalog VIEWS (`pg_replication_slots`) are read `from`, never called.
50
+ **Banned function families** — each is a ban already made elsewhere in another spelling: `pg_notify` (= `NOTIFY`, a write keyword); server control (`pg_cancel_backend`, `pg_terminate_backend`, `pg_reload_*`, `pg_rotate_*`, `pg_switch_*`, `pg_promote`, `pg_wal_replay_*`); replication (`pg_logical_*`, `pg_create_*`, `pg_drop_*`, `pg_replication_*`, `pg_copy_*`, `pg_sync_replication_*` — advancing a slot is a write no `ROLLBACK` undoes); base backups (`pg_backup_*`, `pg_start_backup`, `pg_stop_backup`); `pg_file_*`; `txid_current` / `pg_current_xact_id`; catalog writes (`pg_import_*`, `pg_restore_*`, `pg_clear_*`); `EXPLAIN ANALYSE` as `EXPLAIN ANALYZE`; SQL run from a string (`*_to_xml*`, `ts_stat`, `ts_rewrite`). `U&"…"` is refused, never decoded; a keyword is a whole identifier (`set2` is a column). Catalog VIEWS (`pg_replication_slots`) are read `from`, never called.
51
51
 
52
52
  Banned SQL functions are matched as a **prefix of a CALLED function name** — add a family, never a name (`pg_sleep_for` passed an exact `pg_sleep` ban). The unit is the call (`name(`), so a column `pg_sleep_for_seconds` is fine; the call scan keeps quoted-identifier content (`"pg_advisory_lock"(1)` is a call), the keyword scan blanks it. `pg_advisory_*` (a session lock survives layer 2's `ROLLBACK`; `packages/testing/src/db-integration.test.ts`), `pg_sleep*` (the one ban that holds on PGlite), `nextval`/`setval` (a consumed id is not rolled back).
53
53
 
@@ -408,6 +408,10 @@ tool the agent reads after `list_tenants` (`docs`, `list_resources`).
408
408
  So the app's `resolve` may narrow, and is the one place that does. Held by
409
409
  `tenant-semantics.test.ts`.
410
410
 
411
+ **`tenant.arg` is reserved at every depth a tool reads.** `manage_resource` / `write_resource` /
412
+ `delete_resource` strip it from `params` too, so a tool whose schema is open to extra keys never
413
+ receives a second, different tenant beside the one it runs in.
414
+
411
415
  **Only `tools/call` names a tenant.** `resources/read`, `resources/list`, `prompts/*` and
412
416
  `tools/list` run as the PERSON: a `tenant.arg` sent in their params is ignored, `resolve` is never
413
417
  asked, and a reader sees `caller.tenant === undefined` and no `orgId`. A resource that reads tenant
@@ -775,11 +779,12 @@ A driver without `introspect` is `X_MCP_JOB_TOOL_INVALID`.
775
779
  |---|---|
776
780
  | `recipes: [{ name, title, description, steps: [{ tool, why, example? }], notes? }]` | each served as `docs://recipes/<name>` (`text/markdown`) and through a read-only `docs` tool. Every step's tool must be in the catalog (`X_MCP_RECIPE_TOOL_UNKNOWN`), every example must pass its input (`X_MCP_RECIPE_EXAMPLE_INVALID`), at boot, all offenders at once |
777
781
  | `recipes: await markdownRecipes({ dir })` | one `*.md` per recipe, body served verbatim. Name = file name; `---` `title:` / `description:` frontmatter, else the first `# ` heading and paragraph. A ```` ```call ```` fence — `tool {"arg": "value"}` — is a step, checked like one; a whole `"<name>"` value is a placeholder, any value at boot. A `docs://recipes/` link in the text that names no recipe is `X_MCP_RECIPE_LINK_DANGLING` |
778
- | `extraRecipes: (caller) => recipes` | the caller's own (a tenant's runbooks), asked per request: on `docs` as `source: 'caller'`, on `resources/list` and `resources/read` to that caller alone. Not boot-checked; one naming a tool the caller cannot call is not shown |
782
+ | `extraRecipes: (caller) => recipes` | the caller's own (a tenant's runbooks), asked per request: on `docs` as `source: 'caller'`, on `resources/list` and `resources/read` to that caller alone (a throw is `-32603` on all three, audited `failed`). Not boot-checked; one naming a tool the caller cannot call is not shown |
779
783
 
780
784
  `docs({})` lists what this caller can follow; `docs({ name })` / `docs({ uri })` reads one;
781
785
  `docs({ q })` inlines the best match (3 points a word in name or title, 2 in description, 1 in the
782
- body) and names the nearest names on a miss — never an empty answer while a recipe is visible. A
786
+ body) and names the nearest names on a miss — never an empty answer while a recipe is visible. `q`
787
+ is at most 1000 characters (`X_INPUT_INVALID` beyond); a miss compares its first 16 words. A
783
788
  recipe is visible only when every step's tool is visible to the caller and its scope is on the
784
789
  token; hidden and unknown are the same not-found. An `UltimateError`'s `docs://recipes/<name>` is
785
790
  checked at load (`X_MCP_RECIPE_UNKNOWN`). In a contract test, `replayRecipes(server, recipes, {
@@ -799,8 +804,8 @@ lists resources per caller — what `extraRecipes` is built on.
799
804
  | output | `{ untrusted, isError }`: the remote's text inside `<untrusted source="mcp:<name>/<tool>">`, middle cut past `maxResultChars`; invisible format characters (`\p{Cf}`) stripped, then every `<` (and full-width `<`, small `﹤`) written `&lt;` — no tag-shaped pattern left to bypass |
800
805
  | `expose` | default `false`: the actions are this app's, not its `/mcp`'s — `include: 'exposed'` leaves them out, while an in-app `agent()` is still offered them (`agents: true`). `expose: true` opts one remote server in, making this app's `/mcp` answer for a third party's tools |
801
806
  | `reverifyMs` | default 3,600,000: one verdict against the live server stands this long (read on `clock`, default `systemClock`), then the next call re-lists and holds it to the lock again — a remote that changes and announces nothing is caught within the hour |
802
- | `mcpClient({ name, url, dial, deadlineMs, auth })` | over core's `outbound()`; modern era first, the legacy handshake when the server refuses it for its era. A text-only result is a success. `X_MCP_REMOTE_REFUSED`'s `meta.failure` tells `transport` / `status` / `rpc` / `malformed` apart; a tool's own `isError` is a result. A 401 is `X_MCP_REMOTE_AUTH_REQUIRED` with `meta.resourceMetadata` |
803
- | `mcpOAuthClient({ clientId, clientName, redirectUri, scopes? })` | the upstream's OAuth: `begin(serverUrl)` reads RFC 9728 then RFC 8414 metadata and answers `{ authorizeUrl, handshake }` (PKCE S256 from `@ultimat3/auth`, `resource` per RFC 8707); `exchange(handshake, { code, state })` and `refresh(handshake, token)` answer `{ accessToken, refreshToken, expiresIn }`. `clientId` is the HTTPS URL this app serves `metadata()` at (a client ID metadata document). Keep the handshake server-side; return the token from `auth` |
807
+ | `mcpClient({ name, url, dial, deadlineMs, auth })` | over core's `outbound()`; modern era first, the legacy handshake when the server refuses it for its era (a 400/404/405, an unknown-version/method/request JSON-RPC code, a body that is no answer — never a 429, 408 or 403; one handshake shared by concurrent first calls, and a failed one decides nothing). A `tools/list` whose cursor outlasts 50 pages is `malformed`, never a truncated list. A text-only result is a success. `X_MCP_REMOTE_REFUSED`'s `meta.failure` tells `transport` / `status` / `rpc` / `malformed` apart; a tool's own `isError` is a result. A 401 is `X_MCP_REMOTE_AUTH_REQUIRED` with `meta.resourceMetadata` |
808
+ | `mcpOAuthClient({ clientId, clientName, redirectUri, scopes? })` | the upstream's OAuth: `begin(serverUrl)` reads RFC 9728 then RFC 8414 metadata and answers `{ authorizeUrl, handshake }` (PKCE S256 from `@ultimat3/auth`, `resource` per RFC 8707); `exchange(handshake, { code, state })` and `refresh(handshake, token)` answer `{ accessToken, refreshToken, expiresIn }`. When the server's refresh answer carries no `refresh_token`, `refresh` answers the one it was passed (RFC 6749 §6: the old one stays valid), so storing the answer never loses it; `null` only from `exchange`. `begin` refuses a server URL or an issuer that is not `https:` (loopback `http:` aside), before fetching its metadata. `clientId` is the HTTPS URL this app serves `metadata()` at (a client ID metadata document). Keep the handshake server-side; return the token from `auth` |
804
809
 
805
810
  ## Errors
806
811
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/mcp",
3
- "version": "31.47.1",
3
+ "version": "31.49.0",
4
4
  "description": "MCP server, dev tools, and the action-to-tool projection \u2014 one authz system, two surfaces",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -44,15 +44,15 @@
44
44
  "test": "bun test"
45
45
  },
46
46
  "dependencies": {
47
- "@ultimat3/action": "31.47.1",
48
- "@ultimat3/auth": "31.47.1",
49
- "@ultimat3/core": "31.47.1",
50
- "@ultimat3/db": "31.47.1",
51
- "@ultimat3/entity": "31.47.1",
52
- "@ultimat3/http": "31.47.1",
53
- "@ultimat3/jobs": "31.47.1",
54
- "@ultimat3/policy": "31.47.1",
55
- "@ultimat3/query": "31.47.1",
56
- "@ultimat3/schema": "31.47.1"
47
+ "@ultimat3/action": "31.49.0",
48
+ "@ultimat3/auth": "31.49.0",
49
+ "@ultimat3/core": "31.49.0",
50
+ "@ultimat3/db": "31.49.0",
51
+ "@ultimat3/entity": "31.49.0",
52
+ "@ultimat3/http": "31.49.0",
53
+ "@ultimat3/jobs": "31.49.0",
54
+ "@ultimat3/policy": "31.49.0",
55
+ "@ultimat3/query": "31.49.0",
56
+ "@ultimat3/schema": "31.49.0"
57
57
  }
58
58
  }
@@ -30,10 +30,15 @@
30
30
  * - CONTROL THE SERVER (`pg_reload_*`, `pg_rotate_*`, `pg_switch_*`, `pg_promote`,
31
31
  * `pg_wal_replay_*`) — the family `pg_cancel_backend`/`pg_terminate_backend` established;
32
32
  * - CONSUME THE REPLICATION STREAM (`pg_create_*`, `pg_drop_*`, `pg_replication_*`,
33
- * `pg_logical_*`) — `pg_logical_slot_get_changes` advances a slot's confirmed position. The
34
- * catalog VIEWS beside them (`pg_replication_slots`) are read `from`, never called;
33
+ * `pg_logical_*`, `pg_copy_*`, `pg_sync_replication_*`) — `pg_logical_slot_get_changes` advances
34
+ * a slot's confirmed position, and copying or syncing a slot creates one outside the
35
+ * transaction. The catalog VIEWS beside them (`pg_replication_slots`) are read `from`, never
36
+ * called;
37
+ * - RUN A BASE BACKUP (`pg_backup_*`, and `pg_start_backup`/`pg_stop_backup` before 15) — server
38
+ * control again, forcing a checkpoint;
35
39
  * - WRITE A FILE (`pg_file_*`) — the other half of `pg_read_*`;
36
- * - WRITE THE CATALOG (`pg_import_*`) — `pg_import_system_collations` inserts `pg_collation` rows;
40
+ * - WRITE THE CATALOG (`pg_import_*`, `pg_restore_*`, `pg_clear_*`) — `pg_import_system_collations`
41
+ * inserts `pg_collation` rows; 18's `pg_restore_relation_stats` rewrites `pg_class`;
37
42
  * - RUN A QUERY HANDED TO IT AS TEXT (`query_to_xml*`, `cursor_to_xml*`, `table_to_xml*`,
38
43
  * `schema_to_xml*`, `database_to_xml*`, `ts_stat`, `ts_rewrite`) — the statement is a string
39
44
  * literal, which every pass of the scan blanks by design, so whatever it calls is invisible.
@@ -50,7 +55,10 @@ const FORBIDDEN_FUNCTIONS = [
50
55
  'lo_',
51
56
  'nextval',
52
57
  'pg_advisory_',
58
+ 'pg_backup_',
53
59
  'pg_cancel_backend',
60
+ 'pg_clear_',
61
+ 'pg_copy_',
54
62
  'pg_create_',
55
63
  'pg_current_xact_id',
56
64
  'pg_drop_',
@@ -63,14 +71,18 @@ const FORBIDDEN_FUNCTIONS = [
63
71
  'pg_read_',
64
72
  'pg_reload_',
65
73
  'pg_replication_',
74
+ 'pg_restore_',
66
75
  'pg_rotate_',
67
76
  'pg_sleep',
77
+ 'pg_start_backup',
68
78
  'pg_stat_file',
69
79
  'pg_stat_reset',
70
80
  // Not reachable from `pg_stat_reset`: the extension spells the same reset with the statistics
71
81
  // view's name in the middle, so a prefix of one is not a prefix of the other.
72
82
  'pg_stat_statements_reset',
83
+ 'pg_stop_backup',
73
84
  'pg_switch_',
85
+ 'pg_sync_replication_',
74
86
  'pg_terminate_backend',
75
87
  'pg_try_advisory_',
76
88
  'pg_wal_replay_',
@@ -19,11 +19,13 @@ const READ_LEADERS = new Set(['select', 'with', 'explain', 'show', 'table', 'val
19
19
  /**
20
20
  * Keywords that make a statement a write. Includes transaction control (a session the tool
21
21
  * left open is a lock held on a shared dev DB), `set`/`copy` (session mutation, file I/O),
22
- * and `analyze` — `EXPLAIN ANALYZE` executes the plan and `ANALYZE t` rewrites statistics,
23
- * so both are refused rather than special-cased. One rule, no exceptions to remember.
22
+ * and `analyze` (with `analyse`, the spelling Postgres also accepts) — `EXPLAIN ANALYZE` executes
23
+ * the plan and `ANALYZE t` rewrites statistics, so both are refused rather than special-cased. One
24
+ * rule, no exceptions to remember.
24
25
  */
25
26
  const WRITE_KEYWORDS = new Set([
26
27
  'alter',
28
+ 'analyse',
27
29
  'analyze',
28
30
  'begin',
29
31
  'call',
@@ -121,6 +123,18 @@ export function assertReadOnlyQuery(sql: string): string {
121
123
  );
122
124
  }
123
125
  }
126
+ // `explain ("analyze")` is `explain (analyze)`: the option list names options, and a quoted
127
+ // name is the same option — so it is read in the form that keeps identifier content. Only the
128
+ // option list: a column quoted as `"analyze"` elsewhere is a column.
129
+ if (
130
+ leader === 'explain' &&
131
+ explainOptions(stripLiteralsAndComments(sql, 'keep')).some(ANALYZES)
132
+ ) {
133
+ throw rejected(
134
+ 'the statement contains the mutating keyword "analyze" as a quoted EXPLAIN option',
135
+ 'SELECT * FROM <table> LIMIT 10 -- or EXPLAIN with no ANALYZE: db.query never executes the plan it describes',
136
+ );
137
+ }
124
138
  // A family refuses a CALL, never a bare word: scanning every word rejected a column named
125
139
  // `pg_sleep_for_seconds`, and scanning the blanked form missed `"pg_advisory_lock"(1)`, which
126
140
  // is the same call wearing quotes. So this pass reads the form that keeps identifier content.
@@ -147,6 +161,14 @@ export function assertReadOnlyQuery(sql: string): string {
147
161
  return verbatim(sql);
148
162
  }
149
163
 
164
+ const ANALYZES = (word: string): boolean => word === 'analyze' || word === 'analyse';
165
+
166
+ /** The words of `explain ( … )`'s option list, lower-cased; none when it has no list. */
167
+ function explainOptions(kept: string): readonly string[] {
168
+ const list = /^\s*explain\s*\(([^)]*)\)/i.exec(kept)?.[1] ?? '';
169
+ return list.toLowerCase().match(WORD) ?? [];
170
+ }
171
+
150
172
  /**
151
173
  * The caller's bytes, minus surrounding whitespace and one trailing `;`. Anything past that
152
174
  * semicolon is whitespace or a comment — the single-statement check above already proved the
@@ -9,6 +9,11 @@ import type { McpRecipe } from './recipes';
9
9
  import { renderRecipe } 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(
@@ -54,17 +59,27 @@ function scoreOf(recipe: McpRecipe, asked: readonly string[]): number {
54
59
  return score;
55
60
  }
56
61
 
57
- /** The smallest edit distance from the query, or any of its words, to the name or a title word. */
62
+ /**
63
+ * The smallest edit distance from the query, or any of its words, to the name or a title word.
64
+ * Bounded: the query is caller input and the distance is |probe| x |candidate|, so only the first
65
+ * `MAX_PROBES` words count, each cut to `MAX_PROBE_LENGTH`, and a pair whose lengths already differ
66
+ * by the best distance found is skipped — it cannot beat it.
67
+ */
58
68
  function closeness(recipe: McpRecipe, target: string, asked: readonly string[]): number {
59
- const candidates = [recipe.name, ...words(recipe.title)];
60
- const probes = [target, ...asked];
69
+ const candidates = [recipe.name, ...words(recipe.title)].map(clamped);
70
+ const probes = [target, ...asked.slice(0, MAX_PROBES)].map(clamped);
61
71
  let best = Number.POSITIVE_INFINITY;
62
72
  for (const probe of probes) {
63
- for (const candidate of candidates) best = Math.min(best, distance(probe, candidate));
73
+ for (const candidate of candidates) {
74
+ if (Math.abs(probe.length - candidate.length) >= best) continue;
75
+ best = Math.min(best, distance(probe, candidate));
76
+ }
64
77
  }
65
78
  return best;
66
79
  }
67
80
 
81
+ const clamped = (text: string): string => text.slice(0, MAX_PROBE_LENGTH);
82
+
68
83
  /** Levenshtein, two rows. */
69
84
  function distance(a: string, b: string): number {
70
85
  let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
@@ -5,7 +5,7 @@
5
5
  */
6
6
 
7
7
  import { renderCauseValue, UltimateError } from '@ultimat3/core';
8
- import { rankRecipes } from './recipe-search';
8
+ import { MAX_QUERY_LENGTH, rankRecipes } from './recipe-search';
9
9
  import type { McpRecipe } from './recipes';
10
10
  import { recipeNameOf, recipeUri, recipeVisible, renderRecipe } from './recipes';
11
11
  import type { AnyMcpTool, McpCaller, McpToolResult } from './registry';
@@ -55,7 +55,12 @@ export function recipesTool(
55
55
  properties: {
56
56
  name: { type: 'string', description: 'A recipe name from docs({}).' },
57
57
  uri: { type: 'string', description: 'A docs://recipes/ URI, as an error links one.' },
58
- q: { type: 'string', description: 'Words describing the task.' },
58
+ // A miss quotes `q` back and ranks every recipe against it: a megabyte of it is refused.
59
+ q: {
60
+ type: 'string',
61
+ maxLength: MAX_QUERY_LENGTH,
62
+ description: 'Words describing the task.',
63
+ },
59
64
  },
60
65
  additionalProperties: false,
61
66
  },
@@ -76,12 +76,15 @@ const DEFAULT_DEADLINE_MS = 30_000;
76
76
  const DEFAULT_LISTEN_MS = 300_000;
77
77
  const MODERN = MCP_MODERN_VERSIONS[0];
78
78
  const LEGACY = MCP_LEGACY_VERSIONS[0];
79
+ const MAX_TOOL_PAGES = 50;
79
80
 
80
81
  export function mcpClient(options: McpClientOptions): McpClient {
81
82
  const state: { era?: 'modern' | 'legacy'; session?: string | null; next: number } = { next: 1 };
82
83
  const listenMs = finiteCount('mcpClient', 'listenMs', options.listenMs ?? DEFAULT_LISTEN_MS, 1);
83
84
  /** The open `GET` stream; `'unsupported'` once the server answered it 405, `'closed'` after close(). */
84
85
  let listener: Listener | 'unsupported' | 'closed' | undefined;
86
+ /** The one handshake in flight: concurrent calls that need a session share it, never race two. */
87
+ let negotiating: Promise<void> | undefined;
85
88
  const refused = (
86
89
  reason: string,
87
90
  failure: McpRemoteFailure,
@@ -157,8 +160,10 @@ export function mcpClient(options: McpClientOptions): McpClient {
157
160
  method: string,
158
161
  params: Record<string, unknown>,
159
162
  signal: AbortSignal | undefined,
163
+ sent?: { id?: number },
160
164
  ): Promise<Record<string, unknown>> => {
161
165
  const id = state.next++;
166
+ if (sent !== undefined) sent.id = id;
162
167
  let body: Record<string, unknown>;
163
168
  let headers: Record<string, string>;
164
169
  if (state.era === 'legacy') {
@@ -192,9 +197,8 @@ export function mcpClient(options: McpClientOptions): McpClient {
192
197
  return message['result'];
193
198
  };
194
199
 
200
+ /** The legacy handshake. The era is decided only once it succeeds: a failure leaves it open. */
195
201
  const initialize = async (signal: AbortSignal | undefined): Promise<void> => {
196
- state.era = 'legacy';
197
- state.session = null;
198
202
  const id = state.next++;
199
203
  const answer = await post(
200
204
  {
@@ -217,10 +221,32 @@ export function mcpClient(options: McpClientOptions): McpClient {
217
221
  'malformed',
218
222
  );
219
223
  }
220
- state.session = answer.headers.get('mcp-session-id');
224
+ const opened = answer.headers.get('mcp-session-id');
221
225
  const notify = { jsonrpc: '2.0', method: 'notifications/initialized' };
222
- const session = state.session === null ? {} : { 'mcp-session-id': state.session };
226
+ const session = opened === null ? {} : { 'mcp-session-id': opened };
223
227
  await post(notify, { 'mcp-protocol-version': LEGACY, ...session }, signal);
228
+ state.era = 'legacy';
229
+ state.session = opened;
230
+ };
231
+
232
+ /**
233
+ * Joins the handshake in flight, or starts one. A handshake another caller's abort ended is
234
+ * started again under this caller's own signal — someone else's abort is never this call's.
235
+ */
236
+ const negotiate = async (signal: AbortSignal | undefined): Promise<void> => {
237
+ for (;;) {
238
+ negotiating ??= initialize(signal).finally(() => {
239
+ negotiating = undefined;
240
+ });
241
+ const shared = negotiating;
242
+ try {
243
+ await shared;
244
+ return;
245
+ } catch (error) {
246
+ const theirs = isUltimateError(error) && error.code === 'X_ABORTED';
247
+ if (!theirs || signal?.aborted === true) throw error;
248
+ }
249
+ }
224
250
  };
225
251
 
226
252
  /**
@@ -265,21 +291,26 @@ export function mcpClient(options: McpClientOptions): McpClient {
265
291
  method: string,
266
292
  params: Record<string, unknown>,
267
293
  signal: AbortSignal | undefined,
294
+ sent?: { id?: number },
268
295
  ): Promise<Record<string, unknown>> => {
269
296
  listen();
270
- if (state.era === undefined) {
297
+ if (state.era === undefined && negotiating === undefined) {
271
298
  try {
272
- const result = await rpc(method, params, signal);
299
+ const result = await rpc(method, params, signal, sent);
273
300
  state.era = 'modern';
274
301
  return result;
275
302
  } catch (error) {
276
303
  if (!(error instanceof McpRemoteRefusedError) || !eraRefusal(error)) throw error;
277
- await initialize(signal);
278
- listen();
304
+ // A sibling's first call settled the era while this one was out: its answer stands.
305
+ if (state.era === 'modern') throw error;
279
306
  }
280
307
  }
308
+ if (state.era === undefined) {
309
+ await negotiate(signal);
310
+ listen();
311
+ }
281
312
  try {
282
- return await rpc(method, params, signal);
313
+ return await rpc(method, params, signal, sent);
283
314
  } catch (error) {
284
315
  // A legacy session the server forgot (404) is re-opened ONCE, as the transport spec says.
285
316
  if (!(error instanceof McpRemoteRefusedError) || error.meta?.['status'] !== 404) throw error;
@@ -289,9 +320,9 @@ export function mcpClient(options: McpClientOptions): McpClient {
289
320
  listener.close();
290
321
  listener = undefined;
291
322
  }
292
- await initialize(signal);
323
+ await negotiate(signal);
293
324
  listen();
294
- return rpc(method, params, signal);
325
+ return rpc(method, params, signal, sent);
295
326
  }
296
327
  };
297
328
 
@@ -301,8 +332,9 @@ export function mcpClient(options: McpClientOptions): McpClient {
301
332
  async listTools(listOptions = {}) {
302
333
  const tools: RemoteTool[] = [];
303
334
  let cursor: string | undefined;
304
- // Paged; bounded so a server that loops its cursor cannot hold the boot forever.
305
- for (let page = 0; page < 50; page += 1) {
335
+ // Paged; bounded so a server that loops its cursor cannot hold the boot forever — and a list
336
+ // still unfinished at the bound is refused, never handed back as if it were whole.
337
+ for (let page = 0; page < MAX_TOOL_PAGES; page += 1) {
306
338
  const result = await call(
307
339
  'tools/list',
308
340
  cursor === undefined ? {} : { cursor },
@@ -312,9 +344,12 @@ export function mcpClient(options: McpClientOptions): McpClient {
312
344
  if (isJsonObject(tool) && typeof tool['name'] === 'string') tools.push(remoteTool(tool));
313
345
  }
314
346
  cursor = typeof result['nextCursor'] === 'string' ? result['nextCursor'] : undefined;
315
- if (cursor === undefined) break;
347
+ if (cursor === undefined) return tools;
316
348
  }
317
- return tools;
349
+ throw refused(
350
+ `paged past ${String(MAX_TOOL_PAGES)} tools/list pages without an end`,
351
+ 'malformed',
352
+ );
318
353
  },
319
354
  close() {
320
355
  if (typeof listener === 'object') listener.close();
@@ -322,23 +357,28 @@ export function mcpClient(options: McpClientOptions): McpClient {
322
357
  },
323
358
  async callTool(tool, args, callOptions = {}) {
324
359
  const { signal } = callOptions;
360
+ const sent: { id?: number } = {};
325
361
  try {
326
- const result = await call('tools/call', { name: tool, arguments: args }, signal);
362
+ const result = await call('tools/call', { name: tool, arguments: args }, signal, sent);
327
363
  return { isError: result['isError'] === true, text: resultText(result) };
328
- } finally {
329
- if (signal?.aborted === true && state.era === 'legacy') cancelled(tool);
364
+ } catch (error) {
365
+ // Only an abort that interrupted a request already sent is news to the server.
366
+ if (signal?.aborted === true && state.era === 'legacy' && sent.id !== undefined) {
367
+ cancelled(tool, sent.id);
368
+ }
369
+ throw error;
330
370
  }
331
371
  },
332
372
  };
333
373
 
334
374
  /** Legacy servers hear a cancellation as a notification; best effort, and said so in the log. */
335
- function cancelled(tool: string): void {
375
+ function cancelled(tool: string, requestId: number): void {
336
376
  const headers: Record<string, string> = { 'mcp-protocol-version': LEGACY };
337
377
  if (typeof state.session === 'string') headers['mcp-session-id'] = state.session;
338
378
  const notice = {
339
379
  jsonrpc: '2.0',
340
380
  method: 'notifications/cancelled',
341
- params: { requestId: state.next - 1 },
381
+ params: { requestId },
342
382
  };
343
383
  post(notice, headers, undefined).catch((error: unknown) => {
344
384
  tryUseContext()?.logger.warn('mcp.remote.cancel_unsent', {
@@ -361,18 +401,19 @@ function remoteTool(raw: Record<string, unknown>): RemoteTool {
361
401
  }
362
402
 
363
403
  /**
364
- * Whether a first modern request was refused for its ERA — a 4xx a legacy server gives an unknown
365
- * shape, a body that is no answer, or the codes for an unknown version, method or request — rather
366
- * than for its content. Only then is the legacy handshake tried; a modern server's own failure
367
- * (`-32603`, a 503) is that failure.
404
+ * Whether a first modern request was refused for its ERA — the 400/404/405 a legacy server gives an
405
+ * unknown shape, a body that is no answer, or the codes for an unknown version, method or request —
406
+ * rather than for its content. Only then is the legacy handshake tried; a modern server's own
407
+ * failure (`-32603`, a 503) and a refusal of the moment (429, 408, 403) are that failure.
368
408
  */
369
409
  const ERA_RPC_CODES: ReadonlySet<number> = new Set([-32022, -32601, -32600, -32602]);
410
+ const ERA_STATUSES: ReadonlySet<number> = new Set([400, 404, 405]);
370
411
 
371
412
  function eraRefusal(error: McpRemoteRefusedError): boolean {
372
413
  const failure = error.meta?.['failure'];
373
414
  const status = error.meta?.['status'];
374
415
  const code = error.meta?.['rpcCode'];
375
416
  if (failure === 'malformed') return true;
376
- if (failure === 'status') return typeof status === 'number' && status >= 400 && status < 500;
417
+ if (failure === 'status') return typeof status === 'number' && ERA_STATUSES.has(status);
377
418
  return failure === 'rpc' && typeof code === 'number' && ERA_RPC_CODES.has(code);
378
419
  }
@@ -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: (handshake, refreshToken) =>
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
 
@@ -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 event of text.split(/\r?\n\r?\n/)) {
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 event of text.split(/\r?\n\r?\n/)) {
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 &&
@@ -154,7 +154,10 @@ function merge(boot: CatalogBoot, resolved: McpResolvedCatalog): CatalogView {
154
154
  if (boot.tenantArg !== undefined) refused(() => assertArgFree(boot.tenantArg ?? '', tool));
155
155
  }
156
156
  const all = [...boot.tools, ...resolved.tools];
157
- return { tools: new ToolRegistry().registerAll(all), meta: metaOf(boot, resolved, all) };
157
+ // Built with the reserved name, as the boot registry is: `params` reaches `resolve` through the
158
+ // meta dispatchers without passing `tenantStep`.
159
+ const tools = new ToolRegistry(boot.tenantArg).registerAll(all);
160
+ return { tools, meta: metaOf(boot, resolved, all) };
158
161
  }
159
162
 
160
163
  /** The boot groups plus the resolved ones, held to every boot check `MetaSurface.build` makes. */
@@ -1,6 +1,6 @@
1
- // `resources/read` — the document surface's three outcomes (hidden = absent, scope, read), every
2
- // one audited, and every provider call inside a `try`. Split from `server.ts` for the size ceiling;
3
- // the server passes what it owns, so this stays a function and never a second dispatcher.
1
+ // `resources/read` and `resources/list` — the document surface's three outcomes (hidden = absent,
2
+ // scope, read), every one audited, and every provider or source call inside a `try`. Split from
3
+ // `server.ts` for the size ceiling; the server passes what it owns, so these stay functions.
4
4
 
5
5
  import { asCallerContext } from '@ultimat3/action';
6
6
  import type { ErrorAudience } from '@ultimat3/core';
@@ -11,9 +11,9 @@ import { asFrameworkError, forAudience } from './framework-error';
11
11
  import type { McpEra } from './protocol-era';
12
12
  import { resourceNotFoundCode } from './protocol-era';
13
13
  import type { McpCaller } from './registry';
14
- import type { ResourceRegistry } from './resources';
14
+ import type { ResourceRegistry, ResourceResolution } from './resources';
15
15
  import { readResource } from './resources';
16
- import type { JsonRpcRequest, JsonRpcResponse } from './wire';
16
+ import type { JsonRpcId, JsonRpcRequest, JsonRpcResponse } from './wire';
17
17
  import {
18
18
  errorResponse,
19
19
  INTERNAL_ERROR,
@@ -52,7 +52,15 @@ export async function resourcesRead(
52
52
  return errorResponse(id, INVALID_PARAMS, 'resources/read params.uri must be a string');
53
53
  }
54
54
 
55
- const resolved = await on.resources.resolveFor(uri, caller);
55
+ // A per-caller SOURCE is an injected thunk too (`extraRecipes` is a tenant-runbook lookup), and
56
+ // `resolveFor` asks it for any URI the fixed list does not hold: it gets the same `try` the read
57
+ // below has, or its throw is the unanswered request that comment describes.
58
+ let resolved: ResourceResolution;
59
+ try {
60
+ resolved = await on.resources.resolveFor(uri, caller);
61
+ } catch (error) {
62
+ return failed(on, id, uri, `resource "${uri}" could not be read`, error, caller);
63
+ }
56
64
  switch (resolved.kind) {
57
65
  // OUTCOME 1. Absent AND hidden collapse to one answer with no `data`: this branch used to
58
66
  // return `available: [...every uri]`, so one wrong guess enumerated the whole catalog. No
@@ -103,20 +111,50 @@ export async function resourcesRead(
103
111
  on.audit.resourceRead({ uri, outcome: 'ok', caller });
104
112
  return resultResponse(id, { contents: [contents] });
105
113
  } catch (error) {
106
- const thrown = asFrameworkError(error);
107
- if (thrown !== undefined) {
108
- const framework = forAudience(thrown, on.audience);
109
- on.audit.resourceRead({ uri, outcome: 'failed', caller, code: framework.code });
110
- return errorResponse(id, INTERNAL_ERROR, `resource "${uri}" could not be read`, {
111
- code: framework.code,
112
- cause: framework.cause,
113
- fix: fixFor(framework, on.audience),
114
- ...(framework.docs === undefined ? {} : { docs: framework.docs }),
115
- });
116
- }
117
- // No internals: a provider's own message names a path, a query or a host the caller has no
118
- // business seeing, exactly as a failing tool's does.
119
- on.audit.resourceRead({ uri, outcome: 'failed', caller });
120
- return errorResponse(id, INTERNAL_ERROR, `resource "${uri}" could not be read`);
114
+ return failed(on, id, uri, `resource "${uri}" could not be read`, error, caller);
115
+ }
116
+ }
117
+
118
+ /**
119
+ * `resources/list`: the fixed list plus every per-caller source, each source call inside the `try`.
120
+ * Silent when it answers (pre-filtered, as `tools/list` is); a source that throws is one audited
121
+ * `failed` under the method's own name, there being no URI to file it under.
122
+ */
123
+ export async function resourcesList(
124
+ on: ResourceReadDeps,
125
+ req: JsonRpcRequest,
126
+ caller: McpCaller,
127
+ ): Promise<JsonRpcResponse> {
128
+ const id = req.id ?? null;
129
+ try {
130
+ return resultResponse(id, { resources: await on.resources.listFor(caller) });
131
+ } catch (error) {
132
+ return failed(on, id, 'resources/list', 'resources could not be listed', error, caller);
133
+ }
134
+ }
135
+
136
+ /** A provider's throw as `-32603`: a framework error keeps its code, cause and fix. */
137
+ function failed(
138
+ on: ResourceReadDeps,
139
+ id: JsonRpcId,
140
+ uri: string,
141
+ message: string,
142
+ error: unknown,
143
+ caller: McpCaller,
144
+ ): JsonRpcResponse {
145
+ const thrown = asFrameworkError(error);
146
+ if (thrown !== undefined) {
147
+ const framework = forAudience(thrown, on.audience);
148
+ on.audit.resourceRead({ uri, outcome: 'failed', caller, code: framework.code });
149
+ return errorResponse(id, INTERNAL_ERROR, message, {
150
+ code: framework.code,
151
+ cause: framework.cause,
152
+ fix: fixFor(framework, on.audience),
153
+ ...(framework.docs === undefined ? {} : { docs: framework.docs }),
154
+ });
121
155
  }
156
+ // No internals: a provider's own message names a path, a query or a host the caller has no
157
+ // business seeing, exactly as a failing tool's does.
158
+ on.audit.resourceRead({ uri, outcome: 'failed', caller });
159
+ return errorResponse(id, INTERNAL_ERROR, message);
122
160
  }
package/src/server.ts CHANGED
@@ -38,7 +38,7 @@ import type { McpPrompt, McpResource, McpResourceSource } from './resources';
38
38
  import { ResourceRegistry } from './resources';
39
39
  import type { CatalogRefused, CatalogView, McpCatalogSource, PerCall } from './server-catalog';
40
40
  import { catalogRefusal, viewOf } from './server-catalog';
41
- import { resourcesRead } from './server-resources';
41
+ import { resourcesList, resourcesRead } from './server-resources';
42
42
  import type { McpInstructions, McpServerVoice } from './server-voice';
43
43
  import { instructionsFor, invalidArgsResult, screenCatalogDetail } from './server-voice';
44
44
  import type { McpTenant } from './tenant';
@@ -108,7 +108,7 @@ export function mcpServer(input: McpServerInput = {}): McpServer {
108
108
  if (tenant !== undefined) assertTenant(tenant, input.tools ?? []);
109
109
  // `list_tenants` is a boot tool like any other, so every surface lists it and nothing shadows it.
110
110
  const all = [...(input.tools ?? []), ...(tenant === undefined ? [] : [listTenantsTool(tenant)])];
111
- const tools = new ToolRegistry().registerAll(all);
111
+ const tools = new ToolRegistry(tenant?.arg).registerAll(all);
112
112
  const resources = new ResourceRegistry().registerAll(input.resources ?? []);
113
113
  for (const source of input.resourceSources ?? []) resources.addSource(source);
114
114
  const meta = MetaSurface.build({
@@ -252,14 +252,16 @@ export class McpServer {
252
252
  case 'tools/call':
253
253
  return this.toolsCall(body, caller, signal);
254
254
  case 'resources/list':
255
- return resultResponse(id, { resources: await this.resources.listFor(caller) });
256
- case 'resources/read':
257
- return resourcesRead(
258
- { resources: this.resources, audit: this.audit, audience: this.voice.errorAudience },
259
- body,
260
- caller,
261
- era,
262
- );
255
+ case 'resources/read': {
256
+ const on = {
257
+ resources: this.resources,
258
+ audit: this.audit,
259
+ audience: this.voice.errorAudience,
260
+ };
261
+ return body.method === 'resources/list'
262
+ ? resourcesList(on, body, caller)
263
+ : resourcesRead(on, body, caller, era);
264
+ }
263
265
  // MCP's keep-alive: an empty result, which clients treat as "still here".
264
266
  case 'ping':
265
267
  return resultResponse(id, {});