Skip to content

fix(core): tolerate optional MCP HTTP event stream failures - #24

Merged
stanley2058 merged 1 commit into
mainfrom
fix/native-http-mcp-inbound-sse
Aug 1, 2026
Merged

fix(core): tolerate optional MCP HTTP event stream failures#24
stanley2058 merged 1 commit into
mainfrom
fix/native-http-mcp-inbound-sse

Conversation

@lilac-stw

@lilac-stw lilac-stw commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • keep native Streamable HTTP MCP servers available when @ai-sdk/mcp reports a rejected optional inbound GET event stream while POST initialization and discovery still work
  • scope the exception to structured SDK errors for the configured HTTP endpoint, while preserving terminal handling when an established MCP session expires
  • add real-SDK loopback coverage for both the sessionless optional-GET case and stateful session expiration
  • do not add or fall back to the legacy SSE transport

Verification

  • cd apps/core && bun test tests/mcp/registry.test.ts — 25 passed
  • cd apps/core && bunx tsc -p tsconfig.json --noEmit
  • bun run typecheck
  • bun run lint
  • bun run fmt:check
  • live native HTTP registry check against the reported MetaMCP endpoint — available, 124 tools

Full-suite note

bun run test:all was attempted in the sandbox. The affected MCP suite passed, but unrelated environment-bound tests failed: three Codex OAuth callback tests could not connect to their loopback listener, and six SSH transport tests were denied while spawning /usr/bin/ssh. No files in either failing area are changed by this PR.

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of HTTP connection errors during session setup.
    • 404 responses from inbound event streams no longer cause premature terminal failures when the session has not started.
    • Established HTTP sessions are now properly retired when their inbound stream expires.
    • Other unexpected connection errors continue to receive standard failure handling.

@coderabbitai

coderabbitai Bot commented Aug 1, 2026

Copy link
Copy Markdown

Review Change Stack

Walkthrough

Changes

HTTP SSE session lifecycle

Layer / File(s) Summary
Inbound SSE error classification and transport wiring
apps/core/src/mcp/registry.ts
The registry validates optional inbound SSE errors, observes HTTP session expiration, ignores matching pre-session errors, and preserves terminal handling for other errors.
Native HTTP transport lifecycle coverage
apps/core/tests/mcp/registry.test.ts
Tests validate JSON-RPC requests, pre-session inbound SSE 404 handling, and established-session expiration with tool removal.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Registry
  participant HTTPTransport
  participant MCPServer
  Registry->>HTTPTransport: initialize HTTP transport
  HTTPTransport->>MCPServer: request inbound SSE
  MCPServer-->>HTTPTransport: return SSE response or 404
  HTTPTransport->>Registry: report transport error
  Registry->>Registry: check error shape and session state
  Registry->>MCPServer: remove tools after session expiration
Loading

Possibly related PRs

Suggested reviewers: stanley2058

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: tolerating optional MCP HTTP event stream failures.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/native-http-mcp-inbound-sse

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🧹 Nitpick comments (2)
apps/core/src/mcp/registry.ts (2)

565-569: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Log tolerated optional inbound SSE errors instead of discarding them silently.

When isOptionalHttpInboundSseError returns true, the handler returns without any logging. The error is real (a rejected inbound GET SSE stream) even though it's non-fatal; discarding it with no trace makes it hard to diagnose recurring inbound-stream failures in production. Add a debug/trace-level log capturing the tolerated error before returning.

🪵 Proposed logging addition
             onUncaughtError: (error) => {
               if (
                 isOptionalHttpInboundSseError(definition, holder.sessionExpired === true, error)
               ) {
+                logger.debug(`Ignoring optional inbound SSE failure for MCP server ${definition.id}`, { error });
                 return;
               }

As per coding guidelines, "Safely convert unknown caught values, avoid silently swallowing errors, and make logged errors informative and traceable."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/core/src/mcp/registry.ts` around lines 565 - 569, In the handler around
isOptionalHttpInboundSseError, add a debug- or trace-level log containing the
tolerated error and relevant inbound SSE context before the existing return.
Preserve the non-fatal early-return behavior and use the surrounding logger and
established safe unknown-error conversion conventions.

Source: Coding guidelines


224-232: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Document the onSessionExpired vs onUncaughtError ordering assumption.

isOptionalHttpInboundSseError treats a GET-SSE failure as optional only when holder.sessionExpired is still false at the point onUncaughtError runs. The HTTP transport design clears the session before surfacing the 404-based session error, but the explicit ordering guarantee does not apply broadly to all onUncaughtError deliveries. Add a short inline note around observeHttpSessionExpiration so future readers keep this implementation dependency visible.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/core/src/mcp/registry.ts` around lines 224 - 232, Add a short inline
comment near observeHttpSessionExpiration documenting that the HTTP transport
clears the session before onUncaughtError handles the 404-based session error,
while this ordering is not a general onUncaughtError guarantee. Keep the
existing isOptionalHttpInboundSseError logic unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/core/src/mcp/registry.ts`:
- Around line 38-43: Add an acceptance test covering the schema represented by
optionalHttpInboundSseErrorSchema, asserting MCPClientError messages must start
with the exact “MCP HTTP Transport Error: GET SSE failed:” prefix and that a
changed prefix is rejected. Keep the existing statusCode and url validation
unchanged.

---

Nitpick comments:
In `@apps/core/src/mcp/registry.ts`:
- Around line 565-569: In the handler around isOptionalHttpInboundSseError, add
a debug- or trace-level log containing the tolerated error and relevant inbound
SSE context before the existing return. Preserve the non-fatal early-return
behavior and use the surrounding logger and established safe unknown-error
conversion conventions.
- Around line 224-232: Add a short inline comment near
observeHttpSessionExpiration documenting that the HTTP transport clears the
session before onUncaughtError handles the 404-based session error, while this
ordering is not a general onUncaughtError guarantee. Keep the existing
isOptionalHttpInboundSseError logic unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8d3ad5aa-c439-45c6-9317-e8c3d4e9f492

📥 Commits

Reviewing files that changed from the base of the PR and between 8aac906 and 6ecfba8.

📒 Files selected for processing (2)
  • apps/core/src/mcp/registry.ts
  • apps/core/tests/mcp/registry.test.ts

Comment on lines +38 to +43
const optionalHttpInboundSseErrorSchema = z.object({
name: z.literal("MCPClientError"),
message: z.string().startsWith("MCP HTTP Transport Error: GET SSE failed:"),
statusCode: z.number().int(),
url: z.string(),
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Does @ai-sdk/mcp MCPClientError expose a request phase or kind field to distinguish GET SSE stream errors from POST request errors, or only statusCode/url/responseBody?

💡 Result:

No, the @ai-sdk/mcp MCPClientError class does not expose a "request phase kind" field to explicitly distinguish between GET (SSE stream) and POST request errors [1][2]. As of the current implementation, the MCPClientError class exposes the following properties [1][2]: - data: Optional data payload from the error (e.g., from the server's JSON-RPC error response) [1][3]. - code: Optional JSON-RPC error code [1]. - statusCode: Optional HTTP status code, if the error originated from an HTTP transport failure [1][4]. - url: Optional URL of the endpoint that failed [1][4]. - responseBody: Optional body of the failed HTTP response [1][4]. These fields (specifically statusCode, url, and responseBody) were added to provide structured HTTP context for HTTP transport failures, allowing consumers to make decisions based on the HTTP status without needing to parse error message strings [4][5]. However, the class does not include a specific field designed to identify the transport phase (e.g., distinguishing an initial SSE connection/GET request from a tool invocation/POST request) [1][2].

Citations:


Pin the GET-SSE message match to avoid silent behavior change.

@ai-sdk/mcp does not expose a stable request-kind discriminator for MCPClientError; statusCode, url, and responseBody do not distinguish GET-SSE stream failures from POST failures. Add an acceptance test for the exact message.startsWith("MCP HTTP Transport Error: GET SSE failed:") string so a library text change fails CI instead of silently changing whether failures are tolerated.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/core/src/mcp/registry.ts` around lines 38 - 43, Add an acceptance test
covering the schema represented by optionalHttpInboundSseErrorSchema, asserting
MCPClientError messages must start with the exact “MCP HTTP Transport Error: GET
SSE failed:” prefix and that a changed prefix is rejected. Keep the existing
statusCode and url validation unchanged.

@stanley2058
stanley2058 merged commit 570bddc into main Aug 1, 2026
3 checks passed
@stanley2058
stanley2058 deleted the fix/native-http-mcp-inbound-sse branch August 1, 2026 10:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants