Skip to content

feat(mcp): run OAuth MCP installs from the app server - #404

Merged
hieptl merged 42 commits into
mainfrom
hieptl/ohe-3249
Sep 21, 2026
Merged

hieptl merged 42 commits into
mainfrom
hieptl/ohe-3249

Conversation

@hieptl

@hieptl hieptl commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

HUMAN:

  • A human has tested these changes.

AGENT:


Why

Installing an OAuth-based MCP server (Atlassian Rovo, GitLab, Figma, Google Drive and ~20 more catalog entries) fails on every hosted deployment. Agent Canvas opens a window and immediately reports "OAuth authorization requires a reachable local backend."

The flow was only ever built for a local agent-server. Its OAuth client publishes a loopback redirect URI, http://localhost:<random port>/callback, and serves that callback from its own process (_BrowserCoordinatedOAuth in openhands/agent_server/mcp_router.py; _validate_callback_url accepts loopback hosts only). When the backend is the app server, that URI points at the user's own machine, so the provider's redirect never reaches the process waiting for the code. There was no app-server equivalent to point it at: POST /api/v1/mcp/test (#366) deliberately declines OAuth servers, and no other MCP route exists.

Tracked as OHE-3249, with the original design in OHE-2619 / #52. This is the app-server half; Agent Canvas and the SDK are separate PRs (see Notes).

Summary

  • Add openhands/app_server/mcp/mcp_oauth_router.py with three routes. POST /api/v1/mcp/oauth/start validates the candidate server exactly like POST /api/v1/mcp/test (redacted-secret restore, remote transports only, SSRF guard), then runs the SDK probe on a worker thread with a FastMCP OAuth client whose redirect URI is this server's own public callback, and answers with the provider's authorization URL. GET /api/v1/mcp/oauth/status/{job_id} reports progress and, on success, the OAuth state the caller persists in settings; unknown, expired and other users' jobs are indistinguishable 404s. GET /api/v1/mcp/oauth/callback receives the provider's redirect and hands the code to the waiting probe.
  • Keep job state in Redis under a 15-minute TTL (mcp_oauth:job:{id} plus a single-use mcp_oauth:state:{state} pointer) so the callback and the status polls can land on any replica while the probe thread stays on the one that started it. The stored probe result carries OAuth tokens and is encrypted at rest with the app server's JWT service.
  • Allowlist /api/v1/mcp/oauth/callback in SetAuthCookieMiddleware: the provider's redirect is a cross-site navigation and production cookies are SameSite=strict, so it arrives with no session cookie. The route is authorized by the single-use state the MCP client generates, never by a cookie, and it returns only a static "you can close this window" page.
  • Extract the request preparation shared with the connection-test route into prepare_probe_request; POST /api/v1/mcp/test behaviour is unchanged.

Issue Number

https://linear.app/all-hands-ai/issue/OHE-3249/bug-oauth-based-mcp-installation-fails-in-hosted-environment

How to Test

  1. Unit tests and type checking:

    uv sync --all-groups --frozen
    uv run pytest -q tests/unit/app_server/test_mcp_oauth_router.py \
                     tests/unit/app_server/test_mcp_test_router.py \
                     tests/unit/test_auth_middleware.py     # 42 passed
    uv run pre-commit run --config ./dev_config/python/.pre-commit-config.yaml \
      --files openhands/app_server/mcp/mcp_oauth_router.py \
              openhands/app_server/mcp/mcp_test_router.py \
              openhands/app_server/v1_router.py server/middleware.py \
              tests/unit/app_server/test_mcp_oauth_router.py \
              tests/unit/test_auth_middleware.py            # all hooks pass, incl. mypy

    test_mcp_oauth_router.py drives the whole handshake against fakes: start publishes the authorization URL, the callback delivers the code to the probe, status returns the tools and OAuth state, the result is stored encrypted, the state is single-use, a provider ?error= is recorded on the job, non-OAuth servers are rejected, and jobs are scoped to their owner. test_auth_middleware.py pins the callback bypassing the cookie middleware.

  2. Against a running app server, as a signed-in user. The callback must be reachable from the browser, so web_url has to be public (OH_WEB_URL or WEB_HOST; a tunnel works for local runs) and Redis must be up.

    POST /api/v1/mcp/oauth/start with body:

    {"name": "atlassian",
     "server": {"url": "https://mcp.atlassian.com/v1/mcp/authv2", "auth": {"strategy": "oauth2"}},
     "timeout": 120}

    It answers {"ok": true, "job_id": "...", "authorization_url": "https://mcp.atlassian.com/v1/authorize?..."}. Open that URL in a browser and approve. The provider redirects to /api/v1/mcp/oauth/callback, which renders "Authorization complete. You can close this window." Then GET /api/v1/mcp/oauth/status/{job_id} returns {"ok": true, "status": "succeeded", "tools": [...], "oauth_state": {...}}.

    Reloading the callback URL a second time returns the expired-link page, and requesting the job as a different user returns 404.

  3. End to end from Agent Canvas once the companion Canvas PR is deployed alongside this: Customize → MCP servers → Atlassian Rovo → Install.

Not done: I have not yet run step 2 against a real provider, so the live Atlassian handshake is unverified. Atlassian's published metadata does advertise dynamic client registration, PKCE S256, the none client-auth method and the refresh-token grant, so the non-loopback redirect URI is protocol-legal, but it wants confirming before release.

Video/Screenshots

None yet: the live provider run described above is still outstanding, and the rest of the change has no UI of its own.

Type

  • Bug fix
  • Feature
  • Refactor
  • Breaking change
  • Docs / chore

Notes

  • Ships with two companion PRs: one in OpenHands/OpenHands pointing Agent Canvas at these routes on cloud backends, and one in OpenHands/software-agent-sdk letting a sandbox use OAuth credentials captured this way. Links added in a comment once both are open. This PR is safe to merge on its own: nothing calls the routes until Canvas ships.
  • Rollout needs a public web_url. When it is unset or points at localhost the start route answers with a structured failure rather than handing the provider an unreachable redirect URI. Redis is already a hard dependency of the app server; if it is unavailable the routes return 503 rather than degrading silently.
  • The redirect URI is registered per install through dynamic client registration, so no provider-side configuration is required.
  • Deliberately no server-side preflight GET of the authorization URL (FastMCP's client does one by default) to avoid adding an outbound-request surface; the MCP URL itself still goes through the _check_probe_target SSRF guard.
  • The consent window is bounded by the request timeout, capped at 120s by the SDK model, because the SDK wraps the whole probe in anyio.fail_after. Canvas sends the maximum. Lifting that needs an SDK change and is tracked separately.
  • Follow-ups, recorded on OHE-2619: tokens refreshed inside a sandbox are not written back here, which matters for providers with rotating refresh tokens; and POST /api/v1/mcp/test still declines OAuth servers, so the health card's manual retry reports "cannot be tested" for them while re-authorize works.

Enterprise server image for this PR:

ghcr.io/openhands/enterprise-server:sha-c2d9a13

FraterCCCLXIII and others added 30 commits August 12, 2026 17:14
Wire agent-canvas-style --oh-* / cool-grey tokens, AgentServerUIRoot, and neo palette application so the SaaS shell can share the same theme foundation.

Co-authored-by: Cursor <cursoragent@cursor.com>
Port agent-canvas layout utilities so settings-like pages can reuse the same form, list, and sidebar spacing classes.

Co-authored-by: Cursor <cursoragent@cursor.com>
Match agent-canvas settings chrome with tokenized nav links, logo header, bottom user menu, and settings-owned gutters.

Co-authored-by: Cursor <cursoragent@cursor.com>
Restyle org management, members list, and git org rows with shared settings list/form tokens and updated mocks/tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
Replace hardcoded greys with base/surface/muted/primary tokens so budgets and usage monitoring match agent-canvas.

Co-authored-by: Cursor <cursoragent@cursor.com>
Update spinners, badges, chips, context menus, and related shell controls to use --oh-* / muted tokens instead of hardcoded greys.

Co-authored-by: Cursor <cursoragent@cursor.com>
Use neo toast tokens, custom CircleX error layout, loading helper, and route call sites through the shared handlers.

Co-authored-by: Cursor <cursoragent@cursor.com>
Replace the pill toast chrome with agent-canvas-aligned surface, border, radius, and status icon colors.

Co-authored-by: Cursor <cursoragent@cursor.com>
Track remaining hardcoded hex surfaces for follow-up tokenization work.

Co-authored-by: Cursor <cursoragent@cursor.com>
Restyle the settings rail (sidebar, drawer, white brand mark), forms, integrations, and related surfaces to match OpenHands-Neo tokens and agent-canvas patterns.

Co-authored-by: Cursor <cursoragent@cursor.com>
Clarify Personal settings as org-scoped (This org chip), fold Integrations
and Skills into that section, and move User/Application to the bottom.
Continue settings shell, credits, MCP, and chrome alignment.

Co-authored-by: Cursor <cursoragent@cursor.com>
Improve loading skeleton fidelity and stagger, and let non-searchable
dropdowns click-open/click-close like other selects.

Co-authored-by: Cursor <cursoragent@cursor.com>
Override the shared fixed list-row height and keep the Default badge
inline with the profile name so stacked mobile content no longer
overflows the overflow-hidden profiles list.

Co-authored-by: Cursor <cursoragent@cursor.com>
Update frontend tests for neo chrome (toasts, dropdowns, budgets, git settings) and show the org-wide badge on budgets/credits.

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
…hell

Resolve conflicts with main (#167 null balance, #176 dropdown search term,
#199 quota nav item) and align the merged result with the neo settings shell:

- credits/payment: keep main's null balance -> "no budget limit" semantics
- settings nav: add the Quota entry (subline + icon) and tokenize the quota
  page with the shared form-control helpers
- settings loader: fall back to the backend's current org after a hard load
  so /settings/credits stays reachable
- integrations: style the Jira member-guidance row like the other rows
- tests: move the no-limit credits test with the credits UI; drop the
  legacy-sidebar avatar E2E spec (the sidebar no longer renders)
Agent Canvas is served at /canvas next to the enterprise app, so the root
route (and therefore the default post-login destination) should open it
rather than the settings shell.

- replace the settings index redirect with a landing route that does a
  document-level replace to /canvas (a router redirect would bounce
  through the SPA's own canvas/* route and leave / in history)
- keep the route inside the root layout so auth, guards and the
  login_method callback still run before leaving the app
- keep invitation links (/?invitation_token=...) in the settings shell
  so the token is captured and auto-accepted instead of dropped
Resolve conflicts in the settings screens:

- app-settings: keep main's GPG key button/modal and its removal of the
  legacy max-budget control, while retaining the design-update styling
  for the git settings section and the form footer.
- api-keys-manager: keep both sides' imports so main's LLM key export
  gating (useConfig) works alongside the redesigned list/form styling.
- api-keys-manager test: match the refresh control by accessible name,
  since the redesigned manager renders it as an icon button.
Resolved conflict in frontend/src/routes/quota-settings.tsx: kept main's
replacement of the in-app quota increase form with the external request
link, applied on top of the design-update styling of the quota screen.
…gs nav (#307)

The settings-nav user menu rendered UserAvatar without the git user's
avatar_url or fetch state, so it always showed the placeholder icon even
when a profile picture was available. This restores the wiring dropped in
77bb8f2, matching the legacy sidebar: show the picture when present, the
placeholder otherwise, and a spinner while the profile is being fetched.

Extend the user-menu tests to cover the avatar, placeholder, and loading
states.
# Conflicts:
#	frontend/src/components/features/budgets/budgets-tabs.tsx
#	frontend/src/routes/git-settings.tsx
… unlimited (#343)

The Quota entry in the Settings navigation rendered for every SaaS-mode
deployment, including self-hosted enterprise installs where no daily
conversation limit is configured. The page then only showed "Unlimited"
plus a request-increase link.

Gate the nav item on the quota status: hide it when `daily_limit` is
null, keep it whenever a finite limit is in effect. The status query is
only enabled in SaaS mode so OSS builds never call the enterprise-only
endpoint from the navigation hook.

Includes regression tests for both the configured-limit and unlimited
cases.
…irects (#342)

Loader redirects in the settings shell (the ?org= strip, the /settings ->
/settings/org-defaults hop and the permission fallback) were history
pushes, so entering Settings from Agent Canvas in the same tab and
pressing Back re-ran the loader and bounced forward again. They now use
React Router's replace() so one Back returns to the canvas.
hieptl and others added 10 commits September 10, 2026 22:56
* feat: add Test connection for MCP servers on cloud backends

* fix(mcp): harden the MCP test route and type its request body

Address review feedback on POST /api/v1/mcp/test:

- Reject probe targets that must never be reached from the app-server pod:
  only http/https URLs are accepted, and hosts that resolve to loopback,
  link-local (instance metadata), unspecified, multicast or reserved
  addresses, including IPv4-mapped IPv6 forms, are refused with 422.
  Private networks stay reachable because self-hosted deployments run
  their MCP servers there. MCP_TEST_ALLOW_LOCAL_TARGETS=true disables the
  address check for local development. The threat model is documented in
  the module docstring.
- Accept a typed MCPTestRequestBody so the OpenAPI schema documents the
  request and FastAPI validates the top-level fields; the server entry
  stays an untyped map so redacted secrets can be restored before the SDK
  validates it.
- Walk the secret dumps with zip(strict=True) and also scrub URL-encoded
  and JSON-escaped forms of restored secrets from the response text.
- Require a server URL explicitly in the frontend test hook and document
  the request type.
- Cover the new target guard, encoded-secret scrubbing, every failure
  kind's message, and the disabled buttons while a test is pending.

* chore: Remove PR-only artifacts [automated]

* chore: restore the design-update PR artifact this branch deleted

The "PR Artifacts" workflow's cleanup-on-approval job runs `git rm -rf .pr/`
on approval, so approving this PR deleted `.pr/neo-theme-component-audit.md`
(commit 1fcc5a4). That file is design-update's, inherited from the base
branch, not an artifact of this PR, and deleting it is unrelated to the MCP
test route. Restore it from design-update.

---------

Co-authored-by: allhands-bot <allhands-bot@users.noreply.github.com>
OAuth-based MCP servers (Atlassian Rovo, GitLab, Figma and ~20 more catalog
entries) could only be installed against a local agent-server. Its OAuth
client publishes a loopback redirect URI, http://localhost:<port>/callback,
and serves that callback from its own process, so a browser talking to a
hosted backend can never complete the handshake. Agent Canvas refused the
install outright with "OAuth authorization requires a reachable local
backend."

Add the hosted counterpart:

- POST /api/v1/mcp/oauth/start validates the candidate server exactly like
  POST /api/v1/mcp/test (redacted-secret restore, remote transports only,
  SSRF guard), then runs the SDK probe on a worker thread with an OAuth
  client whose redirect URI is this server's own public callback, and
  answers with the provider's authorization URL.
- GET /api/v1/mcp/oauth/status/{job_id} reports progress and, on success,
  the OAuth state the caller persists in settings. Unknown, expired and
  other users' jobs are indistinguishable 404s.
- GET /api/v1/mcp/oauth/callback receives the provider's redirect and hands
  the authorization code to the waiting probe. It is unauthenticated and
  allowlisted in SetAuthCookieMiddleware because the cross-site navigation
  carries no session cookie (production cookies are SameSite=strict); the
  single-use state parameter generated by the MCP client identifies the job.

Jobs live in Redis under a 15-minute TTL so the callback and the status polls
can land on any app server replica while the probe thread stays on the
replica that started it. The stored probe result carries OAuth tokens and is
encrypted at rest with the app server's JWT service.

Request preparation shared with the connection-test route moves into
prepare_probe_request; POST /api/v1/mcp/test behaviour is unchanged.

Part of OHE-3249.
@github-actions github-actions Bot added the type: feat A new feature label Sep 15, 2026
@hieptl

hieptl commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

Companion PRs, both open:

Merge order: this PR, then the Canvas one once it is deployed; the SDK change is independent but has to ship in an agent-server release and sandbox image before hosted conversations can use the captured tokens.

@github-actions

github-actions Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Coverage report

Click to see where and how coverage changed

FileStatementsMissingCoverageCoverage
(new stmts)
Lines missing
  openhands/app_server
  v1_router.py
  openhands/app_server/mcp
  mcp_oauth_router.py 111, 115, 119-121, 125-127, 131-133, 140-147, 151, 157-161, 165-173, 180-188, 192-197, 208-222, 257-263, 273-283, 291-300, 327-356, 367-368, 372-379, 385-409, 419-420, 427-438, 461-502, 521-522, 528-540, 553-588
  mcp_test_router.py 242, 257, 280-288, 310-314, 322-324
  server
  middleware.py
Project Total  

This report was generated by python-coverage-comment-action

@hieptl hieptl self-assigned this Sep 15, 2026
Base automatically changed from design-update to main September 18, 2026 18:28
# Conflicts:
#	frontend/src/components/features/settings/secrets-settings/secret-list-item.tsx
#	frontend/src/routes/secrets-settings.tsx
#	openhands/app_server/mcp/mcp_test_router.py
#	openhands/app_server/v1_router.py
@github-actions

Copy link
Copy Markdown
Contributor

📁 PR Artifacts Notice

This PR contains a .pr/ directory with PR-specific documents. This directory will be automatically removed when the PR is approved.

For fork PRs: Manual removal is required before merging.

@tofarr tofarr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Remove the .pr - I don't think it actually applies to these changes.

@tofarr tofarr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🍰

@hieptl
hieptl merged commit 4a72414 into main Sep 21, 2026
16 checks passed
@hieptl
hieptl deleted the hieptl/ohe-3249 branch September 21, 2026 15:49
@openhands-release-bot openhands-release-bot Bot added the released: 1.63.0 Shipped in 1.63.0 label Sep 22, 2026
@openhands-release-bot

Copy link
Copy Markdown
Contributor

🚀 Released in 1.63.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released: 1.63.0 Shipped in 1.63.0 type: feat A new feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants