Skip to content

fix: connect OAuth MCP servers from chat without stopping the Gateway - #200538

Merged
obviyus merged 3 commits into
mainfrom
fix/mcp-online-oauth-login
Nov 17, 2026
Merged

obviyus merged 3 commits into
mainfrom
fix/mcp-online-oauth-login

Conversation

@obviyus

@obviyus obviyus commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

When you ask your agent to connect an OAuth MCP server (for example Linear), it cannot. openclaw mcp login refuses while the Gateway runs, Settings sign-in only works from a browser, and the agent never learns the server is waiting for sign-in. In practice the agent tells you to stop the Gateway, which takes the agent itself offline.

User Impact

User impact: say "connect Linear" in a direct chat, get a sign-in link in the same reply, approve it, and the next message uses Linear. Nothing stops or restarts. openclaw mcp login and logout now work while the Gateway runs; with the Gateway stopped they keep their existing offline flow. Saving servers from the agent already goes through the running Gateway; routing the mcp add/set/configure CLI commands online is a separate follow-up.

Security boundary: only the owner can start a shared sign-in, only in a direct chat that has not handled untrusted content, and the link is never posted in a group. Admin Gateway clients (Control UI, local CLI) can also start it. Without gateway.publicOrigin, the redirect uses the Gateway's loopback address; on another device you paste the failed redirect URL back. The code is single-use and bound to the original state and PKCE verifier. Existing credentials stay until new ones are saved.

Why This Change Was Made

The running Gateway already owns MCP credentials (SQLite lease on mcp_oauth_stores) and already serves /oauth/mcp/callback. It is now also the one owner of shared sign-in:

  • mcp.authLogin gains a link mode ({ serverName, callbackUrl? }) beside the browser-bound Settings mode. Same method, same admin check, no new method.
  • /oauth/mcp/callback also completes shared attempts, but only ones started in link mode; Settings attempts stay bound to their browser.
  • The CLI routes login/logout to the running Gateway instead of refusing.
  • An account first signed in through a different callback (offline CLI loopback or Settings) is not silently broken: a link refuses to renew it, keeps the saved credentials, and names openclaw mcp logout <name> or offline sign-in.
  • Owner turns get <server>__connect for unauthorized shared servers, and the openclaw tool accepts connectMcpServer to return the link in the same reply. The tool now says which parts of a request were not done instead of reporting success.
  • Docs: docs/cli/mcp/transports.md and docs/tools/mcp.md no longer contradict each other.

Protocol change: mcp.authLogin params become a union; existing callers that send sessionId are unchanged. No schema or stored-format change; no new config option.

Evidence

Control UI, isolated Gateway with a real model and an OAuth MCP fixture. Before: 2 turns, no link, the agent says the Gateway needs an offline window. After: the link arrives in turn 1 (1 min 53 s), approval shows "You're connected.", openclaw mcp status reports authorized, and the next turn calls the server's tool. The Gateway log shows only config hot reloads, no stop or restart.

Clean comparison

Before (main) and after (this branch). Same prompt, same fixture server; the user avatar is blurred.

Before: the agent did not add the server and refused to start sign-in while the Gateway runs

After: turn 1 adds the server and returns a sign-in link

After: the Gateway callback page confirms the connection

After: the next turn calls the MCP tool and lists the issues

Annotated comparison

Before, annotated: turn 1 not added, turn 2 refused because the Gateway must go offline

After, annotated: sign-in link in turn 1

After, annotated: next turn calls the MCP tool and returns issues

Telegram DM (real Telegram test server, real model, owner chat). The bot replied in turn 1 with a Connect fixture-issues button; approval reached the Gateway callback (HTTP 200, "You're connected."); the next message produced "Connected successfully. Your assigned issues: FIX-101 … FIX-102" and the fixture recorded the tool call. When the chat was not yet the owner, the bot refused and posted no link.

