Skip to content

fix(mcp): settle the /mcp auth wait when bearer auth writes the response - #353

Merged
Waishnav merged 2 commits into
Waishnav:mainfrom
yulin0629:fix/mcp-auth-promise
Oct 26, 2026
Merged

Waishnav merged 2 commits into
Waishnav:mainfrom
yulin0629:fix/mcp-auth-promise

Conversation

@yulin0629

@yulin0629 yulin0629 commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Problem

app.all("/mcp") waits for bearerAuth like this:

await new Promise<void>((resolve, reject) => {
  bearerAuth(req, res, (error?: unknown) => { if (error) reject(error); else resolve(); });
});

The SDK's requireBearerAuth middleware only calls next() on success. On 401/403/400 it writes the response itself and returns without calling next, so the Promise above never settles. Every rejected request leaves the handler continuation, req and res reachable for the lifetime of the process. Clients see a normal 401, so nothing looks wrong; the daemon just grows a little on each bad token, which matters once /mcp is on a public hostname.

Fix

Also resolve when the response finishes or closes, so a request that the middleware rejects releases its handler. Behaviour on success is unchanged (res.headersSent short-circuit still applies).

Verification

  • tsc --noEmit clean
  • src/server-oauth.test.ts and src/server.test.ts pass (23/23)

Found while running a fork of DevSpace with a static bearer path in front of the same middleware; the bug itself is independent of that change.

Summary by CodeRabbit

  • Bug Fixes
    • Authentication requests now stop processing if the client disconnects or the response is no longer available.
    • Requests are no longer left waiting when the response finishes or closes before authentication completes.

Copilot AI lite review requested due to automatic review settings September 15, 2026 06:57
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 15, 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-09-15T06:59:54.798925Z 7705cb5 PR opened
ℹ️ 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.

@coderabbitai

coderabbitai Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: aebbab82-eca9-460d-9ce3-a216fe2ac7f1
Commits

Reviewing files that changed from the base of the PR and between 0ecfe74 and 8310d79.

Files selected for processing: 1
  • src/server.ts

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

Walkthrough

The /mcp handler now resolves its bearer-authentication wait when the response finishes or closes. After authentication, it returns if headers were sent or the response was destroyed.

Changes: MCP response lifecycle

Layer / File(s) Summary
Response lifecycle and authentication
src/server.ts
The handler resolves the authentication wait on response finish or close. After authentication, it returns if headers were sent or the response was destroyed.

Priority: Low

Estimated code review effort: 1 (Trivial) | ~5 minutes

Change: Bug fix

Possibly related PRs

  • Waishnav/devspace#371: Both changes address MCP HTTP connection lifecycle. PR #371 covers keep-alive, request abort, and shutdown behavior.

Suggested reviewers: waishnav

Merge Risk: Minimal · up to 8310d

The MCP authentication wait handles response completion and disconnects correctly, so no merge-blocking risk remains.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 1 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 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: settling the /mcp authentication wait when bearer authentication writes the response.
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 unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

A rabbit checks the response stream,
finish and close complete the wait.
If the connection has been destroyed,
The handler stops before it writes.
Then off the rabbit hops, ears bright.

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

Copilot AI 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.

🟡 Changes recommended

The response-close path can continue to the MCP handler before bearer authentication has completed.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Updates /mcp bearer-auth handling so rejected requests do not leave the authentication wait pending.

Changes:

  • Settles the auth wait on response finish or close.
  • Preserves successful-auth and headersSent behavior.
File summaries
File Description
src/server.ts Adds response lifecycle listeners around bearer authentication; the close path requires a guard before continuation.
Review details
  • Files reviewed: 1/1 changed files
  • Comments generated: 1
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/server.ts

await new Promise<void>((resolve, reject) => {
res.once("finish", resolve);
res.once("close", resolve);

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Checked this against the PR head. It isn't an auth bypass: if close resolves the wait before requireBearerAuth finishes, req.auth is still unset, so the req.auth?.resource guard returns 401 before mcpNodeHandler runs. A later next() from the middleware only re-resolves a promise that has already settled.

It does leave one wrinkle, though: an aborted request is logged as auth_denied / invalid_oauth_resource and writes a 401 to a closed socket. @yulin0629, could you record the close and return early? Something like:

let closed = false;
await new Promise<void>((resolve, reject) => {
  res.once("finish", resolve);
  res.once("close", () => { closed = true; resolve(); });
  bearerAuth(req, res, (error?: unknown) => (error ? reject(error) : resolve()));
});
if (closed || res.headersSent) return;

A small test would help too: abort an /mcp request while token verification is pending, then assert that the next request still succeeds and that no auth_denied is logged. With that change, this is good to merge.

requireBearerAuth answers 401/403 itself and never calls next(), so the
Promise wrapping it in the /mcp handler never settled on auth failure and
kept req/res reachable for the life of the process. Resolve on the
response's finish/close as well, so a rejected request releases its
handler continuation.
yulin0629 added a commit to yulin0629/devspace that referenced this pull request Sep 15, 2026
Settle the /mcp auth Promise on response finish/close so rejected
requests no longer keep req/res reachable (same change as upstream
PR Waishnav#353).

AI-Agent: Claude Code
AI-Session-IDs: e7e89df6-478d-4f15-96bd-1f65cb4d4566
@yulin0629

Copy link
Copy Markdown
Contributor Author

Closes #354.

@greptile-apps

greptile-apps Bot commented Sep 15, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

The /mcp bearer-authentication wait now completes when authentication middleware ends a request with a 401, 403, or 400 response without calling next(). The surrounding MCP server and OAuth behavior remains covered by passing focused tests.

Confidence Score: 5/5

Safe to merge: the affected bearer-authentication lifecycle completes correctly while preserving denied-request responses.

No actionable findings remain. Runtime coverage exercised invalid-token, insufficient-scope, and malformed-request denial paths, and the focused MCP server and OAuth tests passed.

Files Needing Attention: None.

T-Rex T-Rex Logs

What T-Rex did

  • Exercised the /mcp bearer-auth wait with real terminating 401, 403, and 400 middleware responses.
  • Observed that the updated behavior preserved the same denial responses and settled every continuation.
  • Ran the before/after runtime scripts and the focused test suite, which completed with 23 passing tests.
  • Validated that after lifecycle listeners are present, 401 (invalid_token), 403 (insufficient_scope), and 400 (invalid_request) responses produce continuationSettled: true; without them, the status remains false.
  • Cross-checked the before/after artifacts and test outputs to confirm the changes were exercised and results captured in the provided logs.

View all artifacts

T-Rex Ran code and verified through T-Rex

Reviews (1): Last reviewed commit: 7705cb5 | Re-trigger Greptile

@Waishnav Waishnav left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Thanks for catching the unresolved auth wait — that part is real. I don’t think we should fix it by resolving on finish/close, though.

requireBearerAuth is already Express middleware, so the simpler and safer fix is to compose it directly:

app.all("/mcp", bearerAuth, async (req, res) => {
  // existing MCP route logic
});

That removes the manual Promise entirely. It also avoids the close race where the route can resume before token verification has completed.

I also wasn’t able to reproduce the claimed permanent per-request memory leak: the pending continuation becomes unreachable and the request objects were collectible after GC. So I’d describe the bug as incorrect/unnecessary async control flow rather than a confirmed process-lifetime leak.

Could you rework this PR around native Express middleware composition instead?

@Waishnav

Copy link
Copy Markdown
Owner

QA on this head: pnpm typecheck, pnpm test, and pnpm build passed. All three built-in replay scenarios passed, and I reviewed their rendered pages. The Windows Smoke failure is the known koffi package-install issue tracked by #403; macOS and Ubuntu Smoke passed. Existing HTTP auth coverage still returns 401; this PR does not add a regression test for the response-finish wait.

QA screenshot

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Waishnav
Waishnav merged commit 3dcc002 into Waishnav:main Oct 26, 2026
1 check passed
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.

3 participants