Repository navigation
fix(mcp): settle the /mcp auth wait when bearer auth writes the response - #353
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
No actionable comments were generated in the recent review.
|
| 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:
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
#371covers 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: 
4 · 
1
-
Failed checks: 1 warning Passed checks: 4 passed -
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.
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.
There was a problem hiding this comment.
🟡 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
finishorclose. - Preserves successful-auth and
headersSentbehavior.
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.
|
|
||
| await new Promise<void>((resolve, reject) => { | ||
| res.once("finish", resolve); | ||
| res.once("close", resolve); |
There was a problem hiding this comment.
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.
7705cb5 to
0ecfe74
Compare
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
|
Closes #354. |
Greptile SummaryThe Confidence Score: 5/5Safe 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.
What T-Rex did
Reviews (1): Last reviewed commit: 7705cb5 | Re-trigger Greptile |
Waishnav
left a comment
There was a problem hiding this comment.
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?
|
QA on this head: |
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Problem
app.all("/mcp")waits forbearerAuthlike this:The SDK's
requireBearerAuthmiddleware only callsnext()on success. On 401/403/400 it writes the response itself and returns without callingnext, so the Promise above never settles. Every rejected request leaves the handler continuation,reqandresreachable 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/mcpis 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.headersSentshort-circuit still applies).Verification
tsc --noEmitcleansrc/server-oauth.test.tsandsrc/server.test.tspass (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