Regression tests, red on main and green here: CLI login/logout against a live Gateway (main refuses with "requires exclusive offline state ownership"), link mode and pasted-redirect completion (main rejects without sessionId), the owner connect tool without a sender ID, the openclaw tool returning the link only after the Gateway applies the committed server, and the pinned-client refusal that keeps saved credentials. New test lines are covered by config/test-lines-allocations/200538-mcp-online-oauth-login.txt (373): one regression per owning boundary, plus the mcp.authLogin harness moved to test-support to stay under the 1000-line test cap.

Upgrade from 2026.11.4: credentials saved by the stable CLI stay authorized after starting this branch on the same state.

Simplification: login/logout moved into the existing OAuth CLI module (mcp-cli.ts is smaller than on main), owner sign-in into its own small agent module, and add/configure flag helpers into mcp-cli-server-controls.ts. Production growth is the link-mode owner (mcp-oauth-link.ts), the connect surface, and CLI routing.

Known gaps
  • The Claude CLI loopback runner has no turn-taint signal, so it gets no connect tool and no delegate link; it fails closed. Embedded and Codex runtimes are covered.
  • Discord was not run; Telegram was the channel proof.
  • Separate, pre-existing on main: with an exec or file SecretRef in config, Gateway startup on state written by 2026.11.4 fails with required secrets are unavailable … disk I/O error. The upgrade proof above used a config without SecretRefs. Not caused by this change.

- mcp.authLogin gains a browserless link mode: returns the authorization URL or
  completes a pasted redirect. Settings sign-in stays browser-bound.
- /oauth/mcp/callback completes shared link-mode attempts.
- openclaw mcp login/logout and add/set/unset/configure/tools route to the running
  Gateway; offline paths remain for a stopped Gateway.
- Accepted config changes clear replaced or removed OAuth credentials for every writer.
- Owner, untainted, direct turns get <server>__connect for unauthorized shared servers;
  the openclaw tool accepts connectMcpServer and reports unfinished parts.
- Docs describe online sign-in consistently.
@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@obviyus

obviyus commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Proof screenshots (Control UI, isolated Gateway, synthetic OAuth MCP fixture; avatars blurred).

Before: the agent did not add the server and refused to start sign-in while the Gateway runs

After: turn 1 adds the server and returns a sign-in link

After: the Gateway callback page confirms the connection

After: the next turn calls the MCP tool and lists the issues

Before, annotated: turn 1 not added, turn 2 refused because the Gateway must go offline

After, annotated: sign-in link in turn 1

After, annotated: next turn calls the MCP tool and returns issues

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime cli CLI command changes agents Agent runtime and tooling extensions: codex size: XL labels Nov 17, 2026
@obviyus
obviyus marked this pull request as ready for review November 17, 2026 09:50
@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: a831cb98dbf3da44dd1c77abccff7ede61c603a7
  • Maintainer: @obviyus
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/mcp-oauth-identity.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/mcp-oauth-link.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/mcp-oauth-provider.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/gateway/mcp-oauth-callback.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server-methods/mcp-auth-login.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server/ws-connection/connect-hello.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 17, 2026
@clawsweeper

clawsweeper Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR adds Gateway-owned OAuth sign-in links for chat and routes MCP CLI mutations through the running Gateway.

Example: An owner asks a direct-chat agent to connect Linear.

  • Before: The agent cannot start shared OAuth without stopping its own Gateway.
  • After: The agent returns a sign-in link, and a subsequent message can use Linear after approval.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The central sign-in flow has credible product proof, but the probe custody regression and confirmed consumer-test failure need correction.
Proof confidence 🐚 platinum hermit (4/6) ✨ media proof bonus Sufficient (screenshot): Inspected Control UI captures exercise chat setup, link delivery, browser callback completion, and a subsequent authenticated MCP tool call; the body records a real Telegram owner-DM exchange and stable-release credential preservation.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: An agent cannot complete shared MCP sign-in when the prescribed terminal recovery requires stopping the Gateway hosting that agent.
Reason: The maintainer-authored direction removes a demonstrated recovery dead end while retaining the existing credential owner and human OAuth consent.

Merge readiness

⛔ Needs changes before merge - 3 items remain

Keep this PR open: it provides useful, maintainer-approved online sign-in, but regresses Docker pre-save probes and leaves an existing logout contract test failing.

Priority: P2
Reviewed head: 1d552cc5b38332af1dbefef165f945ba1bd407cc

Before merge

  • Acquire state ownership before running pre-save probes (P2) - Removing the enclosing offlineMcpAction leaves this probe before setMcpServer acquires or routes ownership. With the Gateway stopped, adding a Docker-wrapped stdio server now reaches prepareMcpDockerLaunch without a captured state owner and fails with “Docker MCP custody requires exclusive OpenClaw state ownership,” so configuration is never saved. configure --probe has the same regression. Keep probes within the existing custody boundary, with any online probe executed by the Gateway owner; the existing Docker custody E2E already covers both offline commands.
  • Update the live-owner logout test for owner routing (P2) - Logout now dispatches mcp.authLogout to the running owner, but this unchanged table still requires an offline-only refusal and no dispatch. The exact-head CI annotation confirms this case fails at line 539. Move logout out of the refusal table and exercise its owner-routed contract, retaining assertions that the CLI performs no local mutation.
  • Explain or restore the original intent of Docker pre-save probes - ff2580a: Docker launches retain state custody through startup and exact-container cleanup, including add and configure probes.

Findings

  • [P2] Acquire state ownership before running pre-save probes — src/cli/mcp-cli.ts:888-893
  • [P2] Update the live-owner logout test for owner routing — src/cli/local-state-owner.process.test.ts:528-529

Provenance

  • Docker pre-save probes changes intended behavior without addressing why it exists (ff2580a: Docker launches retain state custody through startup and exact-container cleanup, including add and configure probes.)

Tests

  • Low-value test src/system-agent/operations.test.ts: Remove the added exact-copy assertion for the fixed “Completed only config.setRef” log sentence; it pins wording without proving that the model reports partially completed requests accurately.
Agent review details

How this fits together

Agent tools and administrative clients initiate sign-in through the existing OAuth owner; the Gateway callback saves credentials that subsequent MCP requests consume.

flowchart TD
A[Owner direct chat] --> B[Agent connect tools]
C[Administrative clients] --> D[Gateway OAuth owner]
B --> D
D --> E[OAuth provider]
E --> F[Gateway callback]
F --> G[Existing credential store]
G --> B
Loading

Technical review

Best possible solution:

Keep Gateway-owned sign-in, restore ownership around pre-save probes, and update the existing logout routing test.

Do we have a high-confidence way to reproduce the issue?

Current-main source establishes the offline-only refusal, consistent with the supplied before capture and published-release report; no target code was executed during this review.

Is this the best way to solve the issue?

Reusing the OAuth owner, callback, and credential store is appropriate; the smallest repair preserves that design while restoring probe custody and migrating the affected logout test.

Full review comments:

  • [P2] Acquire state ownership before running pre-save probes — src/cli/mcp-cli.ts:888-893
    Removing the enclosing offlineMcpAction leaves this probe before setMcpServer acquires or routes ownership. With the Gateway stopped, adding a Docker-wrapped stdio server now reaches prepareMcpDockerLaunch without a captured state owner and fails with “Docker MCP custody requires exclusive OpenClaw state ownership,” so configuration is never saved. configure --probe has the same regression. Keep probes within the existing custody boundary, with any online probe executed by the Gateway owner; the existing Docker custody E2E already covers both offline commands.
    Confidence: 0.99
  • [P2] Update the live-owner logout test for owner routing — src/cli/local-state-owner.process.test.ts:528-529
    Logout now dispatches mcp.authLogout to the running owner, but this unchanged table still requires an offline-only refusal and no dispatch. The exact-head CI annotation confirms this case fails at line 539. Move logout out of the refusal table and exercise its owner-routed contract, retaining assertions that the CLI performs no local mutation.
    Confidence: 1

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against c48b8293ae67.

Provenance checked

  • CLI state ownership changes intended behavior with a stated reason (510255d: Prevent CLI credential writes from competing with the running Gateway; the PR deliberately replaces refusal with Gateway routing.)
  • Settings browser sign-in keeps the original intent (2a48569: Provide browser-bound administrative sign-in using the existing credential owner; the sessionId branch remains browser-bound.)
  • Requester OAuth and credential cleanup keeps the original intent (6a4a546: Keep requester identities separate, correlate callbacks with single-use state, and retire credentials when their server identity is removed or replaced.)
  • Issuer verification keeps the original intent (6f483d3: Preserve the provider's authorization-response issuer through callback completion rather than weakening issuer verification.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit 2a48569 adds src/gateway/server-methods/mcp-auth-login.ts:24 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 2a48569bfbb8; files: src/gateway/server-methods/mcp-auth-login.ts)
  • Peter Steinberger: Raw commit 3588d39 adds src/agents/mcp-config-mutation.ts:33 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 3588d397fea0; files: src/agents/mcp-config-mutation.ts)
  • Patrick Erichsen: Raw commit 6f483d3 adds src/gateway/server-methods/mcp-auth-login.ts:20 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 6f483d3932b2; files: src/gateway/server-methods/mcp-auth-login.ts)

PR surface

Source +651, Tests +836, Docs +10. Total +1497 across 42 files. Added test files: 3.

View PR surface stats
Area Files Added Removed Net
Source 26 5205 4554 +651
Tests 11 1220 384 +836
Docs 5 32 22 +10
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 42 6457 4960 +1497

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Authored production versus tests Production +893/-254; tests and support +1220/-384 Excludes documentation and generated predicates; production growth implements shared link sign-in and owner routing, while test growth covers distinct authentication and CLI boundaries.
Added controls 1 CLI flag, 1 agent-tool parameter, 1 RPC mode Adds --callback-url, connectMcpServer, and the sessionless mcp.authLogin request shape.

Root-cause cluster

Relationship: same_root_cause
Canonical: #199151
Summary: The related report establishes the same CLI ownership refusal; this PR changes the runtime while the documentation proposal explains the existing restriction.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add P2: The improvement is useful, and the demonstrated regression affects advanced Docker MCP configuration commands.
  • add merge-risk: 🚨 compatibility: Existing offline Docker add and configure --probe commands lose the custody their transport requires.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🐚 platinum hermit and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: The improvement is useful, and the demonstrated regression affects advanced Docker MCP configuration commands.
  • merge-risk: 🚨 compatibility: Existing offline Docker add and configure --probe commands lose the custody their transport requires.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🐚 platinum hermit and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: sufficient: Contributor real behavior proof is sufficient.
  • proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 17, 2026, 5:09 AM ET / 10:09 UTC.

- Leave mcp add/set/unset/configure/tools on their offline path; online config
  writes move to a follow-up so add probes keep Docker custody.
- A sign-in link refuses to renew a client registered for another callback and
  names logout or offline sign-in, leaving saved credentials untouched.
- Move add/configure flag helpers to mcp-cli-server-controls.ts (line cap).
- Fix consistent-return in logout, typed test snapshots, the lock payload mock,
  and drop the retired live logout refusal case.
- Record the test-line allocation for the new regressions.
- Covers the pinned-client regression moved into the infra lane.
@obviyus
obviyus merged commit bdd7cd5 into main Nov 17, 2026
177 checks passed
@obviyus
obviyus deleted the fix/mcp-online-oauth-login branch November 17, 2026 11:23
@obviyus

obviyus commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in bdd7cd5.

  • Bug: connecting an OAuth MCP server needed the Gateway stopped or a browser on Settings; agents could not produce a sign-in link and told users to take the Gateway offline.
  • Fix: the running Gateway owns shared sign-in. mcp.authLogin link mode returns the authorization URL, /oauth/mcp/callback completes it, the CLI routes login/logout online, and owner direct chats get the link in the same reply.
  • Proof: Control UI and Telegram DM end to end with a real model (link in turn 1, authorized after approval, tool called on the next turn, no Gateway restart), red-on-main regressions, the packed Bun smoke, an upgrade from 2026.11.4 keeping saved credentials, and a clean local review on this head.

Follow-up: routing openclaw mcp add/set/configure/tools through the running Gateway (with probes kept under offline custody) ships separately.

obviyus added a commit that referenced this pull request Nov 17, 2026
…ay (#200582)

Related: #200538

## What Problem This Solves

`openclaw mcp add`, `set`, `unset`, `configure` and `tools` refuse to run while the Gateway is running and tell you to stop it first. That blocks an operator, or an agent with shell access, from adding an MCP server to a live Gateway, even though the same change through `openclaw config set` already works online.

## User Impact

User impact: you can add or change saved MCP servers with `openclaw mcp …` while the Gateway runs; changes apply without a restart. Commands that probe a server first (`mcp add` by default for non-OAuth servers, and `mcp configure --probe`) still need the Gateway stopped, and now say so with the next step: save without probing (`--no-probe`). OAuth servers skip the probe, so `openclaw mcp add linear --url … --auth oauth` followed by `openclaw mcp login linear` works end to end on a running Gateway. With the Gateway stopped, every command behaves as before.

Replacing or removing an OAuth server now clears its old saved sign-in no matter how the change was made: CLI, agent, Settings editor, or a hand edit of `openclaw.json`. Previously only the offline CLI did this, so an online change could leave a stale account attached to a new URL. A Gateway restart alone clears nothing.

## Why This Change Was Made

The running Gateway is the one config writer. The MCP CLI prepares the same normalized change it would write offline and hands it to the Gateway with the existing config-owner binding, the path `openclaw config set` already uses. Probes are different: they launch the server (Docker launches need exclusive state custody) and can refresh credentials, so the probing path keeps loading, probing and saving inside one offline custody scope, as on main.

Credential cleanup moves to the owner that sees every committed change: when the Gateway accepts a new source config, it compares the previous and next MCP servers and clears OAuth credentials for servers whose definition changed or disappeared, using the existing per-server lifecycle lease and the same rule the offline CLI already applied. The offline facade skips its own cleanup when a running Gateway owns config writes, so nothing is cleared twice.

No schema, protocol, or config-option change.

## Evidence

- **Online routing (process test with a real Gateway owner):** `mcp set`, `configure`, `tools`, `unset` and `add --no-probe` each go through the running Gateway and the Gateway stays up; `mcp add` with its default probe refuses with "Probing a server needs the Gateway stopped" and saves nothing. On main every one of these refuses.
- **Credential cleanup (same harness):** an online URL replacement, a removal, and an in-process agent write each clear the stored OAuth credentials; an unchanged OAuth identity keeps them. On main the online cases keep stale credentials.
- **Probe custody regression:** a probing `mcp add` runs its probe while holding state ownership, which is what Docker launches require. This is the defect the review caught in the earlier attempt (#200538).
- Focused suites, typecheck, lint, line-cap and test-line ratchets pass; the full build with declarations and the packed Bun install smoke pass.

<details><summary>Known local-only flake</summary>

`src/cli/mcp-cli.test.ts` "requires initialize to finish within the configured probe timeout" fails on the development host under heavy load on unmodified main as well, and passes in CI. This PR does not change that path.

</details>

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
…openclaw#200538)

## What Problem This Solves

When you ask your agent to connect an OAuth MCP server (for example Linear), it cannot. `openclaw mcp login` refuses while the Gateway runs, Settings sign-in only works from a browser, and the agent never learns the server is waiting for sign-in. In practice the agent tells you to stop the Gateway, which takes the agent itself offline.

## User Impact

User impact: say "connect Linear" in a direct chat, get a sign-in link in the same reply, approve it, and the next message uses Linear. Nothing stops or restarts. `openclaw mcp login` and `logout` now work while the Gateway runs; with the Gateway stopped they keep their existing offline flow. Saving servers from the agent already goes through the running Gateway; routing the `mcp add/set/configure` CLI commands online is a separate follow-up.

Security boundary: only the owner can start a shared sign-in, only in a direct chat that has not handled untrusted content, and the link is never posted in a group. Admin Gateway clients (Control UI, local CLI) can also start it. Without `gateway.publicOrigin`, the redirect uses the Gateway's loopback address; on another device you paste the failed redirect URL back. The code is single-use and bound to the original state and PKCE verifier. Existing credentials stay until new ones are saved.

## Why This Change Was Made

The running Gateway already owns MCP credentials (SQLite lease on `mcp_oauth_stores`) and already serves `/oauth/mcp/callback`. It is now also the one owner of shared sign-in:

- `mcp.authLogin` gains a link mode (`{ serverName, callbackUrl? }`) beside the browser-bound Settings mode. Same method, same admin check, no new method.
- `/oauth/mcp/callback` also completes shared attempts, but only ones started in link mode; Settings attempts stay bound to their browser.
- The CLI routes login/logout to the running Gateway instead of refusing.
- An account first signed in through a different callback (offline CLI loopback or Settings) is not silently broken: a link refuses to renew it, keeps the saved credentials, and names `openclaw mcp logout <name>` or offline sign-in.
- Owner turns get `<server>__connect` for unauthorized shared servers, and the `openclaw` tool accepts `connectMcpServer` to return the link in the same reply. The tool now says which parts of a request were not done instead of reporting success.
- Docs: `docs/cli/mcp/transports.md` and `docs/tools/mcp.md` no longer contradict each other.

Protocol change: `mcp.authLogin` params become a union; existing callers that send `sessionId` are unchanged. No schema or stored-format change; no new config option.

## Evidence

**Control UI, isolated Gateway with a real model and an OAuth MCP fixture.** Before: 2 turns, no link, the agent says the Gateway needs an offline window. After: the link arrives in turn 1 (1 min 53 s), approval shows "You're connected.", `openclaw mcp status` reports `authorized`, and the next turn calls the server's tool. The Gateway log shows only config hot reloads, no stop or restart.

### Clean comparison

Before (main) and after (this branch). Same prompt, same fixture server; the user avatar is blurred.

![Before: the agent did not add the server and refused to start sign-in while the Gateway runs](https://github.com/user-attachments/assets/6f5af2e0-8c79-4fc6-978b-ca1db81a9754)

![After: turn 1 adds the server and returns a sign-in link](https://github.com/user-attachments/assets/0d15afb0-6020-442f-ba79-fa728436c659)

![After: the Gateway callback page confirms the connection](https://github.com/user-attachments/assets/4feb1b63-4258-45ec-a426-1f259e5b8ec9)

![After: the next turn calls the MCP tool and lists the issues](https://github.com/user-attachments/assets/a379c89e-4787-4372-a13a-3e90ce7ba265)

### Annotated comparison

![Before, annotated: turn 1 not added, turn 2 refused because the Gateway must go offline](https://github.com/user-attachments/assets/79d72990-7a1b-4895-a5cb-b05c186b72a9)

![After, annotated: sign-in link in turn 1](https://github.com/user-attachments/assets/d87a06f8-e7f7-49ca-9129-0bc15c8af274)

![After, annotated: next turn calls the MCP tool and returns issues](https://github.com/user-attachments/assets/c17d92cc-8459-4786-96f1-d6c47a9a404e)

**Telegram DM (real Telegram test server, real model, owner chat).** The bot replied in turn 1 with a **Connect fixture-issues** button; approval reached the Gateway callback (HTTP 200, "You're connected."); the next message produced "Connected successfully. Your assigned issues: FIX-101 … FIX-102" and the fixture recorded the tool call. When the chat was not yet the owner, the bot refused and posted no link.

**Regression tests, red on main and green here:** CLI login/logout against a live Gateway (main refuses with "requires exclusive offline state ownership"), link mode and pasted-redirect completion (main rejects without `sessionId`), the owner connect tool without a sender ID, the `openclaw` tool returning the link only after the Gateway applies the committed server, and the pinned-client refusal that keeps saved credentials. New test lines are covered by `config/test-lines-allocations/200538-mcp-online-oauth-login.txt` (373): one regression per owning boundary, plus the `mcp.authLogin` harness moved to test-support to stay under the 1000-line test cap.

**Upgrade from 2026.11.4:** credentials saved by the stable CLI stay `authorized` after starting this branch on the same state.

**Simplification:** login/logout moved into the existing OAuth CLI module (`mcp-cli.ts` is smaller than on main), owner sign-in into its own small agent module, and add/configure flag helpers into `mcp-cli-server-controls.ts`. Production growth is the link-mode owner (`mcp-oauth-link.ts`), the connect surface, and CLI routing.

<details><summary>Known gaps</summary>

- The Claude CLI loopback runner has no turn-taint signal, so it gets no connect tool and no delegate link; it fails closed. Embedded and Codex runtimes are covered.
- Discord was not run; Telegram was the channel proof.
- Separate, pre-existing on main: with an exec or file SecretRef in config, Gateway startup on state written by 2026.11.4 fails with `required secrets are unavailable … disk I/O error`. The upgrade proof above used a config without SecretRefs. Not caused by this change.

</details>

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
…ay (openclaw#200582)

Related: openclaw#200538

## What Problem This Solves

`openclaw mcp add`, `set`, `unset`, `configure` and `tools` refuse to run while the Gateway is running and tell you to stop it first. That blocks an operator, or an agent with shell access, from adding an MCP server to a live Gateway, even though the same change through `openclaw config set` already works online.

## User Impact

User impact: you can add or change saved MCP servers with `openclaw mcp …` while the Gateway runs; changes apply without a restart. Commands that probe a server first (`mcp add` by default for non-OAuth servers, and `mcp configure --probe`) still need the Gateway stopped, and now say so with the next step: save without probing (`--no-probe`). OAuth servers skip the probe, so `openclaw mcp add linear --url … --auth oauth` followed by `openclaw mcp login linear` works end to end on a running Gateway. With the Gateway stopped, every command behaves as before.

Replacing or removing an OAuth server now clears its old saved sign-in no matter how the change was made: CLI, agent, Settings editor, or a hand edit of `openclaw.json`. Previously only the offline CLI did this, so an online change could leave a stale account attached to a new URL. A Gateway restart alone clears nothing.

## Why This Change Was Made

The running Gateway is the one config writer. The MCP CLI prepares the same normalized change it would write offline and hands it to the Gateway with the existing config-owner binding, the path `openclaw config set` already uses. Probes are different: they launch the server (Docker launches need exclusive state custody) and can refresh credentials, so the probing path keeps loading, probing and saving inside one offline custody scope, as on main.

Credential cleanup moves to the owner that sees every committed change: when the Gateway accepts a new source config, it compares the previous and next MCP servers and clears OAuth credentials for servers whose definition changed or disappeared, using the existing per-server lifecycle lease and the same rule the offline CLI already applied. The offline facade skips its own cleanup when a running Gateway owns config writes, so nothing is cleared twice.

No schema, protocol, or config-option change.

## Evidence

- **Online routing (process test with a real Gateway owner):** `mcp set`, `configure`, `tools`, `unset` and `add --no-probe` each go through the running Gateway and the Gateway stays up; `mcp add` with its default probe refuses with "Probing a server needs the Gateway stopped" and saves nothing. On main every one of these refuses.
- **Credential cleanup (same harness):** an online URL replacement, a removal, and an in-process agent write each clear the stored OAuth credentials; an unchanged OAuth identity keeps them. On main the online cases keep stale credentials.
- **Probe custody regression:** a probing `mcp add` runs its probe while holding state ownership, which is what Docker launches require. This is the defect the review caught in the earlier attempt (openclaw#200538).
- Focused suites, typecheck, lint, line-cap and test-line ratchets pass; the full build with declarations and the packed Bun install smoke pass.

<details><summary>Known local-only flake</summary>

`src/cli/mcp-cli.test.ts` "requires initialize to finish within the configured probe timeout" fails on the development host under heavy load on unmodified main as well, and passes in CI. This PR does not change that path.

</details>

Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 19, 2026
…ay (#200582)

Related: #200538

`openclaw mcp add`, `set`, `unset`, `configure` and `tools` refuse to run while the Gateway is running and tell you to stop it first. That blocks an operator, or an agent with shell access, from adding an MCP server to a live Gateway, even though the same change through `openclaw config set` already works online.

User impact: you can add or change saved MCP servers with `openclaw mcp …` while the Gateway runs; changes apply without a restart. Commands that probe a server first (`mcp add` by default for non-OAuth servers, and `mcp configure --probe`) still need the Gateway stopped, and now say so with the next step: save without probing (`--no-probe`). OAuth servers skip the probe, so `openclaw mcp add linear --url … --auth oauth` followed by `openclaw mcp login linear` works end to end on a running Gateway. With the Gateway stopped, every command behaves as before.

Replacing or removing an OAuth server now clears its old saved sign-in no matter how the change was made: CLI, agent, Settings editor, or a hand edit of `openclaw.json`. Previously only the offline CLI did this, so an online change could leave a stale account attached to a new URL. A Gateway restart alone clears nothing.

The running Gateway is the one config writer. The MCP CLI prepares the same normalized change it would write offline and hands it to the Gateway with the existing config-owner binding, the path `openclaw config set` already uses. Probes are different: they launch the server (Docker launches need exclusive state custody) and can refresh credentials, so the probing path keeps loading, probing and saving inside one offline custody scope, as on main.

Credential cleanup moves to the owner that sees every committed change: when the Gateway accepts a new source config, it compares the previous and next MCP servers and clears OAuth credentials for servers whose definition changed or disappeared, using the existing per-server lifecycle lease and the same rule the offline CLI already applied. The offline facade skips its own cleanup when a running Gateway owns config writes, so nothing is cleared twice.

No schema, protocol, or config-option change.

- **Online routing (process test with a real Gateway owner):** `mcp set`, `configure`, `tools`, `unset` and `add --no-probe` each go through the running Gateway and the Gateway stays up; `mcp add` with its default probe refuses with "Probing a server needs the Gateway stopped" and saves nothing. On main every one of these refuses.
- **Credential cleanup (same harness):** an online URL replacement, a removal, and an in-process agent write each clear the stored OAuth credentials; an unchanged OAuth identity keeps them. On main the online cases keep stale credentials.
- **Probe custody regression:** a probing `mcp add` runs its probe while holding state ownership, which is what Docker launches require. This is the defect the review caught in the earlier attempt (#200538).
- Focused suites, typecheck, lint, line-cap and test-line ratchets pass; the full build with declarations and the packed Bun install smoke pass.

<details><summary>Known local-only flake</summary>

`src/cli/mcp-cli.test.ts` "requires initialize to finish within the configured probe timeout" fails on the development host under heavy load on unmodified main as well, and passes in CI. This PR does not change that path.

</details>

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 6e38d6d)

Release adaptation: retain the release baseline inline MCP control helpers and OAuth registration; apply online routing and revision-bound configure callbacks without restoring the later extracted controls module. Companion #200538 is superseded by this complete fix.

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 4038419d371c8d583a010a152b4b957b8931c66b)
IstiqlalBhat added a commit to IstiqlalBhat/openclaw-upstream that referenced this pull request Nov 20, 2026
The Gateway-backed login branch added in openclaw#200538 printed the authorization
URL through the redacting console logger, so a JWT-shaped client_id was
masked there as well. Write it straight to stdout like the offline flow.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui cli CLI command changes docs Improvements or additions to documentation extensions: codex gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. security-sensitive-changed size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant