@myrialabs/clopen 0.3.22 → 0.4.1

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 (61) hide show
  1. package/backend/auth/permissions.ts +12 -1
  2. package/backend/chat/stream-manager.ts +14 -3
  3. package/backend/database/migrations/040_create_mcp_servers_table.ts +34 -0
  4. package/backend/database/migrations/index.ts +7 -0
  5. package/backend/database/queries/index.ts +3 -1
  6. package/backend/database/queries/mcp-server-queries.ts +166 -0
  7. package/backend/engine/README.md +2 -2
  8. package/backend/engine/adapters/codex/message-converter.ts +1 -1
  9. package/backend/engine/adapters/codex/stream.ts +1 -1
  10. package/backend/engine/adapters/copilot/message-converter.ts +1 -1
  11. package/backend/engine/adapters/copilot/stream.ts +1 -1
  12. package/backend/engine/adapters/qwen/message-converter.ts +1 -1
  13. package/backend/engine/adapters/qwen/stream.ts +1 -1
  14. package/backend/engine/docs/adapter-contract.md +2 -2
  15. package/backend/engine/docs/lessons-learned.md +3 -3
  16. package/backend/engine/docs/quick-reference.md +1 -1
  17. package/backend/git/git-parser.ts +58 -29
  18. package/backend/git/git-service.ts +79 -10
  19. package/backend/git/git-spawn-validation.ts +3 -3
  20. package/backend/index.ts +5 -1
  21. package/backend/mcp/README.md +67 -32
  22. package/backend/mcp/external/config.ts +200 -0
  23. package/backend/mcp/external/registry-client.ts +214 -0
  24. package/backend/mcp/external/types.ts +69 -0
  25. package/backend/mcp/index.ts +104 -19
  26. package/backend/mcp/{config.ts → internal/config.ts} +82 -18
  27. package/backend/mcp/{remote-server.test.ts → internal/remote-server.test.ts} +3 -3
  28. package/backend/mcp/{servers → internal/servers}/browser-automation/actions.ts +1 -1
  29. package/backend/mcp/{servers → internal/servers}/browser-automation/browser.ts +1 -1
  30. package/backend/mcp/{servers → internal/servers}/browser-automation/index.ts +2 -0
  31. package/backend/mcp/{servers → internal/servers}/browser-automation/inspection.ts +1 -1
  32. package/backend/mcp/{servers → internal/servers}/helper.ts +11 -0
  33. package/backend/mcp/{servers → internal/servers}/index.ts +0 -2
  34. package/backend/mcp/{types.ts → internal/types.ts} +3 -3
  35. package/backend/mcp/shared/constants.ts +66 -0
  36. package/backend/projects/project-cleanup.ts +1 -1
  37. package/backend/ws/engine/index.ts +3 -1
  38. package/backend/ws/engine/restart.ts +54 -0
  39. package/backend/ws/git/branch.ts +3 -2
  40. package/backend/ws/git/commit.ts +14 -0
  41. package/backend/ws/git/remote.ts +85 -0
  42. package/backend/ws/index.ts +5 -1
  43. package/backend/ws/mcp/catalog.ts +56 -0
  44. package/backend/ws/mcp/crud.ts +174 -0
  45. package/backend/ws/mcp/index.ts +18 -0
  46. package/backend/ws/settings/crud.ts +31 -0
  47. package/dist/assets/main-DKLZPDUN.css +1 -0
  48. package/dist/assets/main-qT_RedHf.js +377 -0
  49. package/dist/index.html +2 -2
  50. package/package.json +1 -1
  51. package/shared/types/git.ts +4 -0
  52. package/shared/types/stores/settings.ts +2 -0
  53. package/backend/mcp/servers/weather/get-temperature.ts +0 -56
  54. package/backend/mcp/servers/weather/index.ts +0 -31
  55. package/dist/assets/main-Ba19ADkk.js +0 -377
  56. package/dist/assets/main-CwCZzMVm.css +0 -1
  57. /package/backend/mcp/{output-validator.test.ts → internal/output-validator.test.ts} +0 -0
  58. /package/backend/mcp/{output-validator.ts → internal/output-validator.ts} +0 -0
  59. /package/backend/mcp/{project-context.test.ts → internal/project-context.test.ts} +0 -0
  60. /package/backend/mcp/{project-context.ts → internal/project-context.ts} +0 -0
  61. /package/backend/mcp/{remote-server.ts → internal/remote-server.ts} +0 -0
@@ -233,14 +233,23 @@ export class GitService {
233
233
  // Branches
234
234
  // ============================================
235
235
 
236
- async getBranches(cwd: string): Promise<GitBranchInfo> {
236
+ async getBranches(cwd: string, selectedRemote?: string): Promise<GitBranchInfo> {
237
+ // `git for-each-ref` lets us pull the committer date alongside the
238
+ // short hash and subject in a single call per ref namespace, which
239
+ // the old `git branch -v` output doesn't expose. Format:
240
+ // `HEAD|short-name|short-hash|subject|iso-date`
241
+ // where `HEAD` is `*` for the current branch and ` ` for others.
242
+ // `iso-date` is strict ISO 8601 so it can't collide with the `|`
243
+ // separators — the parser uses `lastIndexOf('|')` to extract it.
244
+ const localFmt = '%(HEAD)|%(refname:short)|%(objectname:short)|%(subject)|%(committerdate:iso8601)';
245
+ const remoteFmt = '%(refname:short)|%(objectname:short)|%(subject)|%(committerdate:iso8601)';
237
246
  const [localResult, remoteResult, headRef] = await Promise.all([
238
- execGit(['branch', '-v', '--no-color'], cwd),
239
- execGit(['branch', '-r', '-v', '--no-color'], cwd),
247
+ execGit(['for-each-ref', `--format=${localFmt}`, 'refs/heads/'], cwd),
248
+ execGit(['for-each-ref', `--format=${remoteFmt}`, 'refs/remotes/'], cwd),
240
249
  execGit(['rev-parse', '--abbrev-ref', 'HEAD'], cwd)
241
250
  ]);
242
251
 
243
- // Handle empty repo (no commits yet) — branch command returns empty
252
+ // Handle empty repo (no commits yet) — for-each-ref returns empty
244
253
  if (!localResult.stdout.trim()) {
245
254
  // Try to get the initial branch name from HEAD
246
255
  const headResult = await execGit(['symbolic-ref', '--short', 'HEAD'], cwd);
@@ -269,11 +278,12 @@ export class GitService {
269
278
  branchInfo.current = headName;
270
279
  for (const b of branchInfo.local) b.isCurrent = b.name === headName;
271
280
 
272
- // Get ahead/behind for current branch
273
- if (branchInfo.current) {
281
+ // Get ahead/behind for current branch relative to the SELECTED remote
282
+ if (branchInfo.current && selectedRemote) {
274
283
  try {
284
+ const remoteRef = `${selectedRemote}/${branchInfo.current}`;
275
285
  const abResult = await execGit(
276
- ['rev-list', '--left-right', '--count', `${branchInfo.current}...@{upstream}`],
286
+ ['rev-list', '--left-right', '--count', `${branchInfo.current}...${remoteRef}`],
277
287
  cwd
278
288
  );
279
289
  if (abResult.exitCode === 0) {
@@ -281,7 +291,6 @@ export class GitService {
281
291
  branchInfo.ahead = ahead;
282
292
  branchInfo.behind = behind;
283
293
 
284
- // Update the current branch entry too
285
294
  const currentBranch = branchInfo.local.find(b => b.isCurrent);
286
295
  if (currentBranch) {
287
296
  currentBranch.ahead = ahead;
@@ -289,7 +298,7 @@ export class GitService {
289
298
  }
290
299
  }
291
300
  } catch {
292
- // No upstream configured
301
+ // Remote tracking branch doesn't exist — show 0
293
302
  }
294
303
  }
295
304
 
@@ -343,6 +352,15 @@ export class GitService {
343
352
  }
344
353
  }
345
354
 
355
+ async deleteRemoteBranch(cwd: string, remote: string, branch: string): Promise<void> {
356
+ assertSafeGitRevish(remote, 'remote name');
357
+ assertSafeGitRevish(branch, 'branch name');
358
+ const result = await execGit(['push', remote, '--delete', branch], cwd);
359
+ if (result.exitCode !== 0) {
360
+ throw new Error(`git push --delete failed: ${result.stderr}`);
361
+ }
362
+ }
363
+
346
364
  async mergeBranch(cwd: string, branchName: string, noFastForward = false): Promise<{ success: boolean; message: string }> {
347
365
  assertSafeGitRevish(branchName, 'merge branch');
348
366
  const args = ['merge'];
@@ -497,6 +515,25 @@ export class GitService {
497
515
  }
498
516
  }
499
517
 
518
+ async setRemoteUrl(cwd: string, name: string, url: string): Promise<void> {
519
+ assertSafeGitRemoteName(name);
520
+ assertSafeGitRemoteUrl(url);
521
+ const result = await execGit(['remote', 'set-url', name, url], cwd);
522
+ if (result.exitCode !== 0) {
523
+ throw new Error(`git remote set-url failed: ${result.stderr}`);
524
+ }
525
+ }
526
+
527
+ async renameRemote(cwd: string, oldName: string, newName: string): Promise<void> {
528
+ assertSafeGitRemoteName(oldName);
529
+ assertSafeGitRemoteName(newName);
530
+ if (oldName === newName) return;
531
+ const result = await execGit(['remote', 'rename', oldName, newName], cwd);
532
+ if (result.exitCode !== 0) {
533
+ throw new Error(`git remote rename failed: ${result.stderr}`);
534
+ }
535
+ }
536
+
500
537
  async removeRemote(cwd: string, name: string): Promise<void> {
501
538
  assertSafeGitRemoteName(name);
502
539
  const result = await execGit(['remote', 'remove', name], cwd);
@@ -510,7 +547,11 @@ export class GitService {
510
547
  // ============================================
511
548
 
512
549
  async stashList(cwd: string): Promise<GitStashEntry[]> {
513
- const result = await execGit(['stash', 'list'], cwd);
550
+ // Custom format appends the committer date (ISO 8601) after a ` | `
551
+ // separator so the parser can extract it. The default `git stash list`
552
+ // output has no date. `%cI` is the strict ISO format — it contains
553
+ // colons and dashes but never ` | `, so the lastIndexOf split is safe.
554
+ const result = await execGit(['stash', 'list', '--format=%gd: %gs | %cI'], cwd);
514
555
  return parseStashList(result.stdout);
515
556
  }
516
557
 
@@ -558,6 +599,19 @@ export class GitService {
558
599
  }
559
600
  }
560
601
 
602
+ async stashDiff(cwd: string, index = 0): Promise<GitFileDiff[]> {
603
+ if (!Number.isInteger(index) || index < 0) {
604
+ throw new Error('Invalid stash index');
605
+ }
606
+ // `git stash show -p stash@{N}` produces a unified diff in the
607
+ // same format as `git diff`, so `parseDiff` handles it unchanged.
608
+ const result = await execGit(['stash', 'show', '-p', `stash@{${index}}`], cwd);
609
+ if (result.exitCode !== 0) {
610
+ throw new Error(`git stash show failed: ${result.stderr}`);
611
+ }
612
+ return parseDiff(result.stdout);
613
+ }
614
+
561
615
  // ============================================
562
616
  // Tags
563
617
  // ============================================
@@ -759,6 +813,21 @@ export class GitService {
759
813
  };
760
814
  }
761
815
 
816
+ /** Cherry-pick one or more commits onto the current branch (`git cherry-pick <hash>...`). */
817
+ async cherryPick(cwd: string, refs: string[]): Promise<{ success: boolean; message: string }> {
818
+ if (refs.length === 0) {
819
+ return { success: false, message: 'No commits provided' };
820
+ }
821
+ for (const ref of refs) {
822
+ assertSafeGitRevish(ref, 'cherry-pick ref');
823
+ }
824
+ const result = await execGit(['cherry-pick', ...refs], cwd);
825
+ return {
826
+ success: result.exitCode === 0,
827
+ message: result.exitCode === 0 ? (result.stdout || result.stderr || 'Cherry-pick succeeded') : result.stderr
828
+ };
829
+ }
830
+
762
831
  // ============================================
763
832
  // Maintenance
764
833
  // ============================================
@@ -25,11 +25,11 @@ export function assertSafeGitRevish(value: string, label: string): void {
25
25
  }
26
26
  }
27
27
 
28
- /** `git remote` names are a small charset in practice; keep strict. */
28
+ /** `git remote` names — allow common refname chars (slashes for hierarchies, plus signs). */
29
29
  export function assertSafeGitRemoteName(name: string): void {
30
30
  assertSafeGitRevish(name, 'remote name');
31
- if (!/^[A-Za-z0-9._-]+$/.test(name)) {
32
- throw new Error('Invalid git remote name');
31
+ if (!/^[A-Za-z0-9._\-+/]+$/.test(name)) {
32
+ throw new Error(`Invalid git remote name "${name}": only letters, digits, '.', '_', '-', '+', '/' allowed`);
33
33
  }
34
34
  }
35
35
 
package/backend/index.ts CHANGED
@@ -18,6 +18,7 @@ import { loggerMiddleware } from './middleware/logger';
18
18
 
19
19
  // Database initialization
20
20
  import { initializeDatabase, closeDatabase } from './database';
21
+ import { syncInternalServers } from './mcp';
21
22
  import { disposeAllEngines } from './engine';
22
23
  import { refreshProcessPath } from './utils/path-enrich';
23
24
  import { debug } from '$shared/utils/logger';
@@ -39,7 +40,7 @@ import { audioRoute } from './http/audio';
39
40
  import { browserPreviewServiceManager } from './preview';
40
41
 
41
42
  // MCP remote server for Open Code custom tools
42
- import { handleMcpRequest, closeMcpServer } from './mcp/remote-server';
43
+ import { handleMcpRequest, closeMcpServer } from './mcp';
43
44
 
44
45
  // Auth middleware
45
46
  import { checkRouteAccess } from './auth/permissions';
@@ -163,6 +164,9 @@ async function startServer() {
163
164
  try {
164
165
  await initializeDatabase();
165
166
  debug.log('database', '✅ Database initialized successfully');
167
+ // Mirror code-defined internal MCP servers into the DB so Settings → MCP
168
+ // can list and toggle them. Idempotent; preserves the user's toggles.
169
+ syncInternalServers();
166
170
  // Start expired session cleanup now that the database is ready
167
171
  sessionCleanupScheduler.start();
168
172
  uploadTempCleanup.start();
@@ -1,6 +1,28 @@
1
- # Custom MCP Tools
1
+ # MCP (Model Context Protocol)
2
2
 
3
- Custom MCP (Model Context Protocol) tools for adding specialized functionality to all AI engines (**Claude Code**, **Open Code**, **Codex**, **Copilot**, …). Servers are defined once and shared across every engine via a single-source-of-truth architecture.
3
+ Clopen integrates MCP from **two distinct sources**, kept cleanly separated on
4
+ disk and in their namespace keys:
5
+
6
+ | | **Internal** (`internal/`) | **External** (`external/`) |
7
+ |---|---|---|
8
+ | What | Custom tools defined in code via `defineServer()` | Servers the user installs from the official MCP registry |
9
+ | Managed | By developers (this README) | By users in **Settings → MCP** |
10
+ | Stored | In code (`internal/servers/`) | In the DB (`mcp_servers` table) |
11
+ | Namespace | `clopen-mcp` bridge (non-Claude) / server name (Claude) | one bare `<slug>` per server (no prefix) |
12
+ | Execution | In-process (no subprocess) | Engine connects directly (stdio subprocess or remote HTTP) |
13
+
14
+ Both are merged behind the **facade** `backend/mcp/index.ts` — the only module
15
+ the rest of the backend imports from (`getEnabledMcpServers()`,
16
+ `getXxxMcpConfig()`, `resolveOpenCodeToolName()` all return the combined view).
17
+
18
+ The rest of this document covers the **internal** custom-tool system. External
19
+ servers need no code — see `external/registry-client.ts` and `external/config.ts`.
20
+
21
+ ---
22
+
23
+ ## Custom (Internal) MCP Tools
24
+
25
+ Custom MCP tools add specialized functionality to all AI engines (**Claude Code**, **Open Code**, **Codex**, **Copilot**, …). Servers are defined once and shared across every engine via a single-source-of-truth architecture.
4
26
 
5
27
  ## 📚 Table of Contents
6
28
 
@@ -38,9 +60,9 @@ System for adding custom tools to AI engines with type-safe TypeScript definitio
38
60
 
39
61
  ### 1. Create a New Server
40
62
 
41
- Create a new folder in `./servers/` (e.g., `calculator/`) and create an `index.ts` file using the `defineServer` helper:
63
+ Create a new folder in `./internal/servers/` (e.g., `calculator/`) and create an `index.ts` file using the `defineServer` helper:
42
64
 
43
- **File: `./servers/calculator/index.ts`**
65
+ **File: `./internal/servers/calculator/index.ts`**
44
66
  ```typescript
45
67
  import { z } from "zod";
46
68
  import { defineServer } from "../helper";
@@ -85,7 +107,7 @@ export default defineServer({
85
107
 
86
108
  ### 2. Register the Server
87
109
 
88
- Add to `./servers/index.ts` to auto-build registries:
110
+ Add to `./internal/servers/index.ts` to auto-build registries:
89
111
 
90
112
  ```typescript
91
113
  import weather from './weather';
@@ -106,7 +128,7 @@ export const serverRegistry = registry;
106
128
 
107
129
  ### 3. Configure the Server
108
130
 
109
- Add to `./config.ts` (only specify `enabled` and `tools`):
131
+ Add to `./internal/config.ts` (only specify `enabled` and `tools`):
110
132
 
111
133
  ```typescript
112
134
  const mcpServersConfig: Record<ServerName, ServerConfig> = {
@@ -133,24 +155,33 @@ Tool available to Claude as: `mcp__calculator__calculate`
133
155
 
134
156
  ```
135
157
  backend/mcp/
136
- ├── types.ts # TypeScript type definitions (auto-inferred from metadata)
137
- ├── config.ts # User configuration (enabled, tools) + auto-merge with registry
138
- │ # + resolveOpenCodeToolName() & getOpenCodeMcpConfig()
139
- ├── index.ts # Main export point
140
- ├── remote-server.ts # Remote HTTP MCP server for Open Code (Streamable HTTP transport)
141
- ├── project-context.ts # Project context service for MCP tool handlers
142
- ├── servers/ # Server implementations (single source of truth)
143
- │ ├── index.ts # Auto-build registries from server array + export allServers
144
- │ ├── helper.ts # defineServer, buildServerRegistries & createRemoteMcpServer
145
- │ ├── weather/ # Example: Weather service
146
- │ │ ├── index.ts # Server definition using defineServer
147
- │ │ └── get-temperature.ts # Tool handler implementation
148
- │ └── browser-automation/ # Example: Browser automation service
149
- │ ├── index.ts # Server definition
150
- │ ├── actions.ts # Browser action handlers
151
- │ ├── browser.ts # Browser instance management
152
- │ └── inspection.ts # Page inspection handlers
153
- └── README.md # This file
158
+ ├── index.ts # FACADE — the only public entry point. Merges
159
+ │ # internal + external before handing config to adapters.
160
+ ├── shared/
161
+ │ └── constants.ts # Namespace constants/helpers (clopen-mcp, clopen-reserved prefix, slugify)
162
+ ├── internal/ # Custom tools defined in code (this README)
163
+ │ ├── types.ts # TypeScript type definitions (auto-inferred from metadata)
164
+ │ ├── config.ts # User configuration (enabled, tools) + auto-merge with registry
165
+ │ │ # + resolveOpenCodeToolName() & getXxxMcpConfig() (clopen-mcp)
166
+ │ ├── remote-server.ts# Remote HTTP MCP bridge for non-Claude engines (/mcp)
167
+ │ ├── project-context.ts # Project context service for MCP tool handlers
168
+ │ ├── output-validator.ts # Caps oversized tool outputs
169
+ │ └── servers/ # Server implementations (single source of truth)
170
+ │ ├── index.ts # Auto-build registries from server array + export allServers
171
+ │ ├── helper.ts # defineServer, buildServerRegistries & createRemoteMcpServer
172
+ │ ├── weather/ # Example: Weather service
173
+ │ │ ├── index.ts
174
+ │ │ └── get-temperature.ts
175
+ │ └── browser-automation/ # Example: Browser automation service
176
+ │ ├── index.ts
177
+ │ ├── actions.ts
178
+ │ ├── browser.ts
179
+ │ └── inspection.ts
180
+ ├── external/ # User-installed servers from the official registry
181
+ │ ├── types.ts # CatalogServer / ResolvedExternalServer
182
+ │ ├── registry-client.ts # Fetch + normalise registry.modelcontextprotocol.io
183
+ │ └── config.ts # Per-engine builders (bare <slug>) + resolveExternalToolName
184
+ └── README.md # This file
154
185
  ```
155
186
 
156
187
  ### Server Organization
@@ -258,9 +289,9 @@ its own transport and `McpServer` instance. Handles session lifecycle
258
289
 
259
290
  ### Folder Structure
260
291
 
261
- Each MCP server should be in its own folder under `./servers/`:
292
+ Each MCP server should be in its own folder under `./internal/servers/`:
262
293
 
263
- 1. **Create a folder**: `./servers/your-server-name/`
294
+ 1. **Create a folder**: `./internal/servers/your-server-name/`
264
295
  2. **Create index.ts**: Main server definition file
265
296
  3. **Optional**: Create separate files for tool handlers (e.g., `tool-name.ts`)
266
297
 
@@ -1040,7 +1071,7 @@ export default defineServer({
1040
1071
  **Problem:** My custom tool doesn't appear in Claude's available tools.
1041
1072
 
1042
1073
  **Solutions:**
1043
- 1. Verify server folder exists in `./servers/` with an `index.ts` file
1074
+ 1. Verify server folder exists in `./internal/servers/` with an `index.ts` file
1044
1075
  2. Verify server is defined using `defineServer` and exported as default (`export default defineServer(...)`)
1045
1076
  3. Check server is imported and added to `allServers` array in `servers/index.ts`
1046
1077
  4. Check that server is enabled in `mcpServersConfig` in `config.ts`
@@ -1171,11 +1202,15 @@ checklist in `backend/engine/README.md` §9.12. The summary:
1171
1202
 
1172
1203
  | File | Location | Purpose |
1173
1204
  |------|----------|---------|
1174
- | Tool definitions | `backend/mcp/servers/` | Single source of truth |
1175
- | Remote MCP server | `backend/mcp/remote-server.ts` | HTTP server for every non-Claude engine |
1176
- | Server factory | `backend/mcp/servers/helper.ts` | `createRemoteMcpServer()` |
1177
- | Per-engine config | `backend/mcp/config.ts` | `getOpenCodeMcpConfig()`, `getCodexMcpConfig()`, `getCopilotMcpConfig()` |
1178
- | Tool name resolver | `backend/mcp/config.ts` | `resolveOpenCodeToolName()` (handles every engine's prefix variant) |
1205
+ | Public facade | `backend/mcp/index.ts` | Only public entry; merges internal + external |
1206
+ | Tool definitions | `backend/mcp/internal/servers/` | Single source of truth (internal) |
1207
+ | Remote MCP server | `backend/mcp/internal/remote-server.ts` | HTTP bridge for every non-Claude engine |
1208
+ | Server factory | `backend/mcp/internal/servers/helper.ts` | `createRemoteMcpServer()` |
1209
+ | Per-engine config (internal) | `backend/mcp/internal/config.ts` | `getOpenCodeMcpConfig()`, `getCodexMcpConfig()`, … (clopen-mcp) |
1210
+ | Tool name resolver | `backend/mcp/internal/config.ts` | `resolveOpenCodeToolName()` (handles every engine's prefix variant) |
1211
+ | External catalog | `backend/mcp/external/registry-client.ts` | Browse the official MCP registry |
1212
+ | Per-engine config (external) | `backend/mcp/external/config.ts` | `getXxxExternalMcpConfig()` (<slug>) |
1213
+ | Namespace constants | `backend/mcp/shared/constants.ts` | `clopen-mcp`, clopen-reserved prefix, slugify |
1179
1214
 
1180
1215
  ---
1181
1216
 
@@ -0,0 +1,200 @@
1
+ /**
2
+ * External MCP — per-engine config builders.
3
+ *
4
+ * Reads enabled servers from the `mcp_servers` table and emits each engine's
5
+ * native MCP config shape. Every external server occupies its OWN namespace
6
+ * key (its bare `<slug>`; the `clopen` prefix is reserved for internal) — disjoint from the internal `clopen-mcp` bridge — so the
7
+ * two systems never collide. The facade (`backend/mcp/index.ts`) merges these
8
+ * with the internal config before handing them to an adapter.
9
+ *
10
+ * Unlike internal tools, external servers are real MCP servers the engine
11
+ * connects to directly (stdio subprocess or remote HTTP), NOT routed through
12
+ * Clopen's in-process `/mcp` bridge.
13
+ */
14
+
15
+ import type { McpServerConfig } from '@anthropic-ai/claude-agent-sdk';
16
+ import type { McpLocalConfig, McpRemoteConfig } from '@opencode-ai/sdk';
17
+ import type { MCPServerConfig as CopilotMcpServerConfig } from '@github/copilot-sdk';
18
+ import type { CLIMcpServerConfig as QwenMcpServerConfig } from '@qwen-code/sdk';
19
+ import { debug } from '$shared/utils/logger';
20
+ import { mcpServerQueries } from '$backend/database/queries';
21
+ import { externalNamespace } from '../shared/constants';
22
+ import type { ResolvedExternalServer } from './types';
23
+
24
+ /** Codex flattens `mcp_servers.<name>.<key>` config to `--config` flags. */
25
+ type CodexMcpServerConfig = {
26
+ command?: string;
27
+ args?: string[];
28
+ env?: Record<string, string>;
29
+ url?: string;
30
+ };
31
+
32
+ function parseJson<T>(raw: string, fallback: T): T {
33
+ try {
34
+ return JSON.parse(raw) as T;
35
+ } catch {
36
+ return fallback;
37
+ }
38
+ }
39
+
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 => ({
49
+ id: row.id,
50
+ slug: row.slug,
51
+ namespace: externalNamespace(row.slug),
52
+ name: row.name,
53
+ transport: row.transport,
54
+ command: row.command,
55
+ args: parseJson<string[]>(row.args, []),
56
+ env: parseJson<Record<string, string>>(row.env, {}),
57
+ url: row.url,
58
+ headers: parseJson<Record<string, string>>(row.headers, {})
59
+ }));
60
+ }
61
+
62
+ // ---------------------------------------------------------------------------
63
+ // Per-engine builders
64
+ // ---------------------------------------------------------------------------
65
+
66
+ /** Claude Agent SDK: stdio / sse / http config keyed by namespace. */
67
+ export function getClaudeExternalMcpConfig(): Record<string, McpServerConfig> {
68
+ const out: Record<string, McpServerConfig> = {};
69
+ for (const s of getEnabledExternalServers()) {
70
+ if (s.transport === 'stdio' && s.command) {
71
+ out[s.namespace] = { type: 'stdio', command: s.command, args: s.args, env: s.env };
72
+ } else if ((s.transport === 'http' || s.transport === 'sse') && s.url) {
73
+ out[s.namespace] = {
74
+ type: s.transport,
75
+ url: s.url,
76
+ ...(Object.keys(s.headers).length > 0 ? { headers: s.headers } : {})
77
+ };
78
+ }
79
+ }
80
+ logBuilt('Claude', out);
81
+ return out;
82
+ }
83
+
84
+ /** Open Code: `McpLocalConfig` (stdio) / `McpRemoteConfig` (http/sse). */
85
+ export function getOpenCodeExternalMcpConfig(): Record<string, McpLocalConfig | McpRemoteConfig> {
86
+ const out: Record<string, McpLocalConfig | McpRemoteConfig> = {};
87
+ for (const s of getEnabledExternalServers()) {
88
+ if (s.transport === 'stdio' && s.command) {
89
+ out[s.namespace] = {
90
+ type: 'local',
91
+ command: [s.command, ...s.args],
92
+ ...(Object.keys(s.env).length > 0 ? { environment: s.env } : {}),
93
+ enabled: true
94
+ };
95
+ } else if ((s.transport === 'http' || s.transport === 'sse') && s.url) {
96
+ out[s.namespace] = {
97
+ type: 'remote',
98
+ url: s.url,
99
+ enabled: true,
100
+ ...(Object.keys(s.headers).length > 0 ? { headers: s.headers } : {})
101
+ };
102
+ }
103
+ }
104
+ logBuilt('Open Code', out);
105
+ return out;
106
+ }
107
+
108
+ /**
109
+ * Codex: `mcp_servers.<name>` accepts a command (stdio) or url. Note: Codex
110
+ * requires per-tool `approval_mode` to auto-approve, but external tool names
111
+ * aren't known at install time (config-only, lazy spawn), so external MCP
112
+ * tool calls may be cancelled in non-interactive `codex exec`. The server is
113
+ * still registered so interactive/known-tool flows work.
114
+ */
115
+ export function getCodexExternalMcpConfig(): Record<string, CodexMcpServerConfig> {
116
+ const out: Record<string, CodexMcpServerConfig> = {};
117
+ for (const s of getEnabledExternalServers()) {
118
+ if (s.transport === 'stdio' && s.command) {
119
+ out[s.namespace] = {
120
+ command: s.command,
121
+ args: s.args,
122
+ ...(Object.keys(s.env).length > 0 ? { env: s.env } : {})
123
+ };
124
+ } else if ((s.transport === 'http' || s.transport === 'sse') && s.url) {
125
+ out[s.namespace] = { url: s.url };
126
+ }
127
+ }
128
+ logBuilt('Codex', out);
129
+ return out;
130
+ }
131
+
132
+ /** Copilot: `MCPStdioServerConfig` (stdio) / `MCPHTTPServerConfig` (http/sse). */
133
+ export function getCopilotExternalMcpConfig(): Record<string, CopilotMcpServerConfig> {
134
+ const out: Record<string, CopilotMcpServerConfig> = {};
135
+ for (const s of getEnabledExternalServers()) {
136
+ if (s.transport === 'stdio' && s.command) {
137
+ out[s.namespace] = { type: 'local', command: s.command, args: s.args, env: s.env };
138
+ } else if ((s.transport === 'http' || s.transport === 'sse') && s.url) {
139
+ out[s.namespace] = {
140
+ type: s.transport,
141
+ url: s.url,
142
+ ...(Object.keys(s.headers).length > 0 ? { headers: s.headers } : {})
143
+ };
144
+ }
145
+ }
146
+ logBuilt('Copilot', out);
147
+ return out;
148
+ }
149
+
150
+ /** Qwen Code: `CLIMcpServerConfig` — command (stdio) or url/httpUrl (remote). */
151
+ export function getQwenExternalMcpConfig(): Record<string, QwenMcpServerConfig> {
152
+ const out: Record<string, QwenMcpServerConfig> = {};
153
+ for (const s of getEnabledExternalServers()) {
154
+ if (s.transport === 'stdio' && s.command) {
155
+ out[s.namespace] = { command: s.command, args: s.args, env: s.env, trust: true };
156
+ } else if (s.transport === 'http' && s.url) {
157
+ out[s.namespace] = { httpUrl: s.url, headers: s.headers, trust: true };
158
+ } else if (s.transport === 'sse' && s.url) {
159
+ out[s.namespace] = { url: s.url, headers: s.headers, trust: true };
160
+ }
161
+ }
162
+ logBuilt('Qwen', out);
163
+ return out;
164
+ }
165
+
166
+ // ---------------------------------------------------------------------------
167
+ // Tool name resolution
168
+ // ---------------------------------------------------------------------------
169
+
170
+ /**
171
+ * Resolve an external MCP tool name (as a non-Claude engine reports it) into
172
+ * the canonical `mcp__<slug>__<tool>` form.
173
+ *
174
+ * Non-Claude engines join the namespace key and the bare tool name with a
175
+ * separator that varies by SDK (`_` for Open Code, `-` for Copilot). Because
176
+ * external namespaces are bare slugs that may themselves contain `-`, so splitting blindly is ambiguous
177
+ * — so we iterate the known enabled namespaces and strip whichever matches.
178
+ * Claude already emits `mcp__<slug>__<tool>`, handled by the internal
179
+ * resolver's pass-through.
180
+ *
181
+ * Returns null if the name doesn't belong to any enabled external server.
182
+ */
183
+ export function resolveExternalToolName(toolName: string): string | null {
184
+ for (const s of getEnabledExternalServers()) {
185
+ const ns = s.namespace;
186
+ if (toolName.startsWith(`mcp__${ns}__`)) return toolName;
187
+ for (const sep of ['_', '-']) {
188
+ const prefix = `${ns}${sep}`;
189
+ if (toolName.startsWith(prefix)) {
190
+ return `mcp__${ns}__${toolName.slice(prefix.length)}`;
191
+ }
192
+ }
193
+ }
194
+ return null;
195
+ }
196
+
197
+ function logBuilt(engine: string, out: Record<string, unknown>): void {
198
+ const count = Object.keys(out).length;
199
+ if (count > 0) debug.log('mcp', `🧩 ${engine} external MCP: ${count} server(s)`);
200
+ }