@myrialabs/clopen 0.4.1 → 0.4.3

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.
@@ -108,7 +108,10 @@ export const ADMIN_ONLY_ROUTES = new Set([
108
108
  'mcp:install',
109
109
  'mcp:toggle',
110
110
  'mcp:update-config',
111
- 'mcp:uninstall'
111
+ 'mcp:uninstall',
112
+ 'mcp:status',
113
+ 'mcp:oauth-start',
114
+ 'mcp:oauth-complete'
112
115
  ]);
113
116
 
114
117
  /**
@@ -35,7 +35,7 @@ import type { DatabaseMessage } from '$shared/types/database/schema';
35
35
  import { getProjectEngine, initializeProjectEngine } from '../engine';
36
36
  import { messageQueries, sessionQueries } from '../database/queries';
37
37
  import { snapshotService } from '../snapshot/snapshot-service';
38
- import { projectContextService } from '../mcp';
38
+ import { projectContextService, refreshExpiringExternalOAuth } from '../mcp';
39
39
  import { browserMcpControl } from '../preview';
40
40
  import { extractMessageText } from '../snapshot/helpers';
41
41
  import { debug } from '$shared/utils/logger';
@@ -608,6 +608,12 @@ class StreamManager extends EventEmitter {
608
608
  // large repo could begin editing while the baseline scan is still running.
609
609
  if (baselineInitPromise) await baselineInitPromise;
610
610
 
611
+ // Refresh any near-expiry managed MCP OAuth tokens so the engine's
612
+ // (synchronous) MCP config builders below inject a still-valid bearer.
613
+ await refreshExpiringExternalOAuth().catch(error =>
614
+ debug.warn('chat', 'MCP OAuth refresh failed:', error)
615
+ );
616
+
611
617
  // Stream EngineOutput events through the engine adapter
612
618
  const streamIterable = engine.streamQuery({
613
619
  projectPath,
@@ -0,0 +1,16 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Add config_schema column to mcp_servers (UI field metadata)';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Adding config_schema column to mcp_servers...');
8
+ db.exec(`ALTER TABLE mcp_servers ADD COLUMN config_schema TEXT NOT NULL DEFAULT '[]'`);
9
+ debug.log('migration', 'config_schema column added');
10
+ };
11
+
12
+ export const down = (db: DatabaseConnection): void => {
13
+ debug.log('migration', 'Dropping config_schema column from mcp_servers...');
14
+ db.exec('ALTER TABLE mcp_servers DROP COLUMN config_schema');
15
+ debug.log('migration', 'config_schema column dropped');
16
+ };
@@ -0,0 +1,20 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Add oauth column to mcp_servers (centralized OAuth client registration + tokens)';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Adding oauth column to mcp_servers...');
8
+ // Holds the JSON OAuth state Clopen manages on the user's behalf: dynamic
9
+ // client registration + access/refresh tokens. NULL = no OAuth. Kept separate
10
+ // from the user-editable `headers` so a refreshed token never clobbers manual
11
+ // config, and so every engine can be handed `Authorization: Bearer <token>`.
12
+ db.exec(`ALTER TABLE mcp_servers ADD COLUMN oauth TEXT`);
13
+ debug.log('migration', 'oauth column added');
14
+ };
15
+
16
+ export const down = (db: DatabaseConnection): void => {
17
+ debug.log('migration', 'Dropping oauth column from mcp_servers...');
18
+ db.exec('ALTER TABLE mcp_servers DROP COLUMN oauth');
19
+ debug.log('migration', 'oauth column dropped');
20
+ };
@@ -39,6 +39,8 @@ import * as migration037 from './037_repair_auth_audit_log_schema';
39
39
  import * as migration038 from './038_add_workspace_state_to_user_projects';
40
40
  import * as migration039 from './039_create_file_audit_log';
41
41
  import * as migration040 from './040_create_mcp_servers_table';
42
+ import * as migration041 from './041_add_mcp_config_schema';
43
+ import * as migration042 from './042_add_mcp_oauth';
42
44
 
43
45
  // Export all migrations in order
44
46
  export const migrations = [
@@ -281,6 +283,18 @@ export const migrations = [
281
283
  description: migration040.description,
282
284
  up: migration040.up,
283
285
  down: migration040.down
286
+ },
287
+ {
288
+ id: '041',
289
+ description: migration041.description,
290
+ up: migration041.up,
291
+ down: migration041.down
292
+ },
293
+ {
294
+ id: '042',
295
+ description: migration042.description,
296
+ up: migration042.up,
297
+ down: migration042.down
284
298
  }
285
299
  ];
286
300
 
@@ -13,4 +13,4 @@ export { dbClientQueryHistoryQueries } from './db-client-query-history-queries';
13
13
  export { auditLogQueries } from './audit-log-queries';
14
14
  export { fileAuditLogQueries } from './file-audit-log-queries';
15
15
  export { mcpServerQueries } from './mcp-server-queries';
16
- export type { McpServerRow, McpServerInput, McpTransport, McpSource } from './mcp-server-queries';
16
+ export type { McpServerRow, McpServerInput, McpTransport, McpSource, McpConfigField } from './mcp-server-queries';
@@ -18,6 +18,21 @@ import { getDatabase } from '../index';
18
18
  export type McpTransport = 'stdio' | 'http' | 'sse';
19
19
  export type McpSource = 'registry' | 'custom' | 'internal';
20
20
 
21
+ /**
22
+ * A single configurable field, captured from the registry catalog at install
23
+ * time so the "Configure" UI can render the same labelled fields it showed at
24
+ * install. Purely UI metadata — engines read the actual values from
25
+ * `env`/`headers`, never from here. `kind` decides whether the value lands in
26
+ * the env map (stdio) or the headers map (remote auth).
27
+ */
28
+ export interface McpConfigField {
29
+ name: string;
30
+ kind: 'env' | 'header';
31
+ description?: string;
32
+ isRequired: boolean;
33
+ isSecret: boolean;
34
+ }
35
+
21
36
  /** Raw DB row. */
22
37
  export interface McpServerRow {
23
38
  id: number;
@@ -32,6 +47,9 @@ export interface McpServerRow {
32
47
  env: string;
33
48
  url: string | null;
34
49
  headers: string;
50
+ config_schema: string;
51
+ /** JSON OAuth state Clopen manages (registration + tokens), or null. */
52
+ oauth: string | null;
35
53
  source: McpSource;
36
54
  is_enabled: number;
37
55
  created_at: string;
@@ -49,6 +67,7 @@ export interface McpServerInput {
49
67
  env?: Record<string, string>;
50
68
  url?: string | null;
51
69
  headers?: Record<string, string>;
70
+ configSchema?: McpConfigField[];
52
71
  source?: McpSource;
53
72
  }
54
73
 
@@ -82,8 +101,8 @@ export const mcpServerQueries = {
82
101
  const db = getDatabase();
83
102
  const result = db.prepare(
84
103
  `INSERT INTO mcp_servers
85
- (slug, name, description, registry_name, version, transport, command, args, env, url, headers, source)
86
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
104
+ (slug, name, description, registry_name, version, transport, command, args, env, url, headers, config_schema, source)
105
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
87
106
  ).run(
88
107
  input.slug,
89
108
  input.name,
@@ -96,6 +115,7 @@ export const mcpServerQueries = {
96
115
  JSON.stringify(input.env ?? {}),
97
116
  input.url ?? null,
98
117
  JSON.stringify(input.headers ?? {}),
118
+ JSON.stringify(input.configSchema ?? []),
99
119
  input.source ?? 'registry'
100
120
  ) as { lastInsertRowid: number | bigint };
101
121
  const id = Number(result.lastInsertRowid);
@@ -123,6 +143,12 @@ export const mcpServerQueries = {
123
143
  );
124
144
  },
125
145
 
146
+ /** Store (or clear with null) the managed OAuth state JSON for a server. */
147
+ setOAuth(id: number, oauth: string | null): void {
148
+ const db = getDatabase();
149
+ db.prepare(`UPDATE mcp_servers SET oauth = ? WHERE id = ?`).run(oauth, id);
150
+ },
151
+
126
152
  remove(id: number): void {
127
153
  const db = getDatabase();
128
154
  db.prepare(`DELETE FROM mcp_servers WHERE id = ?`).run(id);
@@ -125,25 +125,30 @@ async function init(): Promise<void> {
125
125
  if (!command) throw new Error('opencode binary not found on PATH');
126
126
  const args = [command, 'serve', `--hostname=${OPENCODE_HOST}`, '--port=0'];
127
127
 
128
- // Build MCP config — but only inject if the MCP endpoint is actually reachable.
129
- // The opencode binary may initialize MCP connections synchronously before printing
130
- // "opencode server listening", so an unreachable/slow MCP endpoint can stall startup.
131
- let mcpConfig = getOpenCodeMcpConfig();
128
+ // Build MCP config — but only inject remote servers whose endpoint is
129
+ // actually reachable. The opencode binary may initialize MCP connections
130
+ // synchronously before printing "opencode server listening", so an
131
+ // unreachable/slow remote endpoint can stall startup. Drop ONLY the
132
+ // unreachable remote entries; stdio/local servers (no `url`) are independent
133
+ // of the HTTP bridge and must always survive — they were previously thrown
134
+ // out together with the bridge when it wasn't reachable yet.
135
+ const mcpConfig = getOpenCodeMcpConfig();
132
136
  if (Object.keys(mcpConfig).length > 0) {
133
- const mcpUrls = Object.values(mcpConfig).map(c => (c as any).url).filter(Boolean);
134
- const reachable = await Promise.all(
135
- mcpUrls.map(url => isServerAlive(url))
137
+ const entries = Object.entries(mcpConfig);
138
+ const reachability = await Promise.all(
139
+ entries.map(([, c]) => {
140
+ const url = (c as any).url as string | undefined;
141
+ return url ? isServerAlive(url) : Promise.resolve(true);
142
+ })
136
143
  );
137
-
138
- if (reachable.every(Boolean)) {
139
- debug.log('engine', `Open Code server: injecting ${Object.keys(mcpConfig).length} MCP server(s)`);
140
- for (const [name, config] of Object.entries(mcpConfig)) {
141
- debug.log('engine', ` → ${name}: ${config.type} (${(config as any).url || (config as any).command?.join(' ')})`);
144
+ entries.forEach(([name, config], i) => {
145
+ if (reachability[i]) {
146
+ debug.log('engine', `Open Code server: injecting MCP server → ${name}: ${config.type} (${(config as any).url || (config as any).command?.join(' ')})`);
147
+ } else {
148
+ debug.warn('engine', `Open Code server: MCP endpoint for "${name}" not reachable, skipping it`);
149
+ delete mcpConfig[name];
142
150
  }
143
- } else {
144
- debug.warn('engine', 'Open Code server: MCP endpoint not reachable, starting without MCP');
145
- mcpConfig = {};
146
- }
151
+ });
147
152
  }
148
153
 
149
154
  // Build provider config from DB (enabled providers + env vars)
@@ -52,6 +52,14 @@ mandatory files; optional files use the canonical names from §2.6.
52
52
  - [ ] `backend/engine/index.ts`: import + add a case in
53
53
  `createEngine(type)`. If there is a shared subprocess, call
54
54
  `disposeXxxClient()` from `disposeAllProjectEngines()`.
55
+ - [ ] MCP config (if the SDK accepts a streamable-HTTP MCP URL):
56
+ - [ ] Internal bridge — add `getXxxMcpConfig()` in
57
+ `backend/mcp/internal/config.ts` (reuse `clopen-mcp`; see §9.12).
58
+ - [ ] External servers — add `getXxxExternalMcpConfig()` in
59
+ `backend/mcp/external/config.ts` and **forward `headers`** so the
60
+ centralized OAuth bearer reaches the engine. Use the SDK's real
61
+ header field — **Codex uses `http_headers`, not `bearer_token`**.
62
+ See §9.18 and `backend/mcp/README.md`.
55
63
 
56
64
  ### Stage 3 — Database (if a default provider needs to be seeded)
57
65
 
@@ -713,3 +713,63 @@ event protocol. Until then, v1 is intentional.
713
713
 
714
714
  ---
715
715
 
716
+ ### 9.18 External (registry) MCP servers — pass auth headers; OAuth is centralized
717
+
718
+ §9.12 covers the **internal** `clopen-mcp` bridge. **External** servers (the
719
+ ones users install from the registry, stored in `mcp_servers`) are different:
720
+ the engine connects **directly** to a third-party URL or stdio command, and
721
+ many require authentication.
722
+
723
+ > **Two distinct token systems — don't conflate them.** The internal bridge
724
+ > uses a process-scoped, in-memory **service token** sent only over loopback
725
+ > (`backend/mcp/internal/service-token.ts`, added in #363 to complete #284) —
726
+ > it intentionally does **not** persist. External servers use **third-party
727
+ > credentials** (OAuth tokens / API keys) that **must** persist across
728
+ > restarts, so they live in the DB (`mcp_servers.oauth` / `mcp_servers.headers`).
729
+ > Both happen to ride the same header fields described below.
730
+
731
+ Two ways a new adapter silently breaks here:
732
+
733
+ 1. **Your `getXxxExternalMcpConfig()` must forward `headers`.** Clopen is the
734
+ OAuth client for remote servers (`backend/mcp/external/oauth.ts`): it runs
735
+ discovery + dynamic registration + PKCE, stores tokens in
736
+ `mcp_servers.oauth`, and `resolveServerRow()` injects
737
+ `Authorization: Bearer <token>` into each resolved server's `headers`
738
+ (alongside any static API-key header). **If your builder drops `headers`,
739
+ the token never reaches the engine and every authenticated server fails
740
+ with a 401 — invisibly.** Every existing builder forwards them
741
+ (`getClaude/OpenCode/Copilot/QwenExternalMcpConfig`); mirror that.
742
+
743
+ 2. **Use the engine's real header field — verify it, don't guess.** The field
744
+ name is per-SDK and a wrong key can make the engine reject its whole
745
+ config:
746
+ - OpenCode / Copilot: `headers` (generic map).
747
+ - Qwen: `headers` alongside `httpUrl`.
748
+ - **Codex: `http_headers`** (a TOML table) — **not** `bearer_token`.
749
+ `bearer_token` is rejected for `streamable_http`
750
+ (`Error loading config.toml: bearer_token is not supported for
751
+ streamable_http`), which aborts the entire `codex exec` run. This mirrors
752
+ the internal bridge in `backend/mcp/internal/config.ts`
753
+ (`getCodexMcpConfig` → `http_headers: { Authorization: 'Bearer …' }`).
754
+ When in doubt, confirm against the CLI: `codex mcp add --help`.
755
+
756
+ The token is refreshed at stream start — `stream-manager` calls
757
+ `refreshExpiringExternalOAuth()` before `engine.streamQuery()`, so the
758
+ **synchronous** config builders below it always read a fresh access token.
759
+ Do not add per-adapter OAuth flows or per-engine token stores; the engine just
760
+ receives a bearer header like any other authenticated remote.
761
+
762
+ Connection health is surfaced engine-agnostically by `mcp:status`
763
+ (`backend/mcp/external/probe.ts`) — it classifies `ok / needs_auth (OAuth) /
764
+ needs_config (missing API key) / unreachable / error`, and the Settings panel
765
+ offers **Authenticate** (OAuth) or **Configure** (API key) accordingly. A new
766
+ adapter needs no work here; the probe talks to the server, not the engine.
767
+
768
+ What you must NOT do:
769
+ - ❌ Drop `headers` from an external remote config (silent 401s).
770
+ - ❌ Use `bearer_token` for Codex remote MCP — use `http_headers`.
771
+ - ❌ Add a per-engine OAuth flow or token store — Clopen centralizes it and
772
+ injects the bearer into every engine, Codex included.
773
+
774
+ ---
775
+
@@ -555,14 +555,24 @@ export class GitService {
555
555
  return parseStashList(result.stdout);
556
556
  }
557
557
 
558
- async stashSave(cwd: string, message?: string): Promise<void> {
558
+ async stashSave(cwd: string, message?: string, stagedOnly = false): Promise<void> {
559
559
  const args = ['stash', 'push'];
560
+ // `--staged` stashes exactly the index (works at hunk level, so partially
561
+ // staged files are handled precisely). Requires Git >= 2.35.
562
+ if (stagedOnly) args.push('--staged');
560
563
  if (message) {
561
564
  assertSafeGitCommitMessage(message);
562
565
  args.push('-m', message);
563
566
  }
564
567
  const result = await execGit(args, cwd);
565
568
  if (result.exitCode !== 0) {
569
+ // Git < 2.35 doesn't know `--staged`; surface an actionable message
570
+ // instead of the raw "unknown option" / "usage:" noise.
571
+ if (stagedOnly && /unknown option|--staged|usage:/i.test(result.stderr)) {
572
+ throw new Error(
573
+ 'Stashing staged changes only requires Git 2.35 or newer. Please update Git to use this option.'
574
+ );
575
+ }
566
576
  throw new Error(`git stash failed: ${result.stderr}`);
567
577
  }
568
578
  }
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';
@@ -99,7 +99,37 @@ const app = new Elysia()
99
99
 
100
100
  // MCP remote server endpoint for Open Code custom tools
101
101
  // Handles GET (SSE stream), POST (JSON-RPC), DELETE (session close)
102
- .all('/mcp', async ({ request }) => handleMcpRequest(request))
102
+ .all('/mcp', async ({ request, server }) => {
103
+ // MCP tool calls can run far longer than Bun's default 10s idle timeout.
104
+ // While a tool executes, the streaming response sends no bytes, so Bun
105
+ // would close the idle connection and the call surfaces as MCP error
106
+ // -32001 ("Request timed out"). Disable the idle timeout for this
107
+ // long-lived endpoint only — every other route keeps the safe default.
108
+ server?.timeout(request, 0);
109
+ return handleMcpRequest(request);
110
+ })
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
+ })
103
133
 
104
134
  // HTTP file upload — mounted before the WS plugin so /api/files/upload
105
135
  // stays on the HTTP path through the Vite dev proxy.
@@ -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);