@ultimat3/mcp 31.14.0 → 31.15.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 CHANGED
@@ -30,7 +30,8 @@ import. The CLI wires it.
30
30
  | `confirmations.ts` · `confirmation-*.ts` | `mcpConfirmations`: a factory over `action` (view/decide) · the gate on `handle` · stores · DDL · codes. `confirmation-installed.ts` is the `mcpConfirmationStore` slot a declaration with no `store` reads; `adapter.ts` (`./adapter`) its interface, error and installer |
31
31
  | `oauth-metadata.ts` | RFC 9728 protected-resource metadata + the 401 `resource_metadata` challenge (`defineAppMcp({ oauth })`) |
32
32
  | `oauth-server.ts` | `mcpAuthorizationServer`: `@ultimat3/auth`'s `authorizationServer` bound to one endpoint's `resource` (default and required by `resolveToken`), its `oauth` block, `mcp.auth.<event>` lines. No protocol rule lives here |
33
- | `transport-stdio.ts` | NDJSON on stdin/stdout for `x mcp serve` |
33
+ | `transport-stdio.ts` | NDJSON on stdin/stdout for `x mcp serve`: ≤ 16 calls run, ≤ 64 queued; the reader keeps reading at the cap, so `notifications/cancelled` and `ping` are always heard |
34
+ | `stdio-lines.ts` | raw chunks → lines, the cap in bytes |
34
35
  | `app-tools.ts` | `defineAppMcp` — a generated app's own MCP surface, one call |
35
36
  | `runtime-*` · `*-catalog.ts` · `tenant.ts` | `catalog:` (`runtimeTool()`, checked, merged per request) · `tenant:` (`list_tenants`); codes in `catalog-errors.ts` |
36
37
  | `app-tool.ts` | the authored `tools: { name: {...} }` record → `ProjectablePrimitive` |
@@ -39,6 +40,7 @@ import. The CLI wires it.
39
40
  | `include-early.ts` | `assertIncludeCurrent`, the mount's after-scan check (`X_MCP_INCLUDE_EARLY`) — [history](../../docs/history/mcp.md) |
40
41
  | `scopes.ts` | the `scopes:` map — outcome 2's declaration surface and its three boot refusals |
41
42
  | `readonly-sql.ts` · `readonly-sql-calls.ts` | layer 3 of `db.query` — the single-read parse — and `db.migrate`'s branch check · the banned call families |
43
+ | `query-page.ts` | a list query tool's ONE bounded page, `_after` cursor |
42
44
  | `query-limits.ts` | layer 4 of `db.query` — the row, byte and timeout ceilings, and what truncation reports |
43
45
  | `meta-surface.ts` · `meta-catalog-render.ts` | `surface: 'meta'` catalog, `groups:` boot checks (dispatch: `server.ts`) · its text, `catalogDetail` |
44
46
  | `meta-split.ts` · `meta-split-call.ts` · `meta-host.ts` | `surface: 'meta-split'`: the three dispatchers, the effect boot check · their dispatch (wrong tool, preview, `confirmed_by_user`) · the server half both meta doors call |
@@ -245,17 +247,15 @@ import. The CLI wires it.
245
247
  - **`mcpConfirmations` also registers its gate by name** (`@ultimat3/ai`'s adapter reads it). Invalid
246
248
  args REFUSE (`X_INPUT_INVALID`), never `run()`: an action's parse drops unknown keys. First
247
249
  registered answers in-app; any server without its own asks it. Proof: `scripts/ai-tool-confirmation.test.ts`.
248
- - **`transport-stdio.ts`'s default `write` is AWAITED** — fd 1 is a pipe, and an unawaited
249
- `Bun.stdout.write` lost the tail of a 4 MB frame at exit. It is also the loop's only
250
- back-pressure; only a child-process test can see it.
251
- - **A schema property lands through `Object.defineProperty` too** — `@ultimat3/schema`'s
252
- `wire-schema.ts`, the twin of `validate-args.ts`'s `put` on the schema side. `out[key] = …` for
253
- a property named `__proto__` runs `Object.prototype`'s setter and re-prototypes the published
254
- `properties` record instead of adding a key, so a field the tool author declared vanishes from
255
- `tools/list` and from what the arg validator reads back.
250
+ - **`transport-stdio.ts`'s default `write` is AWAITED** — fd 1 is a pipe; unawaited, a 4 MB
251
+ frame lost its tail at exit. Full rule: `docs/history/mcp.md`.
252
+ - **A schema property lands through `Object.defineProperty` too** (`wire-schema.ts`, the twin of
253
+ `validate-args.ts`'s `put`): a `__proto__` field never vanishes. Full rule: `docs/history/mcp.md`.
256
254
  - `transport-stdio.ts` never writes stdout except the wire (diagnostics → stderr) and caps one
257
- message at `DEFAULT_STDIO_LINE_LIMIT` (1 MiB): one `-32600` frame, the rest of that line discarded.
255
+ message at `DEFAULT_STDIO_LINE_LIMIT` (1 MiB, bytes): one `-32600` frame, the rest of that line discarded.
258
256
  Full rule: `docs/history/mcp.md`.
257
+ - **`mcpOAuthClient().begin` refuses an endpoint that is not `https:`** (loopback `http:` aside,
258
+ RFC 8252): the authorize URL is rendered as a link, so `javascript:` would run in the app's origin.
259
259
  - New mutating tool ⇒ set `destructive: true`, or it is metered as cheap read chatter.
260
260
  - **Invalid arguments are an `isError` RESULT (`X_INPUT_INVALID`), `As of 22.10`** — clients hide a
261
261
  `-32602` from the model. Audit outcome stays `invalid-args`. `-32602` only for a call that is not
package/README.md CHANGED
@@ -437,6 +437,8 @@ defineAppMcp({
437
437
  | `outputSchema` | an action's `output` with an object root; a query's `rows` as `{ rows: [<row>] }`, or as the row itself for a `single: true` read (which answers one row or `X_NOT_FOUND`, as its route does) — `toWireOutputSchema` (from `@ultimat3/schema`) / `toRowsOutputSchema`, structure only (no bounds, patterns or `additionalProperties`: a client refuses a result that misses its schema) | none |
438
438
  | `structuredContent` | `structuredResult(value, wrap?)`: the serialized answer read back, beside the text block — a list query's rows under `rows`, a `single: true` query's row unwrapped | absent |
439
439
 
440
+ **A list query answers one bounded page** (`As of 31.7`): its own `.page()`, at most `MAX_WIRE_PAGE_SIZE` (500) rows — fewer under a declared `maxPage` — and 256 KiB of JSON (`QUERY_LIMITS.maxBytes`). A cut answer adds `{ truncated: true, truncatedBy: 'rows' \| 'bytes', nextCursor? }` to `structuredContent` and as a second text block; the agent passes `nextCursor` back as the tool's `_after` argument. An answer that fits is the bare rows, unchanged. A read whose rows carry no `id` is read whole and cut, with no cursor.
441
+
440
442
  A tool's text is **compact JSON** (`jsonResult`; the 2-space form until 22.10). The meta tools
441
443
  carry their own hints: `list_resources` and `describe_resource` read-only, `manage_resource` a
442
444
  write; on `'meta-split'`, `read_resource` read-only and the other two destructive.
@@ -461,6 +463,8 @@ keeps `fix`. An error whose `docs` is not the framework's one Error-Codes page
461
463
  | HTTP | `mcpHttpRoute({ server, resolveToken })` → `POST /mcp` — `resolveToken(token, facts)` | `Authorization: Bearer <token>` → `Actor { kind: 'agent' }` |
462
464
  | stdio | `serveStdio({ server, caller })` | none — the peer already owns the shell |
463
465
 
466
+ stdio dispatches each line without waiting for the last (at most 16 at once, then up to 64 more queue while the reader reads on; only a full queue stops it): a slow `tools/call` never holds a `ping`, and a `ping` never queues. `notifications/cancelled` aborts the named call's signal — `tool.handle(args, caller, signal)`, `ctx.signal` inside a projected primitive — and the cancelled call — running or still queued — writes no answer. `lineLimitBytes` counts bytes on the raw chunk (characters until 31.7).
467
+
464
468
  The HTTP transport exports a route *descriptor*, not a mounted handler: a host owns the lifecycle,
465
469
  and the descriptor stays drivable from a bare `Request` in a test. It carries
466
470
  `rateLimitClass(body)` because all MCP traffic is one URL — a per-route bucket would charge
@@ -548,7 +552,7 @@ handed on. What an action or query DID still reaches core's `auditSink` port (`s
548
552
  |---|---|---|
549
553
  | `tool-call` | every `tools/call` outcome (`ok`, `hidden`, `scope-denied`, `refused`, `policy-denied`, `invalid-args`, `unconfirmed`, `previewed`, `failed`) — `refused` (at `warn`) is the pre-dispatch one: a `tenant:` server's call that named no tenant (`X_MCP_TENANT_REQUIRED`), answered before any tool ran. A `tenant.resolve` that throws or answers a non-agent is `X_MCP_TENANT_UNRESOLVED`, and lands in `failed` | `tool`, `outcome`, `caller`, `scope?`, `code?` |
550
554
  | `resource-read` | every `resources/read` outcome | `uri`, `outcome`, `caller`, `scope?`, `code?` |
551
- | `auth-refused` | a missing or rejected token, a non-agent actor, an address past its failure allowance, a cross-origin `Origin` (`origin-refused`, before the token is read) — also logged `mcp.auth.<reason>` at `warn` | `reason`, `status` (401/403/429), `facts` |
555
+ | `auth-refused` | a missing or rejected token, a non-agent actor, an address past its failure allowance, a cross-origin `Origin` (`origin-refused`, before the token is read) — also logged `mcp.auth.<reason>` at `warn`, except `missing-token` at `info` (OAuth discovery opens with one), the line's `address` its network (an IPv6 /64, `addressNetwork`), the event's `facts` the full one | `reason`, `status` (401/403/429), `facts` |
552
556
 
553
557
  Every event has `at` from the server's `clock`. Never the token, never the arguments. The hook is
554
558
  not awaited and cannot change an answer: one that throws or rejects is logged once as
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/mcp",
3
- "version": "31.14.0",
3
+ "version": "31.15.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.14.0",
48
- "@ultimat3/auth": "31.14.0",
49
- "@ultimat3/core": "31.14.0",
50
- "@ultimat3/db": "31.14.0",
51
- "@ultimat3/entity": "31.14.0",
52
- "@ultimat3/http": "31.14.0",
53
- "@ultimat3/jobs": "31.14.0",
54
- "@ultimat3/policy": "31.14.0",
55
- "@ultimat3/query": "31.14.0",
56
- "@ultimat3/schema": "31.14.0"
47
+ "@ultimat3/action": "31.15.0",
48
+ "@ultimat3/auth": "31.15.0",
49
+ "@ultimat3/core": "31.15.0",
50
+ "@ultimat3/db": "31.15.0",
51
+ "@ultimat3/entity": "31.15.0",
52
+ "@ultimat3/http": "31.15.0",
53
+ "@ultimat3/jobs": "31.15.0",
54
+ "@ultimat3/policy": "31.15.0",
55
+ "@ultimat3/query": "31.15.0",
56
+ "@ultimat3/schema": "31.15.0"
57
57
  }
58
58
  }
package/src/audit-hook.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  // carry those — there is no `ctx`, often no primitive, and nothing ran.
6
6
 
7
7
  import type { Clock, Logger } from '@ultimat3/core';
8
- import { logger, stringField, systemClock } from '@ultimat3/core';
8
+ import { addressNetwork, logger, stringField, systemClock } from '@ultimat3/core';
9
9
  import type { RequestFacts as McpRequestFacts } from '@ultimat3/http';
10
10
  import type { McpAuditEntry, McpResourceAuditEntry } from './audit';
11
11
  import { auditResourceRead, auditToolCall } from './audit';
@@ -69,15 +69,20 @@ export function mcpAuditor(input: McpAuditorInput = {}): McpAuditor {
69
69
  },
70
70
  authRefused(reason, status, facts) {
71
71
  // `warn`, the level of every refusal a prober can drive: a token walk is the same shape as a
72
- // tool-name walk one step earlier. The address and path carry the decision; the user agent
73
- // and origin stay in the event only — caller-controlled text an alert rule has no use for.
74
- log.warn(`mcp.auth.${reason}`, {
72
+ // tool-name walk one step earlier. Except `missing-token`, at `info`: MCP's own OAuth
73
+ // discovery opens unauthenticated, so EVERY legitimate client's first connect lands there.
74
+ // The address is its NETWORK (core's `addressNetwork`, an IPv6 /64 — the failure meter's key),
75
+ // never the full address; the hook's `facts` keep the host's answer. The user agent and origin
76
+ // stay in the event only — caller-controlled text an alert rule has no use for.
77
+ const line = {
75
78
  surface: 'mcp',
76
79
  reason,
77
80
  status,
78
81
  path: facts.path,
79
- ...(facts.address === null ? {} : { address: facts.address }),
80
- });
82
+ ...(facts.address === null ? {} : { address: addressNetwork(facts.address) }),
83
+ };
84
+ if (reason === 'missing-token') log.info(`mcp.auth.${reason}`, line);
85
+ else log.warn(`mcp.auth.${reason}`, line);
81
86
  if (hook !== undefined) {
82
87
  deliver(hook, { kind: 'auth-refused', at: clock.now(), reason, status, facts }, log);
83
88
  }
@@ -54,9 +54,9 @@ function registeredGate(tool: AnyMcpTool): AnyMcpTool {
54
54
  ...tool,
55
55
  // The catalog's label reads what is declared by now; the refusal below reads the call's truth.
56
56
  ...(toolGateFor(tool.name) === undefined ? {} : { confirms: true }),
57
- async handle(args: ToolArgs, caller: McpCaller): Promise<McpToolResult> {
57
+ async handle(args: ToolArgs, caller: McpCaller, signal?: AbortSignal): Promise<McpToolResult> {
58
58
  const toolGate = toolGateFor(tool.name);
59
- if (toolGate === undefined) return tool.handle(args, caller);
59
+ if (toolGate === undefined) return tool.handle(args, caller, signal);
60
60
  tool.admit?.(caller);
61
61
  const call = {
62
62
  tool: tool.name,
@@ -65,7 +65,7 @@ function registeredGate(tool: AnyMcpTool): AnyMcpTool {
65
65
  actor: caller.actor,
66
66
  };
67
67
  // What a gate answers is what `run` answered, or it threw: this `run` answers a tool result.
68
- return (await toolGate(call, async () => tool.handle(args, caller))) as McpToolResult;
68
+ return (await toolGate(call, async () => tool.handle(args, caller, signal))) as McpToolResult;
69
69
  },
70
70
  };
71
71
  }
@@ -98,14 +98,14 @@ function gate(tool: AnyMcpTool, confirmations: McpConfirmations): AnyMcpTool {
98
98
  return {
99
99
  ...tool,
100
100
  confirms: true,
101
- async handle(args: ToolArgs, caller: McpCaller): Promise<McpToolResult> {
101
+ async handle(args: ToolArgs, caller: McpCaller, signal?: AbortSignal): Promise<McpToolResult> {
102
102
  // Caller-only half of the policy first: one who may never call this opens no row for a person
103
103
  // to look at. Throws the same denial `handle` would, rendered by the server.
104
104
  tool.admit?.(caller);
105
105
  return confirmedCall(
106
106
  confirmations,
107
107
  { tool: tool.name, args, actor: caller.actor },
108
- async () => tool.handle(args, caller),
108
+ async () => tool.handle(args, caller, signal),
109
109
  );
110
110
  },
111
111
  };
@@ -13,7 +13,7 @@ import './errors';
13
13
  * below is not `X_RATE_LIMITED`: `@ultimat3/http`'s `X_BODY_INVALID` names `bodyLimitBytes` on the
14
14
  * HTTP pipeline, and this route never passes through it — the knob is `mcpHttpRoute`'s (or
15
15
  * `defineAppMcp`'s, which forwards it), and over stdio it is `serveStdio({ lineLimitBytes })`, a
16
- * ceiling in characters rather than bytes. One class for both transports, because the condition is
16
+ * ceiling in bytes of one line (in characters until 31.7). One class for both transports, because the condition is
17
17
  * one: the peer sent more in one message than this end agreed to hold, and the two answers must
18
18
  * name the same code so an agent learns it once.
19
19
  *
@@ -38,7 +38,7 @@ export class McpBodyTooLargeError extends UltimateError {
38
38
  code: 'X_MCP_BODY_TOO_LARGE',
39
39
  cause: http
40
40
  ? `request body is at least ${input.over ?? input.limit} bytes, limit is ${input.limit}`
41
- : `one message exceeded ${input.limit} characters and was dropped`,
41
+ : `one message exceeded ${input.limit} bytes and was dropped`,
42
42
  fix: http
43
43
  ? `send less in one request — page a large read, split a long prompt across calls — or raise the cap where the route is built: mcpHttpRoute({ bodyLimitBytes: ${raised} }) or defineAppMcp({ bodyLimitBytes: ${raised} })`
44
44
  : `send one JSON-RPC message per line, each under the cap — split a large tool result into paged calls — or raise it where the transport is started: serveStdio({ lineLimitBytes: ${raised} })`,
@@ -20,10 +20,18 @@
20
20
  // import this one to return it. `cross-surface.test.ts` pins `toolFrom` to the served entry.
21
21
 
22
22
  import type { Actor, McpExposureDeclaration } from '@ultimat3/core';
23
- import { isMcpExposed, toolDescription } from '@ultimat3/core';
23
+ import {
24
+ ctxOf,
25
+ hasContext,
26
+ isMcpExposed,
27
+ runWithContext,
28
+ toolDescription,
29
+ withChildContext,
30
+ } from '@ultimat3/core';
24
31
  import { McpToolUndeclaredError } from './errors';
25
32
  import type { ListedPrimitive } from './projectable';
26
33
  import { asProjectable } from './projectable';
34
+ import { pageFactsOf, truncatedResult } from './query-page';
27
35
  import type {
28
36
  AnyMcpTool,
29
37
  McpCaller,
@@ -117,16 +125,31 @@ export function toolFrom(listed: ListedPrimitive): AnyMcpTool {
117
125
  ? {}
118
126
  : { admit: (caller: McpCaller) => primitive.admit?.(caller.actor) }),
119
127
  // No `scope` from here: see the header. `defineAppMcp`'s `scopes:` map may add one.
120
- async handle(args: ToolArgs, caller: McpCaller): Promise<McpToolResult> {
128
+ async handle(args: ToolArgs, caller: McpCaller, signal?: AbortSignal): Promise<McpToolResult> {
121
129
  // ONE authz system, TWO surfaces. This `run` IS `invoke`; the HTTP route reaches the
122
130
  // same `invoke` with an actor of kind 'user', MCP arrives with kind 'agent'. Same
123
131
  // policy, same decision.
124
- const output = await primitive.run({ input: args, actor: caller.actor });
125
- return outputSchema === undefined ? jsonResult(output) : structuredResult(output, wrap);
132
+ const output = await withSignal(signal, () =>
133
+ primitive.run({ input: args, actor: caller.actor }),
134
+ );
135
+ const result =
136
+ outputSchema === undefined ? jsonResult(output) : structuredResult(output, wrap);
137
+ // A list query's page that was cut says so, and where the next one starts (`query-page.ts`).
138
+ const page = pageFactsOf(output);
139
+ return page === undefined ? result : truncatedResult(result, page);
126
140
  },
127
141
  };
128
142
  }
129
143
 
144
+ /**
145
+ * A cancelled call's signal as `ctx.signal` — what an action's handler, a query's driver and a
146
+ * `defineTool` body already read — composed with a request's own by core's child scope.
147
+ */
148
+ function withSignal<T>(signal: AbortSignal | undefined, fn: () => T): T {
149
+ if (signal === undefined) return fn();
150
+ return hasContext() ? withChildContext({ signal }, fn) : runWithContext(ctxOf({ signal }), fn);
151
+ }
152
+
130
153
  /**
131
154
  * The MCP hints a primitive's KIND already answers, with the author's `mcp.annotations` laid over
132
155
  * them key by key:
@@ -18,6 +18,7 @@ import { guardQueryBeforeInput, isQuery, queryName, readAnswer, sourceFor } from
18
18
  import { toWireOutputSchema, toWireSchema } from '@ultimat3/schema';
19
19
  import type { ProjectablePrimitive } from './from-action';
20
20
  import { takeIdempotencyKeyArg, withIdempotencyKeyArg } from './idempotency-arg';
21
+ import { pagedRows, takeAfterArg, withAfterArg } from './query-page';
21
22
  import type { JsonSchema } from './wire';
22
23
 
23
24
  /**
@@ -89,7 +90,8 @@ export function primitiveFromQuery(target: AnyQuery): ProjectablePrimitive {
89
90
  name,
90
91
  ...(exposure === undefined ? {} : { mcp: exposure }),
91
92
  ...(exposure?.description === undefined ? {} : { description: exposure.description }),
92
- inputJsonSchema: toWireSchema(target.input),
93
+ // A list read takes the cursor its truncated answer hands back (`query-page.ts`).
94
+ inputJsonSchema: single ? toWireSchema(target.input) : withAfterArg(toWireSchema(target.input)),
93
95
  ...(output === undefined
94
96
  ? {}
95
97
  : { outputJsonSchema: output, ...(single ? {} : { outputWrap: 'rows' }) }),
@@ -100,8 +102,14 @@ export function primitiveFromQuery(target: AnyQuery): ProjectablePrimitive {
100
102
  const ctx = useContext();
101
103
  guardQueryBeforeInput(target.policy, { actor: actorOf(ctx), ctx, query: name }, 'mcp');
102
104
  }),
103
- run: ({ input, actor }) =>
105
+ run: ({ input: args, actor }) =>
104
106
  asCallerContext(actor, async () => {
107
+ // A list read answers ONE bounded page through its own `.page()`, never every row.
108
+ if (!single) {
109
+ const { input, after } = takeAfterArg(args);
110
+ return pagedRows(target, input, after);
111
+ }
112
+ const input = args;
105
113
  // `sourceFor` is the authorized front half of `runQuery` — validate, guard, build —
106
114
  // and is what `live`, `paginate` and `explain` build on too. Executed without the
107
115
  // cache tiers on purpose: an agent diffing two tool calls must be reading the rows,
@@ -0,0 +1,167 @@
1
+ // What a projected LIST query answers an agent: one page through the read's own `.page()`, at most
2
+ // `MAX_WIRE_PAGE_SIZE` rows and `QUERY_LIMITS.maxBytes` of JSON — `db.query`'s ceilings — with
3
+ // `truncated` and a `nextCursor` the agent hands back as `_after`. A read with no `.limit()` dumped
4
+ // every row into a model's context; an answer that fits is still the bare rows it always was.
5
+
6
+ import { finiteCount, isUltimateError } from '@ultimat3/core';
7
+ import type { AnyQuery } from '@ultimat3/query';
8
+ import { MAX_WIRE_PAGE_SIZE, sourceFor } from '@ultimat3/query';
9
+ import { QUERY_LIMITS } from './query-limits';
10
+ import type { McpToolResult } from './registry';
11
+ import type { JsonSchema } from './wire';
12
+
13
+ /** The cursor argument — the wire's own `_after`, a name `query()` refuses as an input field. */
14
+ export const MCP_QUERY_AFTER_ARG = '_after';
15
+
16
+ /** Contract text, published in `tools/list` for every caller, like an action's `mcp.description`. */
17
+ const AFTER_SCHEMA: JsonSchema = {
18
+ type: 'string',
19
+ description: 'nextCursor of the previous answer, for the page after it; omit for the first page',
20
+ minLength: 1,
21
+ maxLength: 4096,
22
+ };
23
+
24
+ /** Why an answer is short: the row ceiling, the byte ceiling, or nothing. */
25
+ export type McpTruncation = 'rows' | 'bytes' | null;
26
+
27
+ /** Why a page was cut short, and where the next one starts. */
28
+ export interface PageFacts {
29
+ readonly truncatedBy: Exclude<McpTruncation, null>;
30
+ readonly nextCursor: string | null;
31
+ }
32
+
33
+ /**
34
+ * The facts of each truncated page, keyed by the rows array `run` returned. `run` stays what it
35
+ * always answered — rows — for every caller of the public `asProjectable`; only the tool result,
36
+ * built by `from-action.ts` from the same array, reads the facts back. Weak: a page forgets itself.
37
+ */
38
+ const truncatedPages = new WeakMap<readonly object[], PageFacts>();
39
+
40
+ /** The facts `pagedRows` recorded for this answer, or `undefined` for an answer that fits. */
41
+ export function pageFactsOf(output: unknown): PageFacts | undefined {
42
+ return Array.isArray(output) ? truncatedPages.get(output) : undefined;
43
+ }
44
+
45
+ function answered(
46
+ rows: readonly object[],
47
+ nextCursor: string | null,
48
+ truncatedBy: McpTruncation,
49
+ ): readonly object[] {
50
+ // A fresh array, so the facts never attach to a list some other code also holds.
51
+ const own = [...rows];
52
+ if (truncatedBy !== null) truncatedPages.set(own, { truncatedBy, nextCursor });
53
+ return own;
54
+ }
55
+
56
+ /** `schema` with the optional cursor; an input that is not an object has no argument to add. */
57
+ export function withAfterArg(schema: JsonSchema): JsonSchema {
58
+ if (schema.type !== 'object') return schema;
59
+ return {
60
+ ...schema,
61
+ properties: { ...(schema.properties ?? {}), [MCP_QUERY_AFTER_ARG]: AFTER_SCHEMA },
62
+ };
63
+ }
64
+
65
+ /** The call's arguments split into the read's input and the cursor. */
66
+ export function takeAfterArg(args: unknown): { readonly input: unknown; readonly after?: string } {
67
+ if (typeof args !== 'object' || args === null || !Object.hasOwn(args, MCP_QUERY_AFTER_ARG)) {
68
+ return { input: args };
69
+ }
70
+ const input: Record<string, unknown> = {};
71
+ let after: unknown;
72
+ for (const [field, value] of Object.entries(args)) {
73
+ if (field === MCP_QUERY_AFTER_ARG) after = value;
74
+ // defineProperty, never `input[field] =`: a `__proto__` field would re-prototype the copy.
75
+ else
76
+ Object.defineProperty(input, field, {
77
+ value,
78
+ writable: true,
79
+ enumerable: true,
80
+ configurable: true,
81
+ });
82
+ }
83
+ return typeof after === 'string' ? { input, after } : { input };
84
+ }
85
+
86
+ /**
87
+ * One page of `target`. A byte cut asks the read again for exactly the rows that fit, so the cursor
88
+ * resumes at the first row cut — never past it. A read whose rows carry no `id` cannot be paged
89
+ * (`X_QUERY_NOT_PAGEABLE`); it is read whole, as before, and cut here with no cursor to offer.
90
+ */
91
+ export async function pagedRows(
92
+ target: AnyQuery,
93
+ input: unknown,
94
+ after: string | undefined,
95
+ ): Promise<readonly object[]> {
96
+ const ceiling = finiteCount('query', 'maxPage', target.maxPage ?? MAX_WIRE_PAGE_SIZE, 1);
97
+ const first = Math.min(MAX_WIRE_PAGE_SIZE, ceiling);
98
+ const read = (size: number) =>
99
+ target.page(
100
+ input,
101
+ after === undefined
102
+ ? { first: size, surface: 'mcp' }
103
+ : { first: size, after, surface: 'mcp' },
104
+ );
105
+ let page: Awaited<ReturnType<typeof read>>;
106
+ try {
107
+ page = await read(first);
108
+ } catch (thrown) {
109
+ if (after !== undefined || !isUltimateError(thrown) || thrown.code !== 'X_QUERY_NOT_PAGEABLE') {
110
+ throw thrown;
111
+ }
112
+ const rows = await (await sourceFor(target, input, { surface: 'mcp' })).execute();
113
+ const kept = rows.slice(0, first);
114
+ const fit = rowsWithinBytes(kept);
115
+ return answered(
116
+ kept.slice(0, fit),
117
+ null,
118
+ fit < kept.length ? 'bytes' : rows.length > first ? 'rows' : null,
119
+ );
120
+ }
121
+ const fit = rowsWithinBytes(page.rows);
122
+ if (fit === page.rows.length)
123
+ return answered(page.rows, page.nextCursor, page.hasMore ? 'rows' : null);
124
+ // One row over the ceiling alone: nothing fits, and a cursor past it would hide it unseen.
125
+ if (fit === 0) return answered([], null, 'bytes');
126
+ const narrowed = await read(fit);
127
+ return answered(narrowed.rows, narrowed.nextCursor, 'bytes');
128
+ }
129
+
130
+ const encoder = new TextEncoder();
131
+
132
+ /** How many leading rows fit `QUERY_LIMITS.maxBytes` as JSON, `[`, `]` and separators counted. */
133
+ function rowsWithinBytes(rows: readonly object[]): number {
134
+ let bytes = 2;
135
+ for (const [index, row] of rows.entries()) {
136
+ let size = 0;
137
+ try {
138
+ size = encoder.encode(JSON.stringify(row)).length + 1;
139
+ } catch {
140
+ // Not JSON (a bigint): left to `jsonResult`'s own refusal, which names the problem.
141
+ }
142
+ if (bytes + size > QUERY_LIMITS.maxBytes) return index;
143
+ bytes += size;
144
+ }
145
+ return rows.length;
146
+ }
147
+
148
+ /**
149
+ * A truncated page's tool result: `base` — what the rows alone answered — plus a second text block
150
+ * and the same keys on `structuredContent`, `{ truncated: true, truncatedBy, nextCursor? }`, so
151
+ * both kinds of client learn it was cut. Not in the `outputSchema`: it allows extra keys, and every
152
+ * list read's `tools/list` entry would otherwise pay ~100 bytes for a rare answer.
153
+ */
154
+ export function truncatedResult(base: McpToolResult, facts: PageFacts): McpToolResult {
155
+ if (base.isError === true) return base;
156
+ const page = {
157
+ truncated: true,
158
+ truncatedBy: facts.truncatedBy,
159
+ ...(facts.nextCursor === null ? {} : { nextCursor: facts.nextCursor }),
160
+ };
161
+ return {
162
+ content: [...base.content, { type: 'text', text: JSON.stringify(page) }],
163
+ ...(base.structuredContent === undefined
164
+ ? {}
165
+ : { structuredContent: { ...base.structuredContent, ...page } }),
166
+ };
167
+ }
package/src/registry.ts CHANGED
@@ -169,7 +169,9 @@ export interface McpTool<A extends ToolArgs = ToolArgs> {
169
169
  */
170
170
  admit?(caller: McpCaller): void;
171
171
  // Method syntax (not a property) so a tool declared with narrower args stays assignable.
172
- handle(args: A, caller: McpCaller): Promise<McpToolResult>;
172
+ // `signal` aborts when the caller cancels the call (`notifications/cancelled` on stdio); absent
173
+ // where no transport can cancel. A projected primitive reads it as `ctx.signal`.
174
+ handle(args: A, caller: McpCaller, signal?: AbortSignal): Promise<McpToolResult>;
173
175
  }
174
176
 
175
177
  export type AnyMcpTool = McpTool<ToolArgs>;
@@ -144,22 +144,42 @@ export function mcpOAuthClient(options: McpOAuthClientOptions): McpOAuthClient {
144
144
  }),
145
145
 
146
146
  async begin(serverUrl) {
147
- const resource = new URL(serverUrl);
148
- resource.hash = '';
147
+ const resource = urlOf(serverUrl);
148
+ if (resource === null) throw refused(serverUrl, 'is not an absolute URL');
149
149
  const prm = await firstOf(serverUrl, wellKnown(resource, 'oauth-protected-resource'));
150
+ // RFC 9728 §3.3: metadata naming another resource is not this server's — a document copied
151
+ // from elsewhere would send the person's consent, and `resource`, to that server's issuer.
152
+ // Absent is tolerated (a lax server), present must be this URL, compared parsed.
153
+ const named = prm['resource'];
154
+ if (named !== undefined && urlOf(named)?.toString() !== resource.toString()) {
155
+ throw refused(serverUrl, 'published resource metadata for another resource');
156
+ }
150
157
  const issuer = Array.isArray(prm['authorization_servers'])
151
158
  ? prm['authorization_servers'].find((entry) => typeof entry === 'string')
152
159
  : undefined;
153
160
  if (typeof issuer !== 'string') {
154
161
  throw refused(serverUrl, 'names no authorization server in its resource metadata');
155
162
  }
156
- const as = await firstOf(issuer, authServerCandidates(new URL(issuer)));
163
+ const issuerUrl = urlOf(issuer);
164
+ if (issuerUrl === null)
165
+ throw refused(serverUrl, 'names an authorization server that is no URL');
166
+ const as = await firstOf(issuer, authServerCandidates(issuerUrl));
157
167
  // RFC 8414 §3.3: a document answering for another issuer is not this issuer's.
158
168
  if (as['issuer'] !== issuer) throw refused(issuer, 'published metadata for another issuer');
159
169
  const authorize = as['authorization_endpoint'];
160
170
  const tokenEndpoint = as['token_endpoint'];
161
- if (typeof authorize !== 'string' || typeof tokenEndpoint !== 'string') {
162
- throw refused(issuer, 'names no authorization_endpoint or token_endpoint');
171
+ const url = urlOf(authorize);
172
+ const tokenUrl = urlOf(tokenEndpoint);
173
+ if (url === null || tokenUrl === null || typeof tokenEndpoint !== 'string') {
174
+ throw refused(issuer, 'names no authorization_endpoint or token_endpoint URL');
175
+ }
176
+ // The authorize URL is handed to a person as a link: `javascript:`/`data:` would run in the
177
+ // app's origin, and plain `http:` would carry the code over the wire in the clear.
178
+ if (!secureEndpoint(url) || !secureEndpoint(tokenUrl)) {
179
+ throw refused(
180
+ issuer,
181
+ 'names an authorization_endpoint or token_endpoint that is not https:',
182
+ );
163
183
  }
164
184
  const methods = as['code_challenge_methods_supported'];
165
185
  if (!Array.isArray(methods) || !methods.includes('S256')) {
@@ -173,7 +193,6 @@ export function mcpOAuthClient(options: McpOAuthClientOptions): McpOAuthClient {
173
193
  }
174
194
  const pkce = pkcePair();
175
195
  const state = randomToken(16);
176
- const url = new URL(authorize);
177
196
  const scopes = options.scopes ?? stringList(prm['scopes_supported']);
178
197
  url.searchParams.set('response_type', 'code');
179
198
  url.searchParams.set('client_id', options.clientId);
@@ -226,6 +245,22 @@ export function mcpOAuthClient(options: McpOAuthClientOptions): McpOAuthClient {
226
245
  };
227
246
  }
228
247
 
248
+ /** A remote's metadata is input: `URL.parse`, never `new URL`, whose TypeError escapes uncoded. */
249
+ function urlOf(value: unknown): URL | null {
250
+ if (typeof value !== 'string') return null;
251
+ const url = URL.parse(value);
252
+ if (url !== null) url.hash = '';
253
+ return url;
254
+ }
255
+
256
+ /** Loopback, the only host OAuth 2.1 (and RFC 8252 §8.3) lets an endpoint use plain `http:` on. */
257
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);
258
+
259
+ /** `https:`, or `http:` to this machine — never `javascript:`, `data:`, `file:` or a cleartext hop. */
260
+ function secureEndpoint(url: URL): boolean {
261
+ return url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK.has(url.hostname));
262
+ }
263
+
229
264
  /** RFC 9728 §3.1: the suffix goes between host and path, then the root as a fallback. */
230
265
  function wellKnown(url: URL, suffix: string): readonly string[] {
231
266
  const path = url.pathname === '/' ? '' : url.pathname.replace(/\/+$/, '');
package/src/server.ts CHANGED
@@ -173,10 +173,12 @@ export class McpServer {
173
173
  this.audit = audit;
174
174
  }
175
175
 
176
+ /** `signal` reaches the tool's `handle` — a transport that hears `notifications/cancelled` aborts it. */
176
177
  async handle(
177
178
  body: unknown,
178
179
  caller: McpCaller,
179
180
  wire?: McpWire | undefined,
181
+ signal?: AbortSignal,
180
182
  ): Promise<JsonRpcResponse | null> {
181
183
  // A batch is legal JSON-RPC 2.0 and this server does not walk one: one call, one answer, one
182
184
  // rate-limit class. Refused BY NAME rather than falling through to the envelope check below —
@@ -209,7 +211,7 @@ export class McpServer {
209
211
  const era = eraOf(body);
210
212
  if (typeof era !== 'string') return unsupportedVersion(id, era.unsupported);
211
213
  const answer = METHODS[era].includes(body.method)
212
- ? await this.answer(id, body, caller, era)
214
+ ? await this.answer(id, body, caller, era, signal)
213
215
  : undefined;
214
216
  if (answer === undefined) {
215
217
  return errorResponse(id, METHOD_NOT_FOUND, `method not found: ${body.method}`, {
@@ -225,6 +227,7 @@ export class McpServer {
225
227
  body: JsonRpcRequest,
226
228
  caller: McpCaller,
227
229
  era: McpEra,
230
+ signal: AbortSignal | undefined,
228
231
  ): Promise<JsonRpcResponse | undefined> {
229
232
  switch (body.method) {
230
233
  case 'initialize':
@@ -247,7 +250,7 @@ export class McpServer {
247
250
  return resultResponse(id, { tools: this.listIn(view, caller) });
248
251
  }
249
252
  case 'tools/call':
250
- return this.toolsCall(body, caller);
253
+ return this.toolsCall(body, caller, signal);
251
254
  case 'resources/list':
252
255
  return resultResponse(id, { resources: await this.resources.listFor(caller) });
253
256
  case 'resources/read':
@@ -320,7 +323,11 @@ export class McpServer {
320
323
  return classifyBody(body, this.meta, this.tools);
321
324
  }
322
325
 
323
- private async toolsCall(req: JsonRpcRequest, caller: McpCaller): Promise<JsonRpcResponse> {
326
+ private async toolsCall(
327
+ req: JsonRpcRequest,
328
+ caller: McpCaller,
329
+ signal: AbortSignal | undefined,
330
+ ): Promise<JsonRpcResponse> {
324
331
  const id = req.id ?? null;
325
332
  const params = paramsOf(req);
326
333
  if (params === null) return errorResponse(id, INVALID_PARAMS, 'tools/call requires params');
@@ -361,7 +368,7 @@ export class McpServer {
361
368
  tools: view.tools,
362
369
  audit: this.audit,
363
370
  catalogDetail: this.voice.catalogDetail ?? 'full',
364
- dispatch: (at, tool, resolved, who) => this.dispatch(at, tool, resolved, who),
371
+ dispatch: (at, tool, resolved, who) => this.dispatch(at, tool, resolved, who, signal),
365
372
  notFound: (at, tool, who, fix) => this.notFound(at, tool, who, fix),
366
373
  refuse: (at, tool, error, who) =>
367
374
  thrownResponse(at, tool, error, who, this.voice.errorAudience, this.audit),
@@ -371,7 +378,7 @@ export class McpServer {
371
378
  );
372
379
  if (answered !== undefined) return answered;
373
380
  }
374
- return this.dispatch(id, name, view.tools.resolve(name, rawArgs ?? {}, who), who);
381
+ return this.dispatch(id, name, view.tools.resolve(name, rawArgs ?? {}, who), who, signal);
375
382
  }
376
383
 
377
384
  /** OUTCOME 1, the one answer for absent and hidden alike. See `dispatch`. */
@@ -389,6 +396,7 @@ export class McpServer {
389
396
  name: string,
390
397
  resolved: ToolResolution,
391
398
  caller: McpCaller,
399
+ signal?: AbortSignal,
392
400
  ): Promise<JsonRpcResponse> {
393
401
  const audience = this.voice.errorAudience;
394
402
  // Three outcomes, deliberately different — and every one of them audited, including the
@@ -441,7 +449,7 @@ export class McpServer {
441
449
 
442
450
  let result: McpToolResult;
443
451
  try {
444
- result = await resolved.tool.handle(resolved.args, caller);
452
+ result = await resolved.tool.handle(resolved.args, caller, signal);
445
453
  } catch (error) {
446
454
  return thrownResponse(id, name, error, caller, audience, this.audit);
447
455
  }
@@ -0,0 +1,80 @@
1
+ // Raw stdin chunks → newline-delimited frames, the line cap measured in BYTES before anything is
2
+ // decoded. A `string.length` cap counted UTF-16 units: a 1 MiB cap admitted ~3 MiB of CJK.
3
+ // Splitting on 0x0A is safe on the raw bytes — UTF-8 never uses that byte inside a character.
4
+
5
+ /** One unit of the wire: a complete line's text, or a line refused for its size. */
6
+ export type StdioFrame =
7
+ | { readonly kind: 'line'; readonly text: string }
8
+ | { readonly kind: 'over-limit' };
9
+
10
+ export interface LineSplitter {
11
+ /** The frames this chunk completes, in wire order. */
12
+ push(chunk: Uint8Array): readonly StdioFrame[];
13
+ /** The trailing message with no newline — still a message, unless it is a dropped tail. */
14
+ end(): readonly StdioFrame[];
15
+ }
16
+
17
+ const NEWLINE = 0x0a;
18
+ const OVER: StdioFrame = { kind: 'over-limit' };
19
+
20
+ export function lineSplitter(limit: number): LineSplitter {
21
+ const decoder = new TextDecoder();
22
+ let pending: Uint8Array[] = [];
23
+ let pendingBytes = 0;
24
+ // The rest of an over-long message is dropped, never parsed: whatever follows it on the same
25
+ // line is the tail of a message this transport refused, not a message of its own.
26
+ let discarding = false;
27
+
28
+ const take = (last: Uint8Array): string => {
29
+ const whole = new Uint8Array(pendingBytes + last.length);
30
+ let at = 0;
31
+ for (const part of pending) {
32
+ whole.set(part, at);
33
+ at += part.length;
34
+ }
35
+ whole.set(last, at);
36
+ pending = [];
37
+ pendingBytes = 0;
38
+ return decoder.decode(whole);
39
+ };
40
+
41
+ return {
42
+ push(chunk) {
43
+ const frames: StdioFrame[] = [];
44
+ let start = 0;
45
+ while (start <= chunk.length) {
46
+ const newline = chunk.indexOf(NEWLINE, start);
47
+ const segment = chunk.subarray(start, newline === -1 ? chunk.length : newline);
48
+ if (newline === -1) {
49
+ if (!discarding && segment.length > 0) {
50
+ // Judged while buffering, so a stream with no newline never grows past the cap.
51
+ if (pendingBytes + segment.length > limit) {
52
+ frames.push(OVER);
53
+ pending = [];
54
+ pendingBytes = 0;
55
+ discarding = true;
56
+ } else {
57
+ // A copy: the stream may hand the same buffer back refilled.
58
+ pending.push(segment.slice());
59
+ pendingBytes += segment.length;
60
+ }
61
+ }
62
+ break;
63
+ }
64
+ if (discarding) discarding = false;
65
+ // Judged before the decode and the parse: a line over the cap costs neither.
66
+ else if (pendingBytes + segment.length > limit) {
67
+ frames.push(OVER);
68
+ pending = [];
69
+ pendingBytes = 0;
70
+ } else frames.push({ kind: 'line', text: take(segment) });
71
+ start = newline + 1;
72
+ }
73
+ return frames;
74
+ },
75
+ end() {
76
+ if (discarding || pendingBytes === 0) return [];
77
+ return [{ kind: 'line', text: take(new Uint8Array(0)) }];
78
+ },
79
+ };
80
+ }
@@ -3,7 +3,7 @@
3
3
  // JSON-RPC envelope — nothing was called. Split from `transport-http.ts`, which keeps the order.
4
4
 
5
5
  import type { Clock, UltimateError } from '@ultimat3/core';
6
- import { proveSameOrigin } from '@ultimat3/core';
6
+ import { addressNetwork, proveSameOrigin } from '@ultimat3/core';
7
7
  import type { Bucket, RateLimitStore } from '@ultimat3/http';
8
8
  import {
9
9
  McpHostRefusedError,
@@ -47,7 +47,9 @@ export function throttled(verbClass: string, limit: number, retryAfterSeconds: n
47
47
  * failure and answers the 429 when that one did not fit. `undefined` from either: carry on.
48
48
  */
49
49
  export function failureMeter(store: RateLimitStore, bucket: Bucket, clock: Clock) {
50
- const keyOf = (address: string): string => `mcp:unauthenticated|ip:${address}`;
50
+ // The NETWORK, as `@ultimat3/http`'s limiter keys it: one IPv6 host holds a /64, and keying the full
51
+ // address handed it ~2^64 allowances of guesses.
52
+ const keyOf = (address: string): string => `mcp:unauthenticated|ip:${addressNetwork(address)}`;
51
53
  const refused = (retryAfterSeconds: number): Response =>
52
54
  throttled('unauthenticated', bucket.capacity, retryAfterSeconds);
53
55
  return {
@@ -12,18 +12,40 @@ import { finiteCount } from '@ultimat3/core';
12
12
  import { McpBodyTooLargeError } from './errors-transport';
13
13
  import type { McpCaller } from './registry';
14
14
  import type { McpServer } from './server';
15
- import { errorResponse, INVALID_REQUEST, PARSE_ERROR, refusalMessage } from './wire';
15
+ import type { StdioFrame } from './stdio-lines';
16
+ import { lineSplitter } from './stdio-lines';
17
+ import type { JsonRpcId, JsonRpcRequest } from './wire';
18
+ import {
19
+ errorResponse,
20
+ INVALID_REQUEST,
21
+ isJsonRpcRequest,
22
+ isNotification,
23
+ PARSE_ERROR,
24
+ paramsOf,
25
+ refusalMessage,
26
+ } from './wire';
16
27
 
17
28
  /**
18
- * Characters held for ONE message that has not ended yet. `transport-http.ts` caps the same wire at
29
+ * BYTES held for ONE message that has not ended yet. `transport-http.ts` caps the same wire at
19
30
  * 1 MiB with `readWithinLimit`, and two transports must not answer one question two ways: the peer
20
31
  * launched this process and is trusted, but a bug in it is not — a stream with no newline in it
21
32
  * grew this buffer until the process died, with no frame written for the request already in flight.
22
- * Characters rather than bytes because characters are what is retained here; one is never less than
23
- * one byte on the wire, so the cap bounds both.
33
+ * Counted on the raw chunk before decoding (`stdio-lines.ts`): characters let 3 MiB of CJK past.
24
34
  */
25
35
  export const DEFAULT_STDIO_LINE_LIMIT = 1_048_576;
26
36
 
37
+ /**
38
+ * Requests answered at once. Each line is dispatched without waiting for the one before it — a slow
39
+ * `tools/call` held every later frame, `ping` included. Past this many a request waits in a queue
40
+ * of `STDIO_MAX_QUEUED` while the reader goes on reading — a `notifications/cancelled` or a `ping`
41
+ * for the calls holding the slots is still heard — and only a FULL queue stops the reader: the
42
+ * pipe's own back-pressure, never an unbounded fan-out.
43
+ */
44
+ export const STDIO_MAX_IN_FLIGHT = 16;
45
+
46
+ /** Requests read and waiting for a slot. A full queue parks the reader until one starts. */
47
+ export const STDIO_MAX_QUEUED = 64;
48
+
27
49
  export interface StdioTransportInput {
28
50
  readonly server: McpServer;
29
51
  /** The local developer, already resolved by the CLI. Usually `kind: 'agent'`. */
@@ -32,65 +54,140 @@ export interface StdioTransportInput {
32
54
  readonly input?: ReadableStream<Uint8Array>;
33
55
  /** Defaults to writing `Bun.stdout`. */
34
56
  write?(chunk: string): Promise<void> | void;
35
- /** Characters buffered for one unterminated message. Defaults to `DEFAULT_STDIO_LINE_LIMIT`. */
57
+ /** Bytes buffered for one unterminated message. Defaults to `DEFAULT_STDIO_LINE_LIMIT`. */
36
58
  readonly lineLimitBytes?: number | undefined;
37
59
  }
38
60
 
39
61
  /**
40
- * Serve until stdin closes. Resolves when the peer disconnects, which is the CLI's signal
41
- * to exit 0 — a closed pipe is a normal shutdown, not an error.
62
+ * Serve until stdin closes and every call in flight has answered. Resolves when the peer
63
+ * disconnects, which is the CLI's signal to exit 0 — a closed pipe is a normal shutdown.
42
64
  */
43
65
  export async function serveStdio(config: StdioTransportInput): Promise<void> {
44
66
  const stream = config.input ?? Bun.stdin.stream();
45
67
  const write = config.write ?? defaultWrite;
46
- // Before a byte of stdin is read, because `line.length > NaN` is false for EVERY line: the cap
47
- // would not be a large one, it would be absent, and the buffer it bounds grows until the process
48
- // dies. `??` cannot screen it — `NaN` is not nullish. Floor of 1: a cap of 0 refuses every
49
- // message there is, which is a dead transport rather than a bound.
68
+ // Before a byte of stdin is read, because `bytes > NaN` is false for EVERY line: the cap would
69
+ // not be a large one, it would be absent, and the buffer it bounds grows until the process dies.
70
+ // `??` cannot screen it — `NaN` is not nullish. Floor of 1: a cap of 0 refuses every message
71
+ // there is, which is a dead transport rather than a bound.
50
72
  const limit = finiteCount(
51
73
  'serveStdio',
52
74
  'lineLimitBytes',
53
75
  config.lineLimitBytes ?? DEFAULT_STDIO_LINE_LIMIT,
54
76
  1,
55
77
  );
56
- const decoder = new TextDecoder();
57
- let buffer = '';
58
- // The rest of an over-long message is dropped, not parsed: whatever follows it on the same line
59
- // is the tail of a message this transport refused, never a message of its own.
60
- let discarding = false;
78
+ const lines = lineSplitter(limit);
79
+ const wire = stdioDispatch(config.server, config.caller, write);
61
80
 
62
81
  for await (const chunk of stream) {
63
- buffer += decoder.decode(chunk, { stream: true });
64
- if (discarding) {
65
- const end = buffer.indexOf('\n');
66
- if (end === -1) {
67
- buffer = '';
68
- continue;
69
- }
70
- buffer = buffer.slice(end + 1);
71
- discarding = false;
72
- }
73
- let newline = buffer.indexOf('\n');
74
- while (newline !== -1) {
75
- const line = buffer.slice(0, newline);
76
- buffer = buffer.slice(newline + 1);
77
- // Checked before the parse, never inside it: a line already over the cap costs a `JSON.parse`
78
- // over the whole of it, which is the work the cap exists to refuse.
79
- if (line.length > limit) await write(`${JSON.stringify(overLimit(limit))}\n`);
80
- else await handleLine(config.server, config.caller, line, write);
81
- newline = buffer.indexOf('\n');
82
- }
83
- if (buffer.length > limit) {
84
- await write(`${JSON.stringify(overLimit(limit))}\n`);
85
- buffer = '';
86
- discarding = true;
87
- }
88
- }
89
- // A trailing message with no newline is still a message — unless it is the tail being dropped.
90
- if (!discarding && buffer.trim().length > 0) {
91
- if (buffer.length > limit) await write(`${JSON.stringify(overLimit(limit))}\n`);
92
- else await handleLine(config.server, config.caller, buffer, write);
82
+ for (const frame of lines.push(chunk)) await wire.take(frame, limit);
83
+ wire.check();
93
84
  }
85
+ for (const frame of lines.end()) await wire.take(frame, limit);
86
+ await wire.drain();
87
+ }
88
+
89
+ /** Frames in, answers out: one task per request, one ordered writer, one abort per request id. */
90
+ function stdioDispatch(
91
+ server: McpServer,
92
+ caller: McpCaller,
93
+ write: (chunk: string) => Promise<void> | void,
94
+ ) {
95
+ const inFlight = new Set<Promise<void>>();
96
+ const cancels = new Map<string, AbortController>();
97
+ // Read, not started: a cancel takes one out before it ever runs.
98
+ const queued: JsonRpcRequest[] = [];
99
+ // Woken whenever a slot frees: the reader parked on a full queue, and `drain`.
100
+ let freed: () => void = () => undefined;
101
+ const slotFreed = (): Promise<void> =>
102
+ new Promise((resolve) => {
103
+ freed = resolve;
104
+ });
105
+ let failure: { readonly thrown: unknown } | undefined;
106
+ // Every frame goes through ONE chain, so two answers finishing together never interleave bytes.
107
+ let tail: Promise<void> = Promise.resolve();
108
+ const send = (frame: unknown): Promise<void> => {
109
+ tail = tail.then(() => write(`${JSON.stringify(frame)}\n`));
110
+ return tail;
111
+ };
112
+ const check = (): void => {
113
+ if (failure !== undefined) throw failure.thrown;
114
+ };
115
+
116
+ const run = (body: JsonRpcRequest): void => {
117
+ const key = body.id === undefined ? undefined : idKey(body.id);
118
+ const controller = new AbortController();
119
+ if (key !== undefined) cancels.set(key, controller);
120
+ const task = (async () => {
121
+ const response = await server.handle(body, caller, { transport: 'stdio' }, controller.signal);
122
+ // `null` is a notification: nothing at all, or the peer sees a phantom reply. A cancelled
123
+ // request gets no answer either — the spec's receiver rule; the peer has stopped waiting.
124
+ if (response === null || controller.signal.aborted) return;
125
+ await send(response);
126
+ })()
127
+ .catch((thrown: unknown) => {
128
+ failure ??= { thrown };
129
+ })
130
+ .finally(() => {
131
+ if (key !== undefined && cancels.get(key) === controller) cancels.delete(key);
132
+ inFlight.delete(task);
133
+ pump();
134
+ freed();
135
+ });
136
+ inFlight.add(task);
137
+ };
138
+ const pump = (): void => {
139
+ while (inFlight.size < STDIO_MAX_IN_FLIGHT && queued.length > 0) {
140
+ run(queued.shift() as JsonRpcRequest);
141
+ }
142
+ };
143
+
144
+ return {
145
+ check,
146
+ async take(frame: StdioFrame, limit: number): Promise<void> {
147
+ check();
148
+ if (frame.kind === 'over-limit') return send(overLimit(limit));
149
+ const trimmed = frame.text.trim();
150
+ if (trimmed.length === 0) return;
151
+ let body: unknown;
152
+ try {
153
+ body = JSON.parse(trimmed);
154
+ } catch {
155
+ return send(errorResponse(null, PARSE_ERROR, 'invalid JSON line'));
156
+ }
157
+ const cancelled = cancelledId(body);
158
+ if (cancelled !== undefined) {
159
+ const key = idKey(cancelled);
160
+ // Still queued: it never runs, and — cancelled — never answers.
161
+ const waiting = queued.findIndex((one) => one.id !== undefined && idKey(one.id) === key);
162
+ if (waiting >= 0) queued.splice(waiting, 1);
163
+ // The tool sees `signal.aborted`; its answer, if it still returns one, is dropped below.
164
+ cancels.get(key)?.abort();
165
+ return;
166
+ }
167
+ // A ping is the peer asking whether the wire is alive: answered at once, never queued.
168
+ if (isJsonRpcRequest(body) && body.method === 'ping') return run(body);
169
+ // The envelope check is the server's: a non-request is handed on and refused there.
170
+ queued.push(body as JsonRpcRequest);
171
+ pump();
172
+ while (queued.length >= STDIO_MAX_QUEUED) await slotFreed();
173
+ },
174
+ async drain(): Promise<void> {
175
+ while (inFlight.size > 0 || queued.length > 0) await slotFreed();
176
+ await tail;
177
+ check();
178
+ },
179
+ };
180
+ }
181
+
182
+ /** A string `"7"` and a number `7` are two ids by JSON-RPC, so they are two keys here. */
183
+ const idKey = (id: JsonRpcId): string => `${typeof id}:${String(id)}`;
184
+
185
+ /** The `requestId` a `notifications/cancelled` names, or `undefined` for any other message. */
186
+ function cancelledId(body: unknown): JsonRpcId | undefined {
187
+ if (!isJsonRpcRequest(body) || !isNotification(body)) return undefined;
188
+ if (body.method !== 'notifications/cancelled') return undefined;
189
+ const requestId = paramsOf(body)?.['requestId'];
190
+ return typeof requestId === 'string' || typeof requestId === 'number' ? requestId : undefined;
94
191
  }
95
192
 
96
193
  /**
@@ -111,29 +208,6 @@ function overLimit(limit: number): ReturnType<typeof errorResponse> {
111
208
  });
112
209
  }
113
210
 
114
- async function handleLine(
115
- server: McpServer,
116
- caller: McpCaller,
117
- line: string,
118
- write: (chunk: string) => Promise<void> | void,
119
- ): Promise<void> {
120
- const trimmed = line.trim();
121
- if (trimmed.length === 0) return;
122
-
123
- let body: unknown;
124
- try {
125
- body = JSON.parse(trimmed);
126
- } catch {
127
- await write(`${JSON.stringify(errorResponse(null, PARSE_ERROR, 'invalid JSON line'))}\n`);
128
- return;
129
- }
130
-
131
- const response = await server.handle(body, caller, { transport: 'stdio' });
132
- // `null` means notification: emit nothing at all, or the peer sees a phantom reply.
133
- if (response === null) return;
134
- await write(`${JSON.stringify(response)}\n`);
135
- }
136
-
137
211
  /**
138
212
  * `Bun.stdout.write` is ASYNCHRONOUS when fd 1 is a pipe — which it always is here, because the
139
213
  * peer LAUNCHED this process — and it answers the count it accepted, never the count it wrote.