Repository navigation
fix(mcp): relay the OAuth callback when the redirect cannot reach the backend - #16545
SimiPrambos wants to merge 2 commits into
Conversation
… backend
MCP OAuth fails whenever the browser cannot reach the agent-server's
loopback interface. The agent-server starts its callback listener on a
random port; in Docker that port lives inside the container, so the
provider's redirect to the host browser dies with ERR_CONNECTION_REFUSED
and the OAuth job never completes.
The agent-server already accepts an out-of-band relay at
POST /api/mcp/oauth/callback/{job_id} and fetches that URL from inside
its own network namespace. McpService.submitOAuthCallback already
wrapped the endpoint, but nothing in the UI ever called it.
authorizeOAuth now hands the probe job id to its caller, and a new
OauthCallbackFallback lets the user paste the URL their browser failed
to load. It is wired into the add/edit modal, the install modal, and the
reauthorize action. The browser cannot read the failed popup's URL
itself -- it is cross-origin, with no readable document after a
connection error -- so a manual copy is the only workable trigger.
Client-side validation stays deliberately loose (http + loopback host):
the agent-server pins scheme, host, port and path to the values its own
job generated, and returns a specific message this UI surfaces inline.
The interactive wait moves to a separate 300s budget so a hand-pasted
URL fits, and the OAuth modal is no longer undismissable while it runs.
Closes OpenHands#15430
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
✅ Mock-LLM E2E Tests62/62 passed Commit: Details
Posted by the Mock-LLM E2E workflow · results are deterministic (scripted LLM responses) |
|
🚦 CI is currently failing on this PR's latest commit. Please fix the failing checks before OpenHands reviews it - this is re-checked automatically once you push a new commit. (A maintainer can also request This is an automated check - no AI was used to generate this comment. |
|
PR Artifacts Notice This PR contains a |
|
@SimiPrambos Nice work :-) Two things I noticed while testing it:
The new comment on ModalBackdrop says there's nothing to orphan beyond the backend job, but that isn't quite true. authorizeOAuth has no abort, so after the modal closes the poll keeps going. If the user then finishes consent in the popup anyway, the .then in handleSubmit still calls addMcpServer / updateMcpServer, and the server gets saved even though they walked away. The editor has unmounted by then, so if that save fails the user never sees an error. React Query skips the per-call onError once the observer has no listeners, and the hooks don't define their own. To be fair, the Cancel button could already do this before the PR (it's only disabled on isPending). This PR adds Escape, backdrop click and the close button on top, though, and the comment makes it look intentional. I think we should either cancel the flow when the modal closes (an abort signal into authorizeOAuth, or at least ignore the result once it's unmounted), or keep dismiss blocked while isOauthTesting is true.
extractCallbackErrorMessage checks error instanceof AxiosError, but submitOAuthCallback goes through the typescript-client MCPClient, which uses fetch and throws HttpError. On that error the body is at error.response.detail, not error.response.data.detail. So a 400 like "Unexpected OAuth callback URL" ends up displayed as the raw HTTP request failed (400 Bad Request): {"detail":"Unexpected OAuth callback URL"}. The test passes because it mocks an AxiosError, which this client never throws. There's already an isSdkHttpError helper in src/api/agent-server-compatibility.ts that should work here, and the test should mock an HttpError instead. |
all-hands-bot
left a comment
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
Scope check: frontend-only fix in the correct repository. The relay endpoint POST /api/mcp/oauth/callback/{job_id} already lives in software-agent-sdk, and this PR only supplies the missing browser half plus UI wiring — that is Agent Canvas work. A manual paste is a defensible trigger, since the failed popup is cross-origin and has no readable document.
Verification on head 4181c36:
- Focused tests pass:
npx vitest runon the 5 changed test files (oauth-callback-fallback, custom-server-editor, install-server-modal, mcp-server-health, mcp-service.api) → 54 passed. - CI:
test-and-build (ubuntu)andtest-and-build (windows)pass.Validate PR descriptionfails on this exact head with:None of the linked issues (#15430) carry the ready-for-dev label. Issue #15430 currently carries onlybug,docker,mcp— no readiness label. That is the repository's own pre-merge gate (.github/workflows/pr-description-check.yml), so a maintainer/label action is required before merge. - Live evidence: the HUMAN Docker reproduction against a real provider plus the attached video satisfy the UI before/after evidence requirement.
Two correctness findings, detailed inline:
-
extractCallbackErrorMessagecan never match in production.submitOAuthCallbackgoes throughMCPClient→ the sharedHttpClient, which usesfetchand throwsHttpError, notAxiosError. So the whole point of the helper — surfacing the backend'sdetailinstead ofHTTP request failed (400 …)— is not achieved, and the new test passes only because it mocks a shape this call path never produces. -
Dropping
isOauthTestingfromisDismissBlockedmakes the modal dismissible mid-OAuth, but the in-flightauthorizeOAuthis not aborted, so completing consent after dismissing still persists the server, and a failing save goes unreported. The comment claiming "there is nothing to orphan" is inaccurate.
🔄 CHANGES REQUESTED
| */ | ||
| function extractCallbackErrorMessage(error: unknown): string { | ||
| if ( | ||
| error instanceof AxiosError && |
There was a problem hiding this comment.
submitOAuthCallback reaches the agent-server through MCPClient → the shared HttpClient, which uses fetch and throws HttpError (name: "HttpError", parsed body directly on error.response). It never throws an AxiosError, so error instanceof AxiosError is false on every real rejection. The fallback retrieveAxiosErrorMessage then treats HttpError as a plain Error and returns error.message, i.e. the user sees HTTP request failed (400 Bad Request): {"detail":"Unexpected OAuth callback URL"} instead of the backend's detail — exactly the behaviour this helper was added to prevent. The new test passes only because it constructs an AxiosError, a shape this call path never produces.
Smallest fix: use the existing getApiErrorMessage(error, fallback) from #/utils/api-error-message.ts, which already reads message/detail from both transports (error.response for HttpError, error.response.data for axios), and update the test to reject with an HttpError-shaped error, e.g. Object.assign(new Error("HTTP request failed"), { name: "HttpError", status: 400, response: { detail: "Unexpected OAuth callback URL" } }).
| // Deliberately excludes `isOauthTesting`: that wait is interactive (the user | ||
| // is off in a provider popup, for up to 300s) and abandoning it must stay | ||
| // possible. See the ModalBackdrop comment below. | ||
| const isDismissBlocked = isPending || isTesting || showDeleteConfirm; |
There was a problem hiding this comment.
authorizeOAuth is awaited and has no abort path, so closing the modal here does not abandon the flow. McpService.authorizeOAuth(...).then(...) is still pending, and when the user finishes consent in the popup the .then runs addMcpServer/updateMcpServer with onSuccess: onSaved → onClose(). The server is persisted after the user walked away.
If that save then fails, handleError is supplied as the mutation's per-call onError, and @tanstack/query-core's MutationObserver.#notify only invokes #mutateOptions.onError when hasListeners() is true (verified in the installed 5.101.4 build). After unmount the observer is gone, so the toast never fires and the failure is silent.
The comment above this line — "there is nothing to orphan beyond a backend job that times out on its own" — is therefore not accurate. Either thread an AbortSignal into authorizeOAuth and stop polling/saving on unmount, or ignore the resolved result once the editor has unmounted, or keep dismissal blocked while isOauthTesting is true.
|
Thanks for working on this and for reproducing it in Docker. The maintainers' direction for #15430 and #18888 is to make normal browser authorization complete, without a manual relay step. #19744 together with OpenHands/software-agent-sdk#6221 does that: the agent-server registers a redirect URI on the URL the browser already uses ( This comment/PR was created by an AI agent (OpenHands) on behalf of Graham Neubig. |
HUMAN:
I reproduced this in Docker with only
-p 8000:8000published, using Attlasian Rovo.The OAuth redirect failed with
ERR_CONNECTION_REFUSEDexactly as described in theissue #15430, because the callback port lives inside the container. With this change I
copied the URL from the failed tab, pasted it into the "Redirect didn't work?"
field, and the flow completed, the server saved and mcp connected.
AGENT:
Implementation was done with Claude Code; the end-to-end Docker verification
against a live OAuth provider was done by the human contributor — see the HUMAN
section and Video/Screenshots.
Automated verification on this branch:
Why
MCP OAuth cannot complete whenever the browser can't reach the agent-server's
loopback interface. The agent-server drives the handshake through FastMCP,
whose callback handler starts an HTTP listener on a random port and
registers
http://localhost:<port>/callbackas the redirect URI.In Docker that listener lives inside the container while the OAuth provider
redirects the host browser to it, and the image publishes only port 8000 —
so the redirect dies with
ERR_CONNECTION_REFUSED, the authorization codenever reaches the agent-server, and the status poll times out. The same failure
hits any deployment where the browser can't reach that loopback interface,
including remote and SSH-tunnelled backends.
The agent-server already supports an out-of-band relay:
POST /api/mcp/oauth/callback/{job_id}accepts a callback URL and fetches itfrom inside its own network namespace, where the port is reachable.
McpService.submitOAuthCallbackalready wrapped that endpoint — but nothing inthe UI ever called it. This PR supplies the missing browser half.
The browser can't read the failed popup's URL on its own: it's cross-origin,
and after a connection error there's no readable document. A manual copy is the
only workable trigger.
Summary
McpService.authorizeOAuthaccepts an optionalonJobStartedcallback thathands the OAuth probe job id to the UI; the return type is unchanged, so the
existing single-argument call sites are unaffected.
OauthCallbackFallback— a collapsed "Redirect didn't work?" disclosurethat relays a pasted callback URL through the existing endpoint. Wired into
the add/edit modal, the install modal, and the reauthorize action (token
expiry is the most common way an existing install hits this).
the add/edit modal is no longer undismissable while that wait runs.
Issue Number
Closes #15430
How to Test
-p 8000:8000.(the GitLab MCP server is the reported case).
ERR_CONNECTION_REFUSED— that's the environment, not the bug.Without this PR, step 4 has no UI at all and the flow dead-ends.
Video/Screenshots
screen-recording-2026-08-12-at-152500_1oswFNwo.mp4
Type
Notes
No new SSRF surface. The relayed URL is fetched server-side, but the
agent-server's
_validate_callback_urlalready pins the scheme tohttp, thehost to loopback, and both port and path to the values that job itself
generated. Client-side validation is deliberately looser than the server's
(scheme + loopback host only): pinning the path or requiring a
codeparam inthe browser would assert knowledge the browser doesn't have, and would reject
provider denial redirects (
?error=access_denied) that are useful to relay sothe backend can fail the job immediately instead of burning the full wait.
The 300s wait matches the agent-server's own
callback_timeoutinsoftware-agent-sdk(
openhands-agent-server/openhands/agent_server/mcp_router.py,_BrowserCoordinatedOAuth.callback_handler). It is a separate constant:OAUTH_MCP_TEST_TIMEOUT_SECONDSis untouched because it also sets HTTP clienttimeouts. Raising the interactive wait also exposed that the add/edit modal
blocked Escape, backdrop click and its close button for the whole duration, so
that modal is now dismissable while OAuth is pending — matching what the install
modal already did.
Error text. The shared
retrieveAxiosErrorMessagereadserror/messagebut not FastAPI's
detail, so backend rejections surfaced as "Request failed".A small file-local helper in the new component reads
detailfirst and fallsback to the shared util. Kept local since no other module needs it today;
happy to promote it to
src/utils/type-guards.tsif you'd prefer.Translations. The two new prose keys were machine-translated into the 14
non-English locales. Corrections from native speakers are very welcome — they
are
MCP$OAUTH_CALLBACK_FALLBACK_LABELandMCP$OAUTH_CALLBACK_INVALID_URL.The URL placeholder is a technical example and is allowlisted in
IDENTICAL_VALUE_ALLOWLIST, matching the existing MCP OAuth placeholders.Not addressed here: making the agent-server bind a fixed callback port. That
lives in
software-agent-sdk, needs a coordinated release, and would still failfor anyone who doesn't publish the port — so this fix is deliberately
frontend-only and works for every unreachable-loopback deployment.
Jev-Fast-Audit
⚡ Jev fast audit · estimates · 0.54s · commit 4181c36⚠️ reduced context — partial coverage; 30/33 hunks, 15/15 files (context budget: 29, hunk budget: 3).
Strongest signal: No primary concern selected.
Evidence: No primary concern to locate.
Coverage:
All estimates and evidence