@myrialabs/clopen 0.4.2 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +2 -0
  2. package/backend/auth/permissions.ts +4 -1
  3. package/backend/chat/stream-manager.ts +7 -1
  4. package/backend/database/migrations/041_add_mcp_config_schema.ts +16 -0
  5. package/backend/database/migrations/042_add_mcp_oauth.ts +20 -0
  6. package/backend/database/migrations/043_relocate_engine_config_dirs.ts +71 -0
  7. package/backend/database/migrations/index.ts +21 -0
  8. package/backend/database/queries/index.ts +1 -1
  9. package/backend/database/queries/mcp-server-queries.ts +42 -2
  10. package/backend/engine/README.md +12 -8
  11. package/backend/engine/adapters/claude/environment.ts +3 -3
  12. package/backend/engine/adapters/codex/credential.ts +6 -2
  13. package/backend/engine/adapters/codex/stream.ts +6 -0
  14. package/backend/engine/adapters/copilot/stream.ts +5 -1
  15. package/backend/engine/adapters/opencode/server.ts +57 -21
  16. package/backend/engine/adapters/qwen/environment.ts +7 -0
  17. package/backend/engine/adapters/qwen/session-fork.ts +13 -1
  18. package/backend/engine/docs/adding-an-engine.md +8 -0
  19. package/backend/engine/docs/database.md +9 -6
  20. package/backend/engine/docs/lessons-learned.md +177 -16
  21. package/backend/git/git-service.ts +21 -2
  22. package/backend/index.ts +23 -1
  23. package/backend/mcp/README.md +81 -0
  24. package/backend/mcp/external/config.ts +70 -14
  25. package/backend/mcp/external/oauth.ts +329 -0
  26. package/backend/mcp/external/probe.ts +308 -0
  27. package/backend/mcp/external/registry-client.ts +8 -1
  28. package/backend/mcp/index.ts +12 -1
  29. package/backend/mcp/internal/config.ts +6 -0
  30. package/backend/mcp/internal/remote-server.test.ts +14 -0
  31. package/backend/mcp/internal/remote-server.ts +8 -0
  32. package/backend/mcp/internal/service-token.ts +51 -0
  33. package/backend/utils/paths.ts +16 -0
  34. package/backend/ws/engine/codex/accounts.ts +3 -0
  35. package/backend/ws/git/remote.ts +3 -2
  36. package/backend/ws/mcp/crud.ts +131 -12
  37. package/dist/assets/{main-qT_RedHf.js → main-AqTMkV9D.js} +272 -266
  38. package/dist/assets/main-DJf71Zum.css +1 -0
  39. package/dist/index.html +2 -2
  40. package/package.json +1 -1
  41. package/dist/assets/main-DKLZPDUN.css +0 -1
@@ -94,16 +94,19 @@ getProvidersWithAccounts(engineType?) // join used by endpoint listing
94
94
  see `streamQuery` in `copilot/stream.ts` and §9.9 below.
95
95
 
96
96
  > **Pattern: auth-blob materialization for shared CLI dotfiles.**
97
- > Some CLIs (e.g. Codex's `~/.codex/auth.json`) read credentials from a
98
- > fixed location on disk that **cannot** be redirected per-process without
99
- > isolating the entire home dir. For those engines, `credential` stores
100
- > the **whole file content** as a JSON wrapper
97
+ > Some CLIs (e.g. Codex's `auth.json`) read credentials from a fixed
98
+ > filename inside their home dir. That home dir is isolated to
99
+ > `{clopenDir}/engine/codex/user/` (via `CODEX_HOME` — see §9.19), but it is a
100
+ > **single** dir shared by all of the engine's Clopen accounts, so the
101
+ > dotfile inside it still has to be swapped per account. For those engines,
102
+ > `credential` stores the **whole file content** as a JSON wrapper
101
103
  > (`{ kind: 'chatgpt', authJson: '...' }`), and the adapter / WS handler
102
104
  > writes that blob back to the shared dotfile on `accounts-switch`. After
103
105
  > each stream, snapshot the (possibly-refreshed-by-the-CLI) dotfile back
104
106
  > into `engine_accounts.credential` so token refreshes survive across
105
- > account switches. This keeps multi-account support working without
106
- > isolated `XYZ_HOME` directories — see §9.13 for the rationale.
107
+ > account switches. This keeps multi-account support working **without**
108
+ > per-account `XYZ_HOME` directories — see §9.13 for the rationale, and
109
+ > §9.19 for the Clopen-vs-global home-dir isolation.
107
110
 
108
111
  ### 3.4 The models.dev catalog (OpenCode-specific)
109
112
 
@@ -271,15 +271,19 @@ surface as.
271
271
  the filename, not a directory name:
272
272
 
273
273
  ```
274
- ~/.codex/sessions/<YYYY>/<MM>/<DD>/rollout-<TIMESTAMP>-<thread_id>.jsonl
274
+ <CODEX_HOME>/sessions/<YYYY>/<MM>/<DD>/rollout-<TIMESTAMP>-<thread_id>.jsonl
275
275
  ```
276
276
 
277
+ where `<CODEX_HOME>` is Clopen's isolated `{clopenDir}/engine/codex/user/` (§9.19),
278
+ **not** `~/.codex` — the helper reads it via `getCodexHomeDir()`, so it
279
+ tracks the isolated dir automatically.
280
+
277
281
  The fork helper walks the date-tree to find the source by
278
282
  `-<thread_id>.jsonl` suffix, copies it into TODAY's `YYYY/MM/DD` dir
279
283
  under a new `rollout-<now>-<forkId>.jsonl` filename, and replaces every
280
284
  occurrence of the source id (UUIDs don't collide with other content in
281
285
  the file). Earlier versions of `codex/session-fork.ts` mistakenly
282
- assumed a directory layout (`~/.codex/sessions/<thread_id>/`) — the
286
+ assumed a directory layout (`<CODEX_HOME>/sessions/<thread_id>/`) — the
283
287
  result was a permanently-broken fork because `sessionStateExists()`
284
288
  never matched. If you change the helper, watch for that regression.
285
289
 
@@ -289,9 +293,13 @@ project's cwd via the SDK's `sanitizeCwd()`
289
293
  (`cwd.replace(/[^a-zA-Z0-9]/g, '-')`, lowercased on win32):
290
294
 
291
295
  ```
292
- ~/.qwen/projects/<sanitized-cwd>/chats/<sessionId>.jsonl
296
+ <QWEN_RUNTIME_DIR>/projects/<sanitized-cwd>/chats/<sessionId>.jsonl
293
297
  ```
294
298
 
299
+ where `<QWEN_RUNTIME_DIR>` is Clopen's isolated `{clopenDir}/engine/qwen/user/`
300
+ (§9.19), **not** `~/.qwen` — both the env var and the fork helper
301
+ (`getQwenRuntimeDir()`) resolve to the same base, so they stay in sync.
302
+
295
303
  Every record line carries a `sessionId` field equal to the file's
296
304
  basename. The fork helper copies the file to
297
305
  `<chats>/<forkId>.jsonl` in the same project directory and replaces
@@ -444,28 +452,34 @@ What you must NOT do:
444
452
  - ❌ A local type alias when the SDK exports the type (Open Code,
445
453
  Copilot). Import `McpRemoteConfig` / `MCPHTTPServerConfig` directly.
446
454
 
447
- ### 9.13 Auth-blob swap into a shared CLI dotfile (vs. per-account isolated dirs)
455
+ ### 9.13 Auth-blob swap into a shared CLI dotfile (vs. **per-account** isolated dirs)
456
+
457
+ > **Scope:** this section is about multiple accounts *within* Clopen. The
458
+ > orthogonal question — keeping Clopen's whole footprint out of the user's
459
+ > global `~/.codex` / `~/.copilot` — is **§9.19**, and there the answer is
460
+ > the opposite: we DO override the home env var, but with **one dir per
461
+ > engine shared by all accounts**, not one per account.
448
462
 
449
463
  When a CLI hard-codes its credential location (Codex reads
450
- `~/.codex/auth.json`; Gemini CLI reads `~/.gemini/oauth_creds.json`;
451
- etc.), the naïve approach is to give each Clopen account its own
464
+ `<CODEX_HOME>/auth.json`; Gemini CLI reads `~/.gemini/oauth_creds.json`;
465
+ etc.), the naïve approach is to give **each Clopen account** its own
452
466
  isolated home directory and override the CLI's home env var
453
- (`CODEX_HOME`, `GEMINI_HOME`). **Don't.** That approach has bitten us:
467
+ (`CODEX_HOME=/foo/account-1/`, `/foo/account-2/`, …). **Don't.** A
468
+ *per-account* split has bitten us:
454
469
 
455
- - Session/thread state lives in the same dir tree (`~/.codex/sessions/`,
456
- `~/.codex/projects/`), so isolating the dir splits session memory,
457
- breaks fork-by-copy, and loses the user's `config.toml` overrides.
470
+ - Session/thread state lives in the same dir tree (`<CODEX_HOME>/sessions/`,
471
+ `<CODEX_HOME>/projects/`), so a per-account split fragments session
472
+ memory and breaks fork-by-copy across accounts.
458
473
  - Token refresh happens in-place in the dotfile — refreshes performed
459
- inside an isolated dir do not propagate back to the user's "real"
460
- home unless we add a watcher.
461
- - The CLI's other features (e.g. project trust, `.agents` allowlist)
462
- expect the dir to be the user's normal one.
474
+ under account A's dir don't reach account B.
463
475
 
464
- **Use the shared-location-with-DB-swap pattern instead:**
476
+ Instead, all Clopen accounts for an engine share the **single** isolated
477
+ home from §9.19, and multi-account is handled by swapping the one dotfile
478
+ inside it to/from the DB:
465
479
 
466
480
  | Step | Behavior |
467
481
  |---|---|
468
- | **Login** | Spawn the CLI's login command (`codex login`, etc.) which writes the user's normal dotfile. On success, **read the dotfile content** and persist it to `engine_accounts.credential` as a JSON wrapper, e.g. `{ kind: 'chatgpt', authJson: '<file content>' }`. |
482
+ | **Login** | Spawn the CLI's login command (`codex login`, etc.) — run with the isolated home env var set (e.g. `CODEX_HOME`) so it writes the dotfile inside `{clopenDir}/engine/{engine}/user/`, not `~`. On success, **read the dotfile content** and persist it to `engine_accounts.credential` as a JSON wrapper, e.g. `{ kind: 'chatgpt', authJson: '<file content>' }`. |
469
483
  | **Switch account** | `accounts-switch` handler reads the chosen account's `credential`, parses the wrapper, writes `authJson` **back to the shared dotfile** with an atomic replace (`write to .tmp` + `rename`). |
470
484
  | **Stream-start** | Adapter ensures the dotfile reflects the right blob (re-write if drift detected; cheap idempotent op). |
471
485
  | **Stream-end** | Read the dotfile back and snapshot it into the active account's `credential` so any token refresh the CLI performed during the turn survives across switches. |
@@ -713,3 +727,150 @@ event protocol. Until then, v1 is intentional.
713
727
 
714
728
  ---
715
729
 
730
+ ### 9.18 External (registry) MCP servers — pass auth headers; OAuth is centralized
731
+
732
+ §9.12 covers the **internal** `clopen-mcp` bridge. **External** servers (the
733
+ ones users install from the registry, stored in `mcp_servers`) are different:
734
+ the engine connects **directly** to a third-party URL or stdio command, and
735
+ many require authentication.
736
+
737
+ > **Two distinct token systems — don't conflate them.** The internal bridge
738
+ > uses a process-scoped, in-memory **service token** sent only over loopback
739
+ > (`backend/mcp/internal/service-token.ts`, added in #363 to complete #284) —
740
+ > it intentionally does **not** persist. External servers use **third-party
741
+ > credentials** (OAuth tokens / API keys) that **must** persist across
742
+ > restarts, so they live in the DB (`mcp_servers.oauth` / `mcp_servers.headers`).
743
+ > Both happen to ride the same header fields described below.
744
+
745
+ Two ways a new adapter silently breaks here:
746
+
747
+ 1. **Your `getXxxExternalMcpConfig()` must forward `headers`.** Clopen is the
748
+ OAuth client for remote servers (`backend/mcp/external/oauth.ts`): it runs
749
+ discovery + dynamic registration + PKCE, stores tokens in
750
+ `mcp_servers.oauth`, and `resolveServerRow()` injects
751
+ `Authorization: Bearer <token>` into each resolved server's `headers`
752
+ (alongside any static API-key header). **If your builder drops `headers`,
753
+ the token never reaches the engine and every authenticated server fails
754
+ with a 401 — invisibly.** Every existing builder forwards them
755
+ (`getClaude/OpenCode/Copilot/QwenExternalMcpConfig`); mirror that.
756
+
757
+ 2. **Use the engine's real header field — verify it, don't guess.** The field
758
+ name is per-SDK and a wrong key can make the engine reject its whole
759
+ config:
760
+ - OpenCode / Copilot: `headers` (generic map).
761
+ - Qwen: `headers` alongside `httpUrl`.
762
+ - **Codex: `http_headers`** (a TOML table) — **not** `bearer_token`.
763
+ `bearer_token` is rejected for `streamable_http`
764
+ (`Error loading config.toml: bearer_token is not supported for
765
+ streamable_http`), which aborts the entire `codex exec` run. This mirrors
766
+ the internal bridge in `backend/mcp/internal/config.ts`
767
+ (`getCodexMcpConfig` → `http_headers: { Authorization: 'Bearer …' }`).
768
+ When in doubt, confirm against the CLI: `codex mcp add --help`.
769
+
770
+ The token is refreshed at stream start — `stream-manager` calls
771
+ `refreshExpiringExternalOAuth()` before `engine.streamQuery()`, so the
772
+ **synchronous** config builders below it always read a fresh access token.
773
+ Do not add per-adapter OAuth flows or per-engine token stores; the engine just
774
+ receives a bearer header like any other authenticated remote.
775
+
776
+ Connection health is surfaced engine-agnostically by `mcp:status`
777
+ (`backend/mcp/external/probe.ts`) — it classifies `ok / needs_auth (OAuth) /
778
+ needs_config (missing API key) / unreachable / error`, and the Settings panel
779
+ offers **Authenticate** (OAuth) or **Configure** (API key) accordingly. A new
780
+ adapter needs no work here; the probe talks to the server, not the engine.
781
+
782
+ What you must NOT do:
783
+ - ❌ Drop `headers` from an external remote config (silent 401s).
784
+ - ❌ Use `bearer_token` for Codex remote MCP — use `http_headers`.
785
+ - ❌ Add a per-engine OAuth flow or token store — Clopen centralizes it and
786
+ injects the bearer into every engine, Codex included.
787
+
788
+ ---
789
+
790
+ ### 9.19 Per-engine config-dir isolation (`{clopenDir}/engine/{engine}/user/`)
791
+
792
+ Every engine's CLI/SDK writes runtime state (credentials, session/rollout
793
+ files, logs, caches) to a home dir. Left at the default, that dir is the
794
+ user's **global** one — `~/.codex`, `~/.copilot`, `~/.config/opencode` +
795
+ `~/.local/share/opencode`, `~/.qwen` — so Clopen's activity gets mixed in
796
+ with the user's own standalone CLI usage. We isolate each engine to
797
+ `{clopenDir}/engine/{engine}/user/` (where `clopenDir` is `~/.clopen`, or
798
+ `~/.clopen-dev` in development) via that engine's home env var. The
799
+ `engine/` parent groups all AI-engine state in one place, separate from
800
+ Clopen's other data dirs (`{clopenDir}/snapshots/`, the DB, …). The helper
801
+ is `getEngineUserConfigDir(engine)` in `backend/utils/paths.ts` — one
802
+ source of truth; do not hand-join the path.
803
+
804
+ | Engine | Lever | Where set |
805
+ |---|---|---|
806
+ | Claude | `CLAUDE_CONFIG_DIR` | `claude/environment.ts` (`getClaudeUserConfigDir()` → helper) |
807
+ | Codex | `CODEX_HOME` | `codex/credential.ts` (`CODEX_HOME` const) **+** the SDK's `env` in `codex/stream.ts` **+** the `codex login` PTY env in `ws/engine/codex/accounts.ts` |
808
+ | Copilot | `baseDirectory` (SDK sets `COPILOT_HOME`) | `copilot/stream.ts` `new CopilotClient({ baseDirectory })` |
809
+ | Qwen | `QWEN_RUNTIME_DIR` | `qwen/environment.ts` **+** `getQwenRuntimeDir()` in `qwen/session-fork.ts` |
810
+ | OpenCode | `XDG_DATA_HOME` / `XDG_CONFIG_HOME` / `XDG_STATE_HOME` / `XDG_CACHE_HOME` | `opencode/server.ts` spawn env |
811
+
812
+ Sharp edges, each of which silently defeats isolation if missed:
813
+
814
+ - **Codex SDK drops `process.env` when you pass `env`.** `@openai/codex-sdk`
815
+ docs: *"When provided, the SDK will not inherit variables from
816
+ `process.env`."* So you must pass the **full** `getCleanSpawnEnv()` and
817
+ layer `CODEX_HOME` on top — passing `{ CODEX_HOME }` alone strips `PATH`,
818
+ `HOME`, etc. and the subprocess fails to launch.
819
+ - **Set `CODEX_HOME` in every spawn site, not just the SDK.** `codex login`
820
+ runs in a separate PTY (`ws/engine/codex/accounts.ts`); without
821
+ `CODEX_HOME` there, the OAuth `auth.json` lands in `~/.codex` while the
822
+ stream reads the isolated dir → "logged in but not authenticated".
823
+ - **Keep the fork helper's base in lockstep with the env var.** Codex's
824
+ `session-fork.ts` reads `getCodexHomeDir()` and Qwen's reads
825
+ `getQwenRuntimeDir()` — both resolve to the same isolated base the env
826
+ var sets. If they drift, `sessionStateExists()` returns false and
827
+ multi-branch checkpoints break (see §9.10).
828
+ - **Qwen isolation is partial — and that's accepted.** `QWEN_RUNTIME_DIR`
829
+ relocates runtime output (chats/sessions, history, logs, tmp) but the
830
+ CLI's global `settings.json` / OAuth creds still resolve to `~/.qwen`
831
+ (`Storage.getGlobalQwenDir()`, no env override). Harmless here: Clopen
832
+ uses paste-token auth, so those files are never written by our path.
833
+ - **OpenCode honors all four XDG bases and appends `/opencode` to each.**
834
+ Setting `XDG_{DATA,CONFIG,STATE,CACHE}_HOME` to the isolated dir lands its
835
+ state at `{clopenDir}/engine/opencode/user/opencode/…` (the extra
836
+ `opencode/` segment is the XDG app-name namespace — unavoidable, and there
837
+ is no single "data dir" env that skips it). Credentials + MCP config are
838
+ injected via `OPENCODE_CONFIG_CONTENT`, so the isolated data dir starts
839
+ empty and needs no auth file carried over.
840
+ - **OpenCode reuses a persisted server — guard reuse on the data dir.**
841
+ `opencode/server.ts` caches the live server's URL in the `settings` table
842
+ (`opencode.server.url`) and reuses it across reconnects/restarts. A reused
843
+ server keeps the env (and thus the data dir) it was **spawned** with, so a
844
+ server left over from before isolation — or from a different isolation path
845
+ — would silently keep writing to the old location even though the env is
846
+ now correct. The fix: persist the spawned data dir as
847
+ `opencode.server.datadir` and **refuse to reuse** when it ≠ the current
848
+ `getEngineUserConfigDir('opencode')`; respawn instead. This was the actual
849
+ bug behind "every engine isolated except OpenCode" — the binary respected
850
+ XDG fine; a stale reused server was the culprit. Symptom to watch for: data
851
+ still landing in `~/.local/share/opencode` after the env looks right.
852
+
853
+ **This is orthogonal to multi-account (§9.13).** All of an engine's Clopen
854
+ accounts share this **one** isolated dir; multiple accounts inside it are
855
+ still the auth-blob swap, **not** a dir per account.
856
+
857
+ **Two different "migration" questions — keep them apart:**
858
+
859
+ - **From the user's *global* dir (`~/.codex`, …) → no migration.** Forward-only
860
+ by design: conversations created before isolation keep their session/rollout
861
+ files in the global dir and lose engine-side resume continuity after the
862
+ switch (the message history in Clopen's own DB is unaffected and still
863
+ renders). Credentials are safe — they live in `engine_accounts.credential`
864
+ and re-materialize into the isolated dir on next use. A clean-cut switch was
865
+ chosen over copying because the shared-SQLite engines (Copilot's
866
+ `session-store.db`, OpenCode's monolithic `opencode.db`) interleave Clopen
867
+ and standalone sessions in one file, with no safe per-session extraction.
868
+ - **Between Clopen's *own* isolated layouts → yes, migrated.** An earlier build
869
+ used `{clopenDir}/{engine}/user/` (no `engine/` parent). Migration
870
+ `043_relocate_engine_config_dirs.ts` moves any such dir to the current
871
+ `{clopenDir}/engine/{engine}/user/`. This is always safe — it only ever
872
+ touches a path Clopen created, never the user's global home — and idempotent
873
+ (skips when the new dir already exists; non-fatal on error). It also clears
874
+ the persisted `opencode.server.{url,datadir}` so a server cached against the
875
+ pre-move dir is re-spawned into the relocated one.
876
+
@@ -204,7 +204,16 @@ export class GitService {
204
204
 
205
205
  async getDiffCommit(cwd: string, commitHash: string): Promise<GitFileDiff[]> {
206
206
  assertSafeGitRevish(commitHash, 'commit hash');
207
- const result = await execGit(['diff', `${commitHash}^`, commitHash], cwd);
207
+ // Root commits have no parent, so `<hash>^` can't resolve and `git diff`
208
+ // fails silently (empty stdout) — which previously surfaced as "No files
209
+ // changed". Detect the parentless case and diff against the empty tree via
210
+ // `diff-tree --root` so the initial commit's files show up as additions.
211
+ // Commits with a parent (including merges) keep the original behaviour.
212
+ const hasParent =
213
+ (await execGit(['rev-parse', '--verify', '--quiet', `${commitHash}^`], cwd)).exitCode === 0;
214
+ const result = hasParent
215
+ ? await execGit(['diff', `${commitHash}^`, commitHash], cwd)
216
+ : await execGit(['diff-tree', '-p', '--root', '--no-commit-id', commitHash], cwd);
208
217
  return parseDiff(result.stdout);
209
218
  }
210
219
 
@@ -555,14 +564,24 @@ export class GitService {
555
564
  return parseStashList(result.stdout);
556
565
  }
557
566
 
558
- async stashSave(cwd: string, message?: string): Promise<void> {
567
+ async stashSave(cwd: string, message?: string, stagedOnly = false): Promise<void> {
559
568
  const args = ['stash', 'push'];
569
+ // `--staged` stashes exactly the index (works at hunk level, so partially
570
+ // staged files are handled precisely). Requires Git >= 2.35.
571
+ if (stagedOnly) args.push('--staged');
560
572
  if (message) {
561
573
  assertSafeGitCommitMessage(message);
562
574
  args.push('-m', message);
563
575
  }
564
576
  const result = await execGit(args, cwd);
565
577
  if (result.exitCode !== 0) {
578
+ // Git < 2.35 doesn't know `--staged`; surface an actionable message
579
+ // instead of the raw "unknown option" / "usage:" noise.
580
+ if (stagedOnly && /unknown option|--staged|usage:/i.test(result.stderr)) {
581
+ throw new Error(
582
+ 'Stashing staged changes only requires Git 2.35 or newer. Please update Git to use this option.'
583
+ );
584
+ }
566
585
  throw new Error(`git stash failed: ${result.stderr}`);
567
586
  }
568
587
  }
package/backend/index.ts CHANGED
@@ -40,7 +40,7 @@ import { audioRoute } from './http/audio';
40
40
  import { browserPreviewServiceManager } from './preview';
41
41
 
42
42
  // MCP remote server for Open Code custom tools
43
- import { handleMcpRequest, closeMcpServer } from './mcp';
43
+ import { handleMcpRequest, closeMcpServer, completeAuthorization } from './mcp';
44
44
 
45
45
  // Auth middleware
46
46
  import { checkRouteAccess } from './auth/permissions';
@@ -109,6 +109,28 @@ const app = new Elysia()
109
109
  return handleMcpRequest(request);
110
110
  })
111
111
 
112
+ // Stable OAuth redirect target for centralized MCP sign-in. The browser is
113
+ // redirected here after the user consents; we exchange the code for tokens
114
+ // (stored against the server) and show a self-closing confirmation page. The
115
+ // Settings panel polls `mcp:status` to pick up the new connected state.
116
+ .get('/api/mcp/oauth/callback', async ({ query }) => {
117
+ const { code, state, error } = query as { code?: string; state?: string; error?: string };
118
+ const page = (title: string, body: string) =>
119
+ new Response(
120
+ `<!doctype html><html><head><meta charset="utf-8"><title>${title}</title><style>body{font-family:system-ui,sans-serif;background:#0f172a;color:#e2e8f0;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0}div{text-align:center;max-width:28rem;padding:2rem}h1{font-size:1.1rem}p{color:#94a3b8;font-size:.9rem}</style></head><body><div><h1>${title}</h1><p>${body}</p><script>setTimeout(()=>window.close(),2500)</script></div></body></html>`,
121
+ { headers: { 'Content-Type': 'text/html' } }
122
+ );
123
+ if (error) return page('Sign-in failed', `The authorization server returned: ${error}. You can close this tab and try again.`);
124
+ if (!code || !state) return page('Sign-in failed', 'Missing authorization code. You can close this tab and try again.');
125
+ try {
126
+ await completeAuthorization(state, code);
127
+ return page('Connected', 'Sign-in complete. You can close this tab and return to Clopen.');
128
+ } catch (err) {
129
+ const message = err instanceof Error ? err.message : 'Unknown error';
130
+ return page('Sign-in failed', `${message}. You can close this tab and try again.`);
131
+ }
132
+ })
133
+
112
134
  // HTTP file upload — mounted before the WS plugin so /api/files/upload
113
135
  // stays on the HTTP path through the Vite dev proxy.
114
136
  .use(filesUploadRoute)
@@ -1197,6 +1197,13 @@ checklist in `backend/engine/README.md` §9.12. The summary:
1197
1197
  in that helper rather than building a per-engine resolver.
1198
1198
  4. Wire the engine's auto-approval path (runtime callback or static
1199
1199
  per-tool config) so MCP tool calls don't get cancelled.
1200
+ 5. Add a sibling `getXxxExternalMcpConfig()` in
1201
+ `backend/mcp/external/config.ts` for user-installed registry servers,
1202
+ and **forward `headers`** so the centrally-managed OAuth bearer (and
1203
+ any static API key) reaches the engine. Use the SDK's real header
1204
+ field — Codex uses `http_headers`, **not** `bearer_token`. See
1205
+ [External Servers, OAuth & Connection Status](#external-servers-oauth--connection-status)
1206
+ and `backend/engine/docs/lessons-learned.md` §9.18.
1200
1207
 
1201
1208
  ### File Locations
1202
1209
 
@@ -1214,6 +1221,80 @@ checklist in `backend/engine/README.md` §9.12. The summary:
1214
1221
 
1215
1222
  ---
1216
1223
 
1224
+ ## External Servers, OAuth & Connection Status
1225
+
1226
+ Everything above describes **internal** custom tools (the `clopen-mcp`
1227
+ bridge). **External** servers are the ones a user installs from the official
1228
+ registry (Settings → MCP → Browse), stored in the `mcp_servers` table. Unlike
1229
+ internal tools, the engine connects to these **directly** — a stdio subprocess
1230
+ or a remote third-party URL — so authentication is Clopen's responsibility.
1231
+
1232
+ ### Centralized OAuth (one sign-in, every engine)
1233
+
1234
+ Remote servers that need OAuth (e.g. Notion) are authenticated by **Clopen
1235
+ itself**, not by each engine. The earlier per-engine approach failed: only
1236
+ OpenCode had a callable sign-in trigger, and its token lived in OpenCode's own
1237
+ store, so Codex/Claude/etc. never got it.
1238
+
1239
+ Flow (`backend/mcp/external/oauth.ts`):
1240
+
1241
+ 1. **Discover** — RFC 9728 protected-resource metadata → RFC 8414
1242
+ authorization-server metadata (endpoints + dynamic registration URL).
1243
+ 2. **Register** — RFC 7591 dynamic client registration (public client, PKCE).
1244
+ 3. **Authorize** — authorization-code + PKCE (S256). The browser is redirected
1245
+ to Clopen's **stable** callback `GET /api/mcp/oauth/callback` (in
1246
+ `backend/index.ts`) — not an ephemeral per-flow loopback server.
1247
+ 4. **Store** — access + refresh tokens are saved in the `mcp_servers.oauth`
1248
+ JSON column (migration 042), separate from the user-editable `headers`.
1249
+ 5. **Inject** — `resolveServerRow()` adds `Authorization: Bearer <token>` to
1250
+ every engine's config. `refreshExpiringExternalOAuth()` runs at chat-stream
1251
+ start (in `stream-manager`) so the synchronous per-engine builders read a
1252
+ fresh token. **A new engine adapter needs no OAuth code** — it just receives
1253
+ a bearer header like any authenticated remote.
1254
+
1255
+ WS routes (admin-only): `mcp:oauth-start` (returns the authorization URL; the
1256
+ UI opens it and polls status), `mcp:oauth-complete` (manual paste fallback).
1257
+
1258
+ ### Per-engine config: forward the auth headers
1259
+
1260
+ Each engine's external builder in `backend/mcp/external/config.ts` MUST forward
1261
+ `headers`, and must use the engine's real header field. Dropping headers causes
1262
+ silent 401s; the wrong field name can make the engine reject its whole config.
1263
+
1264
+ | Engine | Header field | Notes |
1265
+ |--------|-------------|-------|
1266
+ | Claude | `headers` | http/sse |
1267
+ | OpenCode | `headers` | `oauth` left unset = auto-detect fallback |
1268
+ | Copilot | `headers` | — |
1269
+ | Qwen | `headers` (+ `httpUrl`) | — |
1270
+ | **Codex** | **`http_headers`** | **NOT `bearer_token`** — that's rejected for `streamable_http` and aborts the run. Matches the internal bridge. |
1271
+
1272
+ ### Required-credential validation
1273
+
1274
+ `mcp:install` / `mcp:update-config` reject a save when a registry-declared
1275
+ required field (`configSchema[].isRequired`) is left blank — so an API-key
1276
+ server can't install into a silently-broken state.
1277
+
1278
+ ### Connection status probe
1279
+
1280
+ `mcp:status` (`backend/mcp/external/probe.ts`) runs an engine-agnostic
1281
+ handshake (`initialize` + `tools/list`; stdio servers are spawned) and
1282
+ classifies the result:
1283
+
1284
+ | State | Meaning | Settings action |
1285
+ |-------|---------|-----------------|
1286
+ | `ok` | Connected (handshake + tool list OK) | — |
1287
+ | `needs_auth` | 401 with a `Bearer` challenge → OAuth | **Authenticate** |
1288
+ | `needs_config` | Reachable but a static API key is missing | **Configure** |
1289
+ | `unreachable` | No response / network error | Re-check |
1290
+ | `error` | Other failure | Re-check |
1291
+ | `local` | (internal rows only) | — |
1292
+
1293
+ The Settings panel probes on open, after install, and after enabling a server,
1294
+ so status never goes stale silently.
1295
+
1296
+ ---
1297
+
1217
1298
  ## Additional Resources
1218
1299
 
1219
1300
  - [Agent SDK Reference](https://platform.claude.com/docs/en/agent-sdk/typescript.md)
@@ -19,6 +19,7 @@ import type { CLIMcpServerConfig as QwenMcpServerConfig } from '@qwen-code/sdk';
19
19
  import { debug } from '$shared/utils/logger';
20
20
  import { mcpServerQueries } from '$backend/database/queries';
21
21
  import { externalNamespace } from '../shared/constants';
22
+ import type { McpServerRow } from '$backend/database/queries';
22
23
  import type { ResolvedExternalServer } from './types';
23
24
 
24
25
  /** Codex flattens `mcp_servers.<name>.<key>` config to `--config` flags. */
@@ -27,6 +28,13 @@ type CodexMcpServerConfig = {
27
28
  args?: string[];
28
29
  env?: Record<string, string>;
29
30
  url?: string;
31
+ /**
32
+ * Streamable-HTTP auth headers. Codex rejects an inline `bearer_token` for
33
+ * streamable_http but accepts an `http_headers` table (the same field the
34
+ * internal `clopen-mcp` bridge uses), so the centrally-managed
35
+ * `Authorization: Bearer …` and any static API-key headers reach Codex.
36
+ */
37
+ http_headers?: Record<string, string>;
30
38
  };
31
39
 
32
40
  function parseJson<T>(raw: string, fallback: T): T {
@@ -37,15 +45,18 @@ function parseJson<T>(raw: string, fallback: T): T {
37
45
  }
38
46
  }
39
47
 
40
- /**
41
- * Load every enabled external server from the DB, parsing JSON columns and
42
- * computing its `<slug>` namespace key.
43
- */
44
- export function getEnabledExternalServers(): ResolvedExternalServer[] {
45
- // `mcp_servers` also holds INTERNAL (code-defined) rows used only for the
46
- // Settings listing + toggle — exclude them here so they're never emitted as
47
- // real external servers the engine would try to connect to.
48
- return mcpServerQueries.getEnabled().filter(row => row.source !== 'internal').map(row => ({
48
+ /** Parse a raw DB row into a connection-ready resolved server. */
49
+ export function resolveServerRow(row: McpServerRow): ResolvedExternalServer {
50
+ const headers = parseJson<Record<string, string>>(row.headers, {});
51
+ // Inject the Clopen-managed OAuth access token as a bearer header so EVERY
52
+ // engine (Codex included) authenticates with the same token. A user-set
53
+ // `Authorization` header always wins. `refreshExpiringExternalOAuth()` runs
54
+ // at stream start, so the token read here is fresh.
55
+ const oauth = row.oauth ? parseJson<{ accessToken?: string } | null>(row.oauth, null) : null;
56
+ if (oauth?.accessToken && !headers.Authorization && !headers.authorization) {
57
+ headers.Authorization = `Bearer ${oauth.accessToken}`;
58
+ }
59
+ return {
49
60
  id: row.id,
50
61
  slug: row.slug,
51
62
  namespace: externalNamespace(row.slug),
@@ -55,8 +66,40 @@ export function getEnabledExternalServers(): ResolvedExternalServer[] {
55
66
  args: parseJson<string[]>(row.args, []),
56
67
  env: parseJson<Record<string, string>>(row.env, {}),
57
68
  url: row.url,
58
- headers: parseJson<Record<string, string>>(row.headers, {})
59
- }));
69
+ headers
70
+ };
71
+ }
72
+
73
+ /**
74
+ * Load every enabled external server from the DB, parsing JSON columns and
75
+ * computing its `<slug>` namespace key.
76
+ */
77
+ export function getEnabledExternalServers(): ResolvedExternalServer[] {
78
+ // `mcp_servers` also holds INTERNAL (code-defined) rows used only for the
79
+ // Settings listing + toggle — exclude them here so they're never emitted as
80
+ // real external servers the engine would try to connect to.
81
+ return mcpServerQueries.getEnabled().filter(row => row.source !== 'internal').map(resolveServerRow);
82
+ }
83
+
84
+ /**
85
+ * A remote server with no configured static credential (API key / bearer
86
+ * header) relies on OAuth. We turn on each engine's native OAuth
87
+ * auto-detection for these so the engine runs the MCP authorization handshake
88
+ * (dynamic client registration, RFC 7591) instead of hitting an
89
+ * unauthenticated 401 and silently exposing zero tools — the failure that hid
90
+ * `com-notion-mcp` on every non-Claude engine. Servers carrying a static
91
+ * header are left as plain authenticated remotes.
92
+ */
93
+ export function remoteNeedsOAuth(s: ResolvedExternalServer): boolean {
94
+ return (s.transport === 'http' || s.transport === 'sse')
95
+ && !!s.url
96
+ && Object.keys(s.headers).length === 0;
97
+ }
98
+
99
+ /** Qwen OAuth fields for a credential-less remote (dynamic discovery). */
100
+ function remoteAuthQwen(s: ResolvedExternalServer): Partial<QwenMcpServerConfig> {
101
+ if (!remoteNeedsOAuth(s)) return {};
102
+ return { oauth: { enabled: true }, authProviderType: 'dynamic_discovery' };
60
103
  }
61
104
 
62
105
  // ---------------------------------------------------------------------------
@@ -93,6 +136,10 @@ export function getOpenCodeExternalMcpConfig(): Record<string, McpLocalConfig |
93
136
  enabled: true
94
137
  };
95
138
  } else if ((s.transport === 'http' || s.transport === 'sse') && s.url) {
139
+ // `oauth` is intentionally left unset: Open Code's default is OAuth
140
+ // auto-detection (set it to `false` only to opt out). Credential-less
141
+ // remotes therefore get the authorization handshake for free; the
142
+ // interactive sign-in is driven separately via the MCP auth flow.
96
143
  out[s.namespace] = {
97
144
  type: 'remote',
98
145
  url: s.url,
@@ -122,7 +169,12 @@ export function getCodexExternalMcpConfig(): Record<string, CodexMcpServerConfig
122
169
  ...(Object.keys(s.env).length > 0 ? { env: s.env } : {})
123
170
  };
124
171
  } else if ((s.transport === 'http' || s.transport === 'sse') && s.url) {
125
- out[s.namespace] = { url: s.url };
172
+ // `http_headers` carries the injected OAuth bearer (and any static API
173
+ // key), matching the internal bridge — so Codex authenticates too.
174
+ out[s.namespace] = {
175
+ url: s.url,
176
+ ...(Object.keys(s.headers).length > 0 ? { http_headers: s.headers } : {})
177
+ };
126
178
  }
127
179
  }
128
180
  logBuilt('Codex', out);
@@ -136,6 +188,10 @@ export function getCopilotExternalMcpConfig(): Record<string, CopilotMcpServerCo
136
188
  if (s.transport === 'stdio' && s.command) {
137
189
  out[s.namespace] = { type: 'local', command: s.command, args: s.args, env: s.env };
138
190
  } else if ((s.transport === 'http' || s.transport === 'sse') && s.url) {
191
+ // Leaving `oauthClientId` unset makes the Copilot runtime perform
192
+ // dynamic client registration when the server demands OAuth. The
193
+ // interactive consent is delegated to us via the `mcp.oauth_required`
194
+ // event (see the Copilot adapter's MCP auth wiring).
139
195
  out[s.namespace] = {
140
196
  type: s.transport,
141
197
  url: s.url,
@@ -154,9 +210,9 @@ export function getQwenExternalMcpConfig(): Record<string, QwenMcpServerConfig>
154
210
  if (s.transport === 'stdio' && s.command) {
155
211
  out[s.namespace] = { command: s.command, args: s.args, env: s.env, trust: true };
156
212
  } else if (s.transport === 'http' && s.url) {
157
- out[s.namespace] = { httpUrl: s.url, headers: s.headers, trust: true };
213
+ out[s.namespace] = { httpUrl: s.url, headers: s.headers, trust: true, ...remoteAuthQwen(s) };
158
214
  } else if (s.transport === 'sse' && s.url) {
159
- out[s.namespace] = { url: s.url, headers: s.headers, trust: true };
215
+ out[s.namespace] = { url: s.url, headers: s.headers, trust: true, ...remoteAuthQwen(s) };
160
216
  }
161
217
  }
162
218
  logBuilt('Qwen', out);