Skip to content

feat(mcp): serve the MCP server over streamable HTTP - #4955

Merged
gensokyo-dev merged 43 commits into
morluto:mainfrom
earakely-scale:feat/mcp-streamable-http
Oct 19, 2026
Merged

gensokyo-dev merged 43 commits into
morluto:mainfrom
earakely-scale:feat/mcp-streamable-http

Conversation

@earakely-scale

@earakely-scale earakely-scale commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds rea mcp --http [--host <h>] [--port <n>] for gateway/environment hosts while keeping stdio as the default and registered transport. It serves the existing MCP catalog at /mcp, on loopback by default, with one shared active target and one client session at a time.

Direct follow-up commits remain on this original PR through ba73ccafd, with main 49b4edfe7 merged. The requesting human explicitly authorized the HTTP scope, initial readiness and merging; the original author's history and declarations remain.

Problem and expected behavior

A host that reaches MCP services over HTTP can use REA's existing tools without changing stdio registrations. DELETE or a new initialize ends the previous client session while preserving the shared target; cancelled work finishes cleanup before another session or provider teardown can reuse its resources.

Change and scope

  • Adds a node:http bridge and the pinned SDK's stateful Streamable HTTP transport, with streamed replies and Host/Origin validation classified solely from the actual bound IP, with configured aliases added afterward. HTTP is explicit; server.json, setup registrations and stdio behavior remain.
  • The shared server tracks tool and provider-backed completion callbacks through finalization. HTTP sessions also fence late message dispatch and own parsing/response cleanup. Handovers wait ten seconds and return 503 while retaining unfinished work for retry; full shutdown waits for completion.
  • The HTTP request owner admits at most eight concurrent input/route requests by default, before body conversion or initialize tees. MCP input permits end after dispatch and input settlement; plain responses retain admission through delivery and asynchronous source cleanup. Unread uploads retain admission until input completes or either side closes. Excess receives 503/connection close; queued HTTP/1.1 pipelining is disconnected before work starts. Sequential keep-alive remains supported. maxConcurrentDispatches permits an explicit embedding budget.
  • SDK body forwarding ends per request, including early refusals. Shutdown joins full exchanges, handler finalizers and response-source cancellation before provider hooks; failed cleanup retains ownership and stops new admission. All routes return 503 until the factory succeeds. HEAD cancellation stays nonblocking; a retained tee sibling must be consumed or cancelled by its caller before shutdown completes. The native byte bridge preserves reply ownership when cancelling unread input. One response writer owns its reader/cancellation across headers, pumping and completion, so output failures join the same cleanup barrier. Raw fragment delimiters are rejected before URL parsing; encoded query data is preserved.

Contract and boundary impact

  • Semantic owner: HTTP bootstrap/adapters own listener, admission and request lifetimes; the shared MCP server owns callback completion. Domain/provider contracts and Evidence shapes remain.
  • Contribution scope: inbound listener scope is tracked in [Design] Project captures into an environment manifest, serve it over streamable HTTP, export agent-environment bundles #4933 and explicitly authorized by the requesting human in the implementation session. No new provider execution authority is introduced.
  • CLI/MCP: HTTP-only host/port flags and MCP_HOST/MCP_PORT fallbacks; port 0 announces the bound URL on stderr. No new MCP tool or dependency. Standard registrations stay stdio.
  • Compatibility: one shared target, plain HTTP, with explicit non-loopback binding. Environment manifest serving/export are later increments. Authored docs cover transport, CLI and architecture; generated outputs are not committed.

Expected effects (check known effects; use documentation-only on its own).
Unchecked items do not establish absence; leave uncertainties visible.

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

Real HTTP negative controls reproduce late SDK tool dispatch, refused-body retention, admission bypass, premature handler/body cleanup, unread-upload release, startup readiness and queued pipelining. Eight negative controls for the latest response/pipelining fixes fail on the previous implementation. The fixes pass public client/reconnection, partial-upload, overload/recovery, cancellation and teardown workflows. Default stdio and catalog configurations are exercised.

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.
Representative output
listening: {"transport":"streamable-http","url":"http://127.0.0.1:57093/mcp","msg":"MCP transport listening"}
--- session A ---
>>> POST /mcp  accept=application/json, text/event-stream  content-type=application/json
      body: {"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"mcp","version":"0.1.0"}},"jsonrpc":"2.0","id":0}
<<< 200 POST /mcp  content-type=text/event-stream  mcp-session-id=e6e795ba-5e0c-469a-997a-015a62d134ac
>>> POST /mcp  mcp-session-id=e6e795ba-…  body: {"method":"notifications/initialized","jsonrpc":"2.0"}
>>> GET /mcp  mcp-session-id=e6e795ba-…
<<< 202 POST /mcp
>>> POST /mcp  mcp-session-id=e6e795ba-…  body: {"method":"tools/list","jsonrpc":"2.0","id":1}
<<< 200 GET /mcp  content-type=text/event-stream  mcp-session-id=e6e795ba-…
<<< 200 POST /mcp  content-type=text/event-stream  mcp-session-id=e6e795ba-…
>>> POST /mcp  mcp-session-id=e6e795ba-…  body: {"method":"tools/call","params":{"name":"binary_session","arguments":{}},"jsonrpc":"2.0","id":2}
<<< 200 POST /mcp  content-type=text/event-stream  mcp-session-id=e6e795ba-…
[A] session=e6e795ba-5e0c-469a-997a-015a62d134ac tools=207 has_binary_session=True binary_session.isError=False
>>> DELETE /mcp  mcp-session-id=e6e795ba-…
<<< 200 DELETE /mcp
--- session B ---
>>> POST /mcp  body: {"method":"initialize",...,"id":0}
<<< 200 POST /mcp  content-type=text/event-stream  mcp-session-id=b654ce7e-9909-4937-9497-185062379fbc
>>> POST /mcp  body: {"method":"notifications/initialized",...}   <<< 202 POST /mcp
>>> GET /mcp                                                   <<< 200 GET /mcp  text/event-stream
>>> POST /mcp  body: {"method":"tools/list",...,"id":1}          <<< 200 POST /mcp  text/event-stream
>>> POST /mcp  body: {"method":"tools/call","params":{"name":"binary_session","arguments":{}},...,"id":2}   <<< 200 POST /mcp  text/event-stream
[B] session=b654ce7e-9909-4937-9497-185062379fbc tools=207 has_binary_session=True binary_session.isError=False
>>> DELETE /mcp  mcp-session-id=b654ce7e-…   <<< 200 DELETE /mcp
client exit=0
server exit=143  stdout bytes=0
server log msgs: 1 "MCP transport listening", 2 "MCP HTTP session opened", 2 "MCP HTTP session closed by the client"

Validation performed

  • Current ba73ccafd on main 49b4edfe7: 8/8 static/build tasks passed (typecheck/runtime build, lint with 0 errors, module boundaries, formatting, Knip and metadata). Registry metadata passed. All 83 adapter tests passed, including two prior-code failures for localhost-looking names bound to external IPv4/IPv6 addresses and the earlier stream ownership, capacity, pipelining and URL controls.
  • Current 15-file public CLI/MCP/process boundary run: 149 passed / 2 failed (151 total). The failures occur in binary_session provider-status probing: native Java cleanup fails before the CLI provider assertion and the HTTP identity/session test can finish. Stdio initialization/catalog with invalid HTTP-only settings, HTTP Host refusal/options, signal/port shutdown, prompts/completions and lifecycle controls pass. No provider/process patch masks these failures.
  • Clean-main 3ea0d9489 control reproduced the stdio-doctor/process-cleanup family: 16 passed / 9 failed in four affected files, including environment_errno_EACCES. Relevant compiled ownership/direct-analysis/status modules were byte-identical. The new main only adds the upstream browser base64 fix. Current base main's CI is also failing. Broader previous-head run: 155 passed / 14 failed in 19 files.
  • Actual installed /usr/bin/gh, 40,149,832 bytes, SHA-256 ccb3b6fc7719fbae9e027d11856dc1c73ee7503075b23e28a723ab5975c09dde: seven equal normalized_result reports across CLI/stdio/HTTP on this build. Operation, subject path/digest, artifact size/digest, Go version and module path match file identity and independent go version -m. DELETE/replacement, SIGTERM 143, empty stdout, released port and unchanged input all pass.
  • Current CI static/source/build/docs, SQLite compatibility, JavaScript recovery, real Go metadata and Linux native package lanes passed. Darwin packaging fails in unchanged doctor/Java cleanup (process identity could not be revalidated); a test shard fails in unchanged keyed-archive/setup/doctor workflows with native cleanup errors, cancelling peers. Windows packaging passed; CI aggregation completed with Portable tests and CI required failing. The normal exact-head merge request for ba73ccafd was rejected with HTTP 405: 2 of 4 required status checks are failing. The requesting human subsequently authorized a bypass attempt: gh pr merge --admin --match-head-commit ba73ccafd3b9513c975b926c875b115dfc13c075 succeeded as gensokyo-dev on 2026-10-19 at 15:58:52 UTC, squash commit 60bd646478dcfab6c296b7e4765254eea787ffa9. The failing baseline CI checks were bypassed explicitly; they did not pass. Prior reruns produced the same native-ownership family; these failures were not repaired in this HTTP contribution.
  • Greptile reviewed ba73ccafd at 5/5 with no actionable finding. Codex completed its current-head review with no new inline finding observed. Its latest bound-address finding is fixed and resolved with root-cause, structural-fix and validation evidence.
  • Real Hopper/Ghidra/IDA analysis, actual off-host/DNS-reconfigured binds and later environment serve/export remain unverified. Binding classification is covered at its native-address predicate and live loopback behavior through public workflows. The original author's shared startup-failure cleanup limitation remains source-derived and outside this contribution: cleanup before a shutdown handle exists has no retry path; the common stdio failure path is unchanged.

Heavy work used one CPU/worker; no OOM. Static gate: 274.482s wall / 273.851s CPU / 4435.84 MiB sampled peak family RSS. Current 151-case attempt (with failures above): 63.336s / 60.930s / 1409.88 MiB. Equivalent installed-app workflow, 4c09146b6 → ba73ccafd: 34.220 → 27.417s wall, 34.197 → 27.331s CPU, 886.34 → 993.91 MiB; HTTP first/warm 8.518/0.538 → 6.839/0.348s, stdio 8.679/0.677 → 7.840/0.370s. These are single shared-host runs, main also changed and OS caches were not reset; no isolated performance effect is established. RSS sampling every 50ms can double-count shared pages. Agent tokens are unmeasured; 3536-byte envelopes are not token counts.

Compatibility, safety, and release

HTTP does not add TLS, client authentication or isolated target state. Non-loopback binding relaxes Host/Origin validation with a logged warning and requires explicit selection. Stdio stays the default. Shutdown is signal-driven, with SIGINT/SIGTERM 130/143 and provider teardown after the request barrier. No installer, dependency, registry registration or tracked generated-file change.

Author readiness

Human owner: @earakely-scale

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

Add rea mcp --http [--host] [--port]: the same server rea speaks over stdio,
served over MCP Streamable HTTP on a loopback listener by default, using the
SDK's web-standard transport already in the pinned @modelcontextprotocol/server
behind a small node:http bridge. One client and one session at a time; DELETE
ends the session without running provider teardown, a new client's initialize
replaces a session left open, foreign Host headers are refused on loopback
binds, and shutdown is signals-only. Stdio stays the default and registered
transport; server.json and client registrations are unchanged.

Refs morluto#4933

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-19T14:12:33.993177Z ba73cca Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@earakely-scale

Copy link
Copy Markdown
Contributor Author

Requesting maintainer review. The upstream workflows are waiting for approval to run on this first-time-contributor PR; the same head (46dd8f0) ran green on the fork: https://github.com/earakely-scale/rea/actions/runs/39096057470. This is item 2 of the scope decision requested in #4933 and stands alone from #4954: opt-in --http, loopback default with the SDK Host allowlist, one client at a time, signals-only lifecycle. Greptile findings will be addressed in this thread.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 46dd8f0e2b

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/server/http/serveStreamableHttp.ts Outdated
Comment on lines +129 to +132
async close(): Promise<void> {
const open = this.#live;
this.#live = undefined;
await open?.shutdown();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Fence late session arming during shutdown

When shutdown overlaps an initialize that is still being probed or replacing the old session, its handler can resume after this method clears the current session and call #current() again. Because close() neither marks the slot permanently closed nor waits for #arming, #arm() can publish a fresh transport after shutdown has resolved, outside the listener/server cleanup. Mark the slot closed before teardown and join or cancel any in-flight arming.

AGENTS.md reference: AGENTS.md:L23-L23

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b0ec63c. The slot records that it is closed: close() joins an arming session before ending it, and every request after that, including one that was arming, is refused with 503. Test: an initialize racing close() gets 503, the shutdown hook fires once, and the next request gets 503.

Comment thread src/server/http/serveStreamableHttp.ts Outdated
Comment on lines +256 to +258
let closing: Promise<void> | undefined;
const close = (): Promise<void> => {
closing ??= (async () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Let failed HTTP cleanup be retried

If slot.close() or instance.close() rejects—for example when real provider cleanup fails—this ??= permanently memoizes the rejected attempt. createShutdown retries failed owners after another shutdown trigger, but every later call now receives the old rejection and never re-runs unfinished cleanup; the exported server handle cannot recover either. Clear the memoized attempt on failure and make the cleanup stages independently retryable.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b0ec63c, with the Greptile finding below: close() runs three stages (listener, slot, instance) once each, and a failed stage is retried by the next call instead of replaying the rejection, matching createShutdown. Test: the instance's first close() rejects, the second call resolves and the port is released.

Comment thread src/server/http/serveStreamableHttp.ts Outdated
Comment on lines +58 to +60
/** Host header allowlist for a bind, or undefined when validation is relaxed. */
export const hostHeaderAllowlist = (host: string): string[] | undefined =>
LOOPBACK_HOSTS.has(host) ? localhostAllowedHostnames() : undefined;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate every loopback spelling before relaxing Host checks

When an operator binds another loopback spelling such as LOCALHOST, localhost., or 127.0.0.2, the listener is still local, but this exact string lookup returns undefined and the request path skips hostHeaderValidationResponse entirely. Foreign Host values are then accepted even though the documented contract says loopback binds retain the SDK allowlist; classify/normalize all loopback addresses and include the selected bind address rather than treating these as non-loopback.

AGENTS.md reference: AGENTS.md:L5-L5

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b0ec63c, with the Greptile finding below. A bind is loopback by address class after the same normalization the SDK applies to Host headers (new URL hostname): any 127.0.0.0/8 address, ::1 in any spelling, IPv4-mapped loopback and localhost names including LOCALHOST and localhost.. The allowlist adds the bind's own normalized hostname so 127.0.0.2 is still served. Test: twelve spellings.

@greptile-apps

greptile-apps Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[High impact] The PR appears safe to merge; no new actionable issue was established.

Summary

Adds opt-in streamable HTTP at /mcp while keeping stdio as the default.

  • REA's MCP catalog can now serve HTTP clients at /mcp.
  • HTTP work stays tracked until its cleanup finishes.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[HTTP request] --> B[Admission check]
  B -->|Full or cleanup failed| C[503 and close connection]
  B --> D[Host and Origin checks]
  D --> E{Route}
  E -->|MCP| F[Single session owner]
  E -->|Plain route| G[Route handler]
  F --> H[Tracked dispatch and callbacks]
  G --> I[Response writer]
  H --> I
  I --> J[Retained cancellation cleanup]
  K[Shutdown] --> L[Stop listener and close connections]
  L --> M[Drain sessions, exchanges and cleanup]
  M --> N[Close providers]
Loading

Reviews (30) · Last reviewed commit: "fix(mcp): classify HTTP binds from nativ..." · Reviewed by Greptile

Comment thread src/server/http/serveStreamableHttp.ts Resolved
Comment thread src/server/http/serveStreamableHttp.ts Resolved
Comment thread src/server/http/serveStreamableHttp.ts Resolved
Comment thread src/server/http/serveStreamableHttp.ts Resolved
Comment thread scripts/rea.mjs Resolved
…nd shutdown

Addresses the automated review findings on the PR: refuse requests once the
session slot is closed and join an arming initialize during shutdown; retry
failed close stages instead of replaying the rejection; classify loopback
binds by address class and add the bind's own hostname to the Host and Origin
allowlist; let only a POST with the streamable headers replace an open
session; announce the bound URL at every log level; route `mcp -h --http` to
the HTTP entry.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b0ec63cc03

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/server/http/serveStreamableHttp.ts Outdated
return (
accept.includes("application/json") &&
accept.includes("text/event-stream") &&
/^application\/json\b/iu.test(contentType.trim())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require the actual JSON media type before replacement

In hasStreamablePostHeaders, the word-boundary check also accepts media types such as application/json-patch+json; with an otherwise valid initialize body, McpSessionSlot.handle then closes the live transport before the SDK can reject that non-application/json request. An accidental or malformed sessionless POST can therefore evict the active client despite the documented replacement guard, so parse the base media type (allowing parameters) rather than matching a prefix.

AGENTS.md reference: AGENTS.md:L25-L25

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9ed8f06: the guard compares the media type proper (before any ; parameter, lowercased) to application/json, so application/json-patch+json no longer qualifies. Test: such an initialize is refused while the connected client keeps echoing.

Comment thread src/server/http/serveStreamableHttp.ts Outdated
httpServer.listen(port, host);
await once(httpServer, "listening");
} catch (cause: unknown) {
await instance.close().catch(() => undefined);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Retain the server when bind-failure cleanup rejects

When binding fails and the factory-created server's close() also rejects, this catch discards the cleanup failure and serveStreamableHttp throws without returning either the instance or a retry handle. Direct users of this exported helper (including its documented plain-route composition use) consequently lose the only cleanup owner and can leave provider processes or other server resources alive; create the instance after binding or otherwise retain and retry the failed owner.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9ed8f06: the server instance is created after the listener has bound. A bind failure therefore has nothing to clean up and throws the typed listen error as before; a factory failure closes the listener and rethrows the factory error, so no instance is ever created and left unowned. Requests that arrive before the instance exists get 503 Server starting. Test: a throwing factory rejects without announcing a URL.

…server

Addresses the second automated review round: a sessionless POST replaces a
session only when its media type proper is application/json, and the server
instance is created after the listener binds so a bind failure leaves nothing
to clean up and a factory failure releases the listener.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/server/http/serveStreamableHttp.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9ed8f06f75

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/server/http/serveStreamableHttp.ts Outdated
throw new StreamableHttpListenError(cause);
}
const url = endpointUrl(httpServer.address());
origin = new URL(url).origin;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Close scoped-IPv6 listeners when URL construction fails

When --host is a scoped link-local IPv6 literal such as fe80::...%eth0, Node can bind and returns an address containing %eth0; endpointUrl wraps it in brackets, but the supported Node 24.x WHATWG URL rejects that scoped literal at this line. Because the throw occurs after listen() and outside any listener-cleanup catch, serveStreamableHttp rejects while the HTTP socket remains referenced, so the CLI reports startup failure but hangs and retains the port. Reject unsupported scoped binds before listening or close the listener when endpoint construction fails.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b76f354: scoped IPv6 literals (any % in the host) are refused before binding with the typed listen error, and if the bound address still cannot be named in a URL the listener is closed before the error is thrown. Test: fe80::1%lo0 rejects before the factory runs.

Comment thread src/server/http/serveStreamableHttp.ts Outdated
const close = stagedClose([
closeListener,
() => live.close(),
() => instance.close(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Give the HTTP server instance one cleanup owner

In HTTP mode, startMcpTransport still runs Promise.allSettled([handle.close(), closeServers()]), and the factory instance remains in its servers set; adding this stage means both paths call the same instance.close() on every shutdown. If close is non-reentrant, or a provider close rejects once and succeeds when this stage retries it, cleanup can race and the stale closeServers() rejection still forces MCP_SHUTDOWN_FAILED/exit 1 after the second call has cleaned the resources. Make the helper and transport agree on a single owner for instance cleanup.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b76f354: serveStreamableHttp takes closeInstance (default true for standalone callers such as an environment server); the MCP runtime passes closeInstance: false, so startMcpTransport and its factory owner stay the single owner of instance cleanup and nothing races closeServers(). Test: with closeInstance: false, close leaves the instance open until its owner closes it.

Comment thread src/server/http/serveStreamableHttp.ts Outdated
options: ServeStreamableHttpOptions,
): Promise<StreamableHttpServer> => {
const { host, port, logger, routes = [] } = options;
const allowedHosts = hostHeaderAllowlist(host);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Classify loopback after resolving the bind address

When --host is ip6-localhost, ::1%lo, or a custom host alias resolving to loopback, this pre-resolution call returns undefined even though Node's eventual listener address is ::1 or 127.x, so the route accepts foreign Host and Origin values contrary to docs/mcp-contracts.md:449-454. Fresh evidence after the claimed fix is that classification still happens before listen() and never consults httpServer.address(). Classify the bound address and add the configured name to that loopback allowlist.

AGENTS.md reference: AGENTS.md:L5-L5

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b76f354: loopback is now classified after listen() from httpServer.address(), and the allowlist is the SDK list plus the configured name and the bound address, so ip6-localhost or a host alias that resolves to ::1 or 127.x keeps Host and Origin validation and is still served under its own name. Tests: ip6-localhost bound to ::1, dev.local bound to 127.0.0.1, dev.local bound to a public address stays relaxed.

Comment thread src/server/http/serveStreamableHttp.ts Outdated
httpServer.on("request", (request, response) => {
void handleRequest(request, response);
});
httpServer.on("error", (error) => options.onerror?.(error));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not report a bind failure as connection loss

When the selected port is occupied, the same error event invokes this permanent listener and rejects the once(httpServer, "listening") awaited below. In the inspected HTTP runtime in src/main/transport.ts, options.onerror is the MCP_CONNECTION_LOST callback, so a normal EADDRINUSE prints the misleading lost-client message before the correct MCP_HTTP_LISTEN_FAILED; the boundary test only injects a rejected promise and misses this callback. Forward errors only after a successful bind, or ignore them while the server is not listening.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b76f354 with the Greptile finding above: no permanent error listener exists until the bind has succeeded, so EADDRINUSE never reaches the connection-loss handler. Test: an occupied port rejects with the typed listen error and onerror is not called.

…ailures out of onerror

Addresses the third automated review round: loopback is classified from the
address the listener bound with the configured name added to the Host and
Origin allowlist; scoped IPv6 literals are refused before binding and a URL
that cannot be formed closes the listener; listener errors reach onerror only
after a successful bind; the MCP runtime keeps its factory owner as the single
owner of instance cleanup through `closeInstance: false`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b76f354d76

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +117 to +118
accept.includes("application/json") &&
accept.includes("text/event-stream") &&

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require exact Accept media ranges before takeover

When a live session exists, an initialize with Accept: application/json-patch+json, text/event-streaming passes both substring tests even though neither comma-delimited range is one of the required response types; handle() then closes the live transport before the SDK accepts or refuses the request. Fresh evidence after the Content-Type fix is that only the Content-Type essence was made exact while Accept remained substring-based. Parse Accept media ranges case-insensitively and require exact application/json and text/event-stream entries before takeover.

AGENTS.md reference: AGENTS.md:L25-L25

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fb22df3: Accept is split into media ranges, each reduced to its media type (parameters dropped, lowercased), and the guard requires exact application/json and text/event-stream entries. Test: application/json-patch+json, text/event-streaming with a valid initialize body is refused while the connected client keeps echoing.

Comment thread src/server/http/serveStreamableHttp.ts Outdated
await shutdown();
} finally {
protocol.onclose = this.#shutdownHook;
if (this.#live?.transport === transport) this.#live = undefined;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Retain the live session when transport shutdown fails

When shutdown() rejects while a client DELETE or takeover is closing a live transport, this finally still removes the session, so the next initialize arms another transport and no later slot close can retry the unresolved one. Fresh evidence after the staged-close fix is that its regression only fails the later instance.close() stage, not this session-ending stage. Clear #live only after shutdown succeeds so the exact cleanup owner remains retryable.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fb22df3: #endSession releases the session only after shutdown() resolves, and close() does the same, so a rejected shutdown leaves the session owned and the next close() retries exactly it. Test: a transport whose close rejects once makes close() reject, the second call completes, the shutdown hook fires once and later requests get 503.

earakely-scale and others added 2 commits October 18, 2026 09:36
…wn failed

Addresses the fourth automated review round: a sessionless POST replaces a
session only when its Accept header lists application/json and
text/event-stream as exact media ranges, and a session whose transport
shutdown rejected stays owned so the next close retries it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Replaces a comma expression left by the previous commit with plain
statements and moves the port release into a small function, so the listener
body stays within the lint limits without changing behaviour.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 54a7475602

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/server/http/serveStreamableHttp.ts Outdated
Comment on lines +192 to +194
const open = this.#live;
// The session stays owned until its shutdown succeeds, so a retry can finish it.
await open?.shutdown();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Run the shutdown hook when no session is live

When the listener is closed before any MCP request, or after a client DELETE has already cleared #live, open is undefined and this close cannot drive the protocol's onclose. The subsequent instance.close() has no attached transport to generate that event either, so the captured #shutdownHook never runs; direct users whose factory owns resources through that hook can therefore skip final cleanup even though per-session closes deliberately defer it until listener shutdown. Invoke the captured hook exactly once for the sessionless close path.

AGENTS.md reference: AGENTS.md:L23-L23

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1741882: the slot wraps the captured hook so it runs exactly once, and close() invokes it after ending any live session, so a listener closed before any request, or after a client DELETE, still delivers the final cleanup. Tests: two closes of an idle slot fire the hook once; an idle listener close fires it once; the existing session-based tests still see exactly one.

Comment thread src/server/http/serveStreamableHttp.ts Outdated
} catch {
return false;
} finally {
await probe.body?.cancel().catch(() => undefined);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not await cancellation of only the cloned body

With an initialized session, an oversized sessionless POST enters this probe and readRequestBody(probe) can return tooLarge before the cloned branch is drained. A cloned Fetch body is a tee, and canceling one branch does not settle until the original branch is consumed or canceled; because the original cannot reach transport.handleRequest until this await finishes, the request stalls until timeout or shutdown instead of receiving the SDK's bounded refusal, allowing concurrent oversized uploads to retain connections for minutes. Start cancellation without awaiting that branch, or coordinate disposal with the original request.

AGENTS.md reference: AGENTS.md:L51-L52

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1741882: the probe starts cancelling its cloned branch without awaiting it, so the original request reaches the transport and gets the SDK's bounded refusal. Test: a 4.5 MB sessionless initialize is refused promptly (or the upload is cut by the early close) while the connected client keeps echoing.

Comment thread src/server/http/nodeHttpBridge.ts Outdated
response: Response,
target: ServerResponse,
): Promise<void> => {
target.writeHead(response.status, Object.fromEntries(response.headers));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve every Set-Cookie header

When a composed plain route returns multiple Set-Cookie values, the supported Node 24 Headers iterator exposes them as repeated entries, but Object.fromEntries overwrites each earlier value with the last one. writeHead therefore sends only one cookie, breaking routes that need to set independent session and CSRF cookies; pass header tuples/raw header arrays or handle getSetCookie() separately so repeated response metadata survives.

AGENTS.md reference: AGENTS.md:L13-L13

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1741882: writeWebResponse builds the header fields itself and passes headers.getSetCookie() as an array under set-cookie, so repeated cookies survive writeHead. Test: two Set-Cookie values from a composed route both arrive.

…and keep every Set-Cookie

Addresses the fifth automated review round: the instance's shutdown hook runs
exactly once even when the listener closes without a live session; the
initialize probe no longer awaits cancelling its cloned body, which would wait
for the original request to drain; and the node:http bridge passes repeated
Set-Cookie values through as an array.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 174188279b

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/main.ts Outdated
...options,
});
},
registerShutdown: (request) =>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Register signals before asynchronous HTTP startup

When SIGINT or SIGTERM arrives while rea mcp --http is still opening its initial target, loading optional providers, or returning from the asynchronous HTTP serve, this callback has not been invoked—the only invocation is later in createShutdown, after startMcpTransport returns. Node therefore performs default signal termination and bypasses the session/provider cleanup promised by this mode; this race can occur even just after the listening log is emitted and can leave a launched analysis provider behind. Install or latch the signal handler before startup begins, then hand the pending shutdown request to the lifecycle owner.

AGENTS.md reference: AGENTS.md:L23-L23

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 354b4d8: runMcpHttpEntrypoint latches SIGINT and SIGTERM before any asynchronous startup; the HTTP registerShutdown installs the real handler, releases the latch and, if a signal was recorded meanwhile, requests shutdown immediately with that signal's exit status; a second signal during startup exits at once; the latch is released on every startup exit path. Test: the latch records 143, exits on a second signal, hands the status over on release and leaves no listeners.

…cleanup

Addresses the sixth automated review finding: SIGINT and SIGTERM are recorded
from the moment the HTTP entry starts, the lifecycle owner acts on a recorded
signal as soon as it registers, and a second signal during startup exits at
once.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/main.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 354b4d8c08

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/main.ts Outdated
// A signal that arrived during startup is honoured now that the lifecycle owner exists.
const pending = latch.release();
if (pending !== undefined) {
base.setExitCode(pending);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the latched signal status after startup

When SIGINT or SIGTERM arrives before lifecycle registration, latch.release() reaches this branch and assigns 130/143, but run() then returns 0 and the enclosing runEntrypoint overwrites the same exit code with that return value at line 139. Cleanup still runs, but a successfully cleaned startup-time interruption is reported as success instead of the 130/143 promised in docs/mcp-contracts.md:461-465; carry the pending status out of run or otherwise prevent the later overwrite.

AGENTS.md reference: AGENTS.md:L23-L23

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 136d073 with the Greptile finding above: exit.signal(status) records the status in both the latched and live paths and exit.set(0) from runEntrypoint no longer overwrites it; set(1) still does. Tests: unit ordering test plus a process test that signals as startup completes.

…mal return

Addresses the follow-on finding on the signal latch: the HTTP entry now owns
its exit status, so a 0 returned by startup after a recorded signal keeps the
signal's 130 or 143 while a real failure still wins; a process test sends the
signal as the listening line appears.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 136d073fa0

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/server/http/serveStreamableHttp.ts Outdated
): Promise<void> => {
const { route, origin, logger } = target;
try {
const webResponse = await route(toWebRequest(request, response, origin()));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Drain bodies when handlers reply before reading them

When a POST is rejected before the MCP handler reads it (for example by the Host/Origin checks, an unknown plain route, or the startup 503), this inline web request is discarded as soon as route() returns while the underlying IncomingMessage is never drained or canceled. Node leaves that request paused after the response finishes, so a slow uploader on a non-loopback bind can retain one socket per request for the request-timeout window and exhaust the listener; drain the original stream or terminate the connection on early responses.

AGENTS.md reference: AGENTS.md:L51-L52

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a23f5f1: serveNodeRequest checks whether the web request body was consumed when the reply is written; a reply that precedes any read (refused Host or Origin, unknown route, startup 503, or the 500 fallback) is sent with Connection: close, so Node ends the socket after flushing it instead of leaving the unread upload paused. Test: an unknown-route POST and a foreign-Host POST get Connection: close; a keep-alive GET without a body keeps its connection.

… read

Addresses the eighth automated review finding: a refused Host or Origin, an
unknown route or the startup 503 answered a POST while its body stayed unread
on the paused bridged stream; such replies now carry Connection: close so an
unread upload cannot keep a socket open.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/server/http/serveStreamableHttp.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a23f5f1352

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/server/http/serveStreamableHttp.ts Outdated
response: ServerResponse,
): Promise<void> => {
const { route, origin, logger } = target;
const webRequest = toWebRequest(request, response, origin());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Catch Fetch conversion failures inside the request guard

On the supported Node 24 runtime, a client that sends a syntactically valid TRACE or TRACK request makes new Request(...) throw because Fetch forbids those methods. This conversion runs before the try, while the listener at lines 332-334 discards this async function's promise, and there is no process-level unhandledRejection handler, so one HTTP request terminates the MCP process instead of receiving a bounded refusal; move the conversion into the guarded path or reject unsupported methods first.

AGENTS.md reference: AGENTS.md:L31-L31

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 24301be with the Greptile finding above: conversion is guarded and answered with 405 plus Connection: close; nothing escapes serveNodeRequest into the discarded promise.

Comment thread src/server/http/serveStreamableHttp.ts Outdated
Comment on lines +392 to +393
const unreadBody = (): boolean =>
webRequest.body !== null && !webRequest.bodyUsed;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Inspect the incoming stream before keeping bodyless requests alive

When a peer sends GET or HEAD with a Content-Length or chunked body, Node accepts the payload, but toWebRequest deliberately gives these methods a null body (nodeHttpBridge.ts:34-36), so this predicate returns false although the IncomingMessage remains paused and incomplete. Fresh evidence after the prior POST fix is that such a slow upload receives an early 404/406 with keep-alive and retains the socket until the request timeout; inspect the original incoming stream or force connection close for bodyless-method uploads.

AGENTS.md reference: AGENTS.md:L51-L52

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 24301be: the unread-body decision now comes from the incoming message's own body declaration (Content-Length or Transfer-Encoding) rather than the web request, so a GET or HEAD that carries a body also closes the connection after its reply. Test: a keep-alive GET with a declared body is answered 404 with Connection: close and a closed socket. Node's parser already refuses chunked GET bodies with its own 400 and closes.

Track admitted route dispatches until their finalizers settle, retain admission while uploads remain unfinished, and separate MCP cancellation from provider hooks. Reuse staged transport cleanup for startup failures and normal shutdown. Cover plain-route cleanup, incomplete streaming uploads and pending-factory failure with real HTTP requests.
@gensokyo-dev

Copy link
Copy Markdown
Collaborator

@codex review

Please review current head 3eb0722ef on this original PR, including latest main b999e7247.

Both latest plain-route findings have real HTTP negative controls and fixes. The HTTP request owner tracks route promises through finalizers; shutdown cancels MCP work, joins admitted routes, then runs provider hooks. Unread uploads retain admission until input completes or either side closes, including long responses. The same staged transport cleanup now covers a pending factory's startup failure.

Full static/build checks passed 8/8 and 69 focused source tests passed. Four new negative controls reproduce premature normal/startup shutdown and early release for a streaming response. The final compiled workflow suite, upstream capture controls and installed-application comparison are running; the PR body will receive their exact completed results.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3eb0722ef2

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/server/http/serveStreamableHttp.ts Resolved
Comment thread src/server/http/serveStreamableHttp.ts Resolved
Own complete node HTTP exchanges and separately join response-source cancellation before provider hooks. Retain plain-response admission through asynchronous cleanup, preserve prompt HEAD delivery and MCP SSE admission, and fail closed on unsuccessful cleanup.

Reject queued pipelined requests before allocating work or buffered refusals, keep sequential keep-alive, and withhold all routes until server construction succeeds. Add real HTTP regressions for cancellation, late responses, tee ownership, cleanup failures, resource capacity, pipelining and keep-alive.
@gensokyo-dev

Copy link
Copy Markdown
Collaborator

@codex review

Please review the current head ed85af7. The follow-up replaces route-only ownership with whole-exchange plus separately joined response-source cleanup; keeps cleanup failures owned; bounds pending plain responses/cleanup; rejects queued pipelining before dispatch; and gates all routes until the factory succeeds. Eight previous-code negative controls reproduce the lifecycle/pipelining issues. Adapter checks passed; the complete current-head static/build, compiled boundary and installed-app validations are still running and are marked pending in the PR body.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ed85af725d

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/server/http/nodeHttpBridge.ts Resolved
Comment thread src/server/http/nodeHttpBridge.ts Resolved
Make the web-response writer own one reader and one cancellation operation across headers, pumping and completion, so every output exception retains source cleanup before provider teardown. The pump borrows that ownership instead of releasing the source on its own.

Reject raw fragment delimiters before parsing origin-form request targets, preserving percent-encoded query data. Add real HTTP negative controls for malformed chunks, invalid output headers and query fragments.
@gensokyo-dev

Copy link
Copy Markdown
Collaborator

@codex review

Current head: 4c09146. Follow-up relative to your ed85af7 review: the response writer now owns one reader/cancellation operation across headers, pumping and completion, including all output exceptions. It cancels once and registers the original cleanup promise before rethrowing; the pump borrows that owner. Request targets reject raw # before URL parsing; encoded %23 stays query data. Three real-HTTP negative controls fail on ed85af7 and all 81 current adapter tests pass, including the related invalid-header output path. Full static/build and installed-app checks are running; prior-head failures in native provider/ownership paths remain documented with clean-main controls. Please check these fixes and their lifecycle interactions.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4c09146b64

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/server/http/serveStreamableHttp.ts Resolved
Classify loopback from the actual bound IP only, then add the configured name to the Host/Origin allowlist. Remove DNS-name classification and the default/fallback that substituted configuration for binding evidence.

Validate the TCP address once before URL/allowlist consumers, preserve IPv4 and IPv6 alias behavior, and add negative controls for localhost names bound to non-loopback IPv4 and IPv6 addresses.
@gensokyo-dev

Copy link
Copy Markdown
Collaborator

@codex review

Current head ba73cca, refreshed with main 49b4edf. The focused follow-up to your 4c09146 finding removes configured DNS names from loopback classification, requires the actual bound address, and adds configured aliases only after the bound IP is classified. TCP address validity is checked once before URL and allowlist consumers; the fallback to the configured host is removed. IPv4/IPv6 loopback aliases retain existing behavior. The two non-loopback DNS-name controls fail on the previous implementation and all 83 current adapter tests pass. Full current static/build and installed-app checks are running. Please review this binding/ownership change and its callers.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: ba73ccafd3

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@gensokyo-dev

Copy link
Copy Markdown
Collaborator

Follow-up implementation and validation are current at ba73cca (main 49b4edf), on this original PR. All 83 adapter tests, all 8 static/build tasks and the installed-app CLI/stdio/HTTP comparison pass; current Codex review completed with no new inline finding and Greptile reported 5/5. The 151-case public boundary run is 149 passed / 2 failed at the documented common Java/provider cleanup path.

The normal squash merge request for this exact head was submitted and GitHub rejected it with HTTP 405: “2 of 4 required status checks are failing.” The failing required contexts are Portable tests and CI required. Current failures are the documented native Java/ownership family; current base main also has failing CI. No unrelated provider/process patch or replacement PR was added. The configured account can push but cannot bypass the merge gate. This PR remains ready pending baseline CI recovery or a maintainer action on those requirements. Subsequent original PRs #4975/#4999 have not been advanced, preserving the requested merge order.

@kaoru0822-kitauji kaoru0822-kitauji left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at ba73ccafd by reading the source against the pinned @modelcontextprotocol/[email protected]. I did not build or run it, so everything below comes from the source.

The lifecycle work holds up as far as I can see. Session handover and drain, admission, the signal latch, and the stdio path all look right to me; RequestTrackingMcpServer passes calls straight through until enableRequestTracking(), so stdio behaves as before. My concerns are about authority, not lifecycle.

1. The listener exposes execution- and mutation-capable tools without client authentication.

rea mcp --http serves the full catalog: 207 tools in the PR's own transcript. That includes gdb_console, whose own limitation text says "The unrestricted GDB console can access local shell, filesystem, network, and target controls." It also includes start_gdb_session, load_frida_script, instrument_with_frida, execute_rizin_command, install_adb_package and push_adb_file. Over stdio, only the parent process can call these. Over HTTP:

  • Loopback: any local process can connect to 127.0.0.1:<port>, including processes run by other users on a shared host. The Host/Origin checks stop DNS rebinding and browser pages. They do not stop local peers.
  • Takeover: by design, a new initialize replaces the open session. So a peer doesn't have to wait for the analyst to finish. It can take over the session along with the shared active target and run these tools under the analyst's user ID.
  • Non-loopback bind: all of the above applies to anyone who can reach the address, and Host/Origin validation is switched off (see inline).

The docs say to use the endpoint "only within a trusted local or isolated environment". But under CONTRIBUTING's fail-closed rule, a "local-only design or an 'authorized use only' disclaimer does not establish containment." Adding authentication looks cheap: the SDK already exports requireBearerAuth/verifyBearerToken. A per-process token would do it, either generated at startup and written to a 0600 file, or supplied by the gateway through an environment variable. It would also make the takeover behavior safe, since only a token holder could replace the session.

2. Non-loopback binds go beyond what #4933 proposed, and the environment can select one (inline on mcpHttpEndpoint.ts).

3. Scope decision. I don't see a maintainer decision on #4933 yet. Its comments come only from the author and one other contributor, and the PR body cites authorization from "the requesting human in the implementation session". This adds new network access to tools that can execute code, so I think it needs an explicit decision from @morluto on #4933 before merge. That decision should cover the final diff, especially non-loopback binding and the authentication model.

One non-blocking lifecycle note is inline on NodeHttpRequestOwner.ts. It can't happen with rea mcp --http today, but it becomes relevant to the plain routes in #4975.

const issues: ConfigurationSettingIssue[] = [];
let host = overrides.host ?? DEFAULT_MCP_HTTP_HOST;
let port = overrides.port ?? DEFAULT_MCP_HTTP_PORT;
if (overrides.host === undefined && environment.MCP_HOST !== undefined) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#4933 describes item (2) as adding "an inbound loopback listener". This PR also accepts any host. And through this fallback, an inherited MCP_HOST=0.0.0.0 turns on a non-loopback bind with nothing on REA's own command line. MCP_HOST/MCP_PORT are generic names that a gateway or container may already set for other MCP servers. The only sign is the warn line in serveStreamableHttp.ts.

Suggestion for this increment: fail closed and refuse non-loopback bound addresses. If they're needed, require an explicit flag together with authentication. A REA_-prefixed variable would also avoid picking up another server's setting.

options.sessionDrainTimeoutMs,
);
slot = live;
if (allowedHosts === undefined)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On a non-loopback bind, this warning is the only safeguard left. Host and Origin validation are both off, and there's no authentication, so anyone who can reach the address can drive the full tool catalog, including gdb_console. Given the fail-closed rule, I'd rather this path refuse to start (or require a token) than log a warning and continue.

await Promise.allSettled([...this.#exchanges]);
while (this.#bodyCleanups.size > 0)
await Promise.allSettled([...this.#bodyCleanups]);
if (this.#cleanupFailures.length > 0)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking. Nothing ever clears #cleanupFailures, so after one response-source cancel() rejects, drain() throws on every later call:

  1. prepareTransportShutdown stage 3 never completes.
  2. createShutdown rejects before any provider owner closes.
  3. SIGINT/SIGTERM handlers stay registered, because they are only removed after a successful shutdown, so signals can't end the process.
  4. The only way out is SIGKILL, which orphans exactly the provider processes this was meant to keep owned.

With rea mcp --http this can't happen: there are no plain routes, and the SDK's stream cancel() callbacks can't reject. But #4975 adds plain routes. An escalation path would keep "retain ownership" from becoming "never release". For example, a second signal could proceed with provider teardown and still report the retained failure (exit 1).

@gensokyo-dev
gensokyo-dev merged commit 60bd646 into morluto:main Oct 19, 2026
38 of 47 checks passed
@github-actions github-actions Bot mentioned this pull request Oct 19, 2026
3 tasks done
SahilHasnain pushed a commit to SahilHasnain/rea that referenced this pull request Oct 20, 2026
SahilHasnain pushed a commit to SahilHasnain/rea that referenced this pull request Nov 6, 2026
SahilHasnain pushed a commit to SahilHasnain/rea that referenced this pull request Nov 6, 2026
SahilHasnain pushed a commit to SahilHasnain/rea that referenced this pull request Nov 7, 2026
SahilHasnain pushed a commit to SahilHasnain/rea that referenced this pull request Nov 7, 2026
SahilHasnain pushed a commit to SahilHasnain/rea that referenced this pull request Nov 20, 2026
SahilHasnain pushed a commit to SahilHasnain/rea that referenced this pull request Nov 20, 2026
@morluto morluto added area: mcp MCP server, transport, and tool registration enhancement New feature or request labels Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: mcp MCP server, transport, and tool registration enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants