Skip to content

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

Open
yulin0629 wants to merge 1 commit into
Waishnav:mainfrom
yulin0629:fix/mcp-auth-promise
Open

yulin0629 wants to merge 1 commit into
Waishnav:mainfrom
yulin0629:fix/mcp-auth-promise

Conversation

@yulin0629

@yulin0629 yulin0629 commented Sep 15, 2026

Copy link
Copy Markdown

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
    • Improved request handling so authentication processing completes when a response finishes or closes, preventing requests from remaining pending.

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 Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 03491764-79e6-4d4b-b29e-b782d5fcfcea

📥 Commits

Reviewing files that changed from the base of the PR and between 3ee2b1e and 7705cb5.

📒 Files selected for processing (1)
  • src/server.ts

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


📝 Walkthrough

Walkthrough

The /mcp route now resolves the bearer-auth wrapper promise when the response emits finish or close, in addition to the bearer-auth callback.

Changes

MCP response lifecycle

Layer / File(s) Summary
Response event resolution
src/server.ts
The /mcp route adds one-time finish and close listeners that resolve the bearer-auth wrapper promise.

Priority: ⬇️ Low

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

Change: Bug fix · Severity of issue fixed: Low

Suggested reviewers: waishnav

Merge Risk: ⚪ Minimal · up to 0ecfe

The change is narrowly scoped, and reported compilation and server tests pass without an established merge-blocking failure.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ 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 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 identifies the MCP authentication fix and describes the response-settlement behavior changed in the pull request.
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 PR with unit tests

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 watched the response flow
finish and close now signal “go”
The auth promise no longer waits
It hops past unfinished states
And lands where completion grows

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);
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
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?

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