@myrialabs/clopen 0.3.21 → 0.4.0

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 (78) hide show
  1. package/backend/auth/permissions.ts +11 -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/claude/environment.ts +0 -17
  9. package/backend/engine/adapters/claude/error-handler.ts +0 -4
  10. package/backend/engine/adapters/codex/message-converter.ts +1 -1
  11. package/backend/engine/adapters/codex/stream.ts +1 -1
  12. package/backend/engine/adapters/copilot/message-converter.ts +1 -1
  13. package/backend/engine/adapters/copilot/stream.ts +1 -1
  14. package/backend/engine/adapters/qwen/message-converter.ts +1 -1
  15. package/backend/engine/adapters/qwen/stream.ts +1 -1
  16. package/backend/engine/docs/adapter-contract.md +2 -2
  17. package/backend/engine/docs/lessons-learned.md +3 -3
  18. package/backend/engine/docs/quick-reference.md +1 -1
  19. package/backend/engine/install-recipes.ts +26 -95
  20. package/backend/files/file-operations.test.ts +75 -0
  21. package/backend/files/file-operations.ts +10 -56
  22. package/backend/files/image-processing.test.ts +52 -0
  23. package/backend/files/image-processing.ts +11 -1
  24. package/backend/files/path-browsing.ts +141 -139
  25. package/backend/git/git-service.ts +13 -2
  26. package/backend/http/files-upload.test.ts +174 -0
  27. package/backend/http/files-upload.ts +27 -7
  28. package/backend/http/upload-temp-cleanup.ts +53 -0
  29. package/backend/index.ts +9 -1
  30. package/backend/mcp/README.md +67 -32
  31. package/backend/mcp/external/config.ts +200 -0
  32. package/backend/mcp/external/registry-client.ts +214 -0
  33. package/backend/mcp/external/types.ts +69 -0
  34. package/backend/mcp/index.ts +104 -19
  35. package/backend/mcp/{config.ts → internal/config.ts} +82 -18
  36. package/backend/mcp/internal/remote-server.test.ts +150 -0
  37. package/backend/mcp/{remote-server.ts → internal/remote-server.ts} +68 -0
  38. package/backend/mcp/{servers → internal/servers}/browser-automation/actions.ts +1 -1
  39. package/backend/mcp/{servers → internal/servers}/browser-automation/browser.ts +1 -1
  40. package/backend/mcp/{servers → internal/servers}/browser-automation/index.ts +2 -0
  41. package/backend/mcp/{servers → internal/servers}/browser-automation/inspection.ts +1 -1
  42. package/backend/mcp/{servers → internal/servers}/helper.ts +11 -0
  43. package/backend/mcp/{servers → internal/servers}/index.ts +0 -2
  44. package/backend/mcp/{types.ts → internal/types.ts} +3 -3
  45. package/backend/mcp/shared/constants.ts +66 -0
  46. package/backend/projects/project-cleanup.ts +1 -1
  47. package/backend/terminal/pty-session-manager.ts +18 -11
  48. package/backend/ws/engine/index.ts +3 -1
  49. package/backend/ws/engine/restart.ts +54 -0
  50. package/backend/ws/files/index.ts +5 -0
  51. package/backend/ws/files/reveal.ts +61 -0
  52. package/backend/ws/files/search.test.ts +115 -0
  53. package/backend/ws/files/search.ts +77 -26
  54. package/backend/ws/files/write.ts +3 -1
  55. package/backend/ws/git/branch-name.ts +170 -0
  56. package/backend/ws/git/branch.ts +15 -2
  57. package/backend/ws/git/commit-message.ts +8 -2
  58. package/backend/ws/git/index.ts +3 -1
  59. package/backend/ws/index.ts +5 -1
  60. package/backend/ws/mcp/catalog.ts +56 -0
  61. package/backend/ws/mcp/crud.ts +174 -0
  62. package/backend/ws/mcp/index.ts +18 -0
  63. package/backend/ws/user/crud.ts +8 -4
  64. package/dist/assets/main-B7f2Gzb3.css +1 -0
  65. package/dist/assets/main-DYt1fDrp.js +383 -0
  66. package/dist/index.html +2 -2
  67. package/package.json +1 -1
  68. package/shared/constants/git.ts +5 -0
  69. package/shared/types/git.ts +5 -0
  70. package/shared/types/stores/settings.ts +19 -0
  71. package/backend/mcp/servers/weather/get-temperature.ts +0 -56
  72. package/backend/mcp/servers/weather/index.ts +0 -31
  73. package/dist/assets/main-BgOiIS43.js +0 -360
  74. package/dist/assets/main-CJdJeen6.css +0 -1
  75. /package/backend/mcp/{output-validator.test.ts → internal/output-validator.test.ts} +0 -0
  76. /package/backend/mcp/{output-validator.ts → internal/output-validator.ts} +0 -0
  77. /package/backend/mcp/{project-context.test.ts → internal/project-context.test.ts} +0 -0
  78. /package/backend/mcp/{project-context.ts → internal/project-context.ts} +0 -0
@@ -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
+ }
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Official MCP Registry client.
3
+ *
4
+ * Browses servers from registry.modelcontextprotocol.io and normalises each
5
+ * into a single installable `CatalogServer`. The registry exposes a server as
6
+ * a set of `packages` (stdio runtimes such as npx/uvx/docker) and/or `remotes`
7
+ * (HTTP/SSE URLs). We pick a preferred target and flatten it into the install
8
+ * config Clopen stores.
9
+ *
10
+ * Docs: https://registry.modelcontextprotocol.io/docs#/operations/list-servers-v0.1
11
+ */
12
+
13
+ import { debug } from '$shared/utils/logger';
14
+ import type { McpTransport } from '$backend/database/queries';
15
+ import { slugifyRegistryName } from '../shared/constants';
16
+ import type { CatalogServer, CatalogEnvVar, CatalogPage } from './types';
17
+
18
+ const REGISTRY_BASE = 'https://registry.modelcontextprotocol.io/v0.1/servers';
19
+ const FETCH_TIMEOUT_MS = 20_000;
20
+
21
+ // ---------------------------------------------------------------------------
22
+ // Registry response shapes (only the subset we consume)
23
+ // ---------------------------------------------------------------------------
24
+
25
+ interface RegistryArgument {
26
+ type?: 'positional' | 'named';
27
+ name?: string;
28
+ value?: string;
29
+ default?: string;
30
+ }
31
+
32
+ interface RegistryEnvVar {
33
+ name: string;
34
+ description?: string;
35
+ isRequired?: boolean;
36
+ isSecret?: boolean;
37
+ default?: string;
38
+ }
39
+
40
+ interface RegistryPackage {
41
+ registryType?: string;
42
+ identifier?: string;
43
+ version?: string;
44
+ runtimeHint?: string;
45
+ transport?: { type?: string };
46
+ runtimeArguments?: RegistryArgument[];
47
+ packageArguments?: RegistryArgument[];
48
+ environmentVariables?: RegistryEnvVar[];
49
+ }
50
+
51
+ interface RegistryRemote {
52
+ type?: string;
53
+ url: string;
54
+ /** Header inputs the server requires (auth tokens, API keys). */
55
+ headers?: RegistryEnvVar[];
56
+ }
57
+
58
+ interface RegistryServer {
59
+ name: string;
60
+ title?: string;
61
+ description?: string;
62
+ version?: string;
63
+ packages?: RegistryPackage[];
64
+ remotes?: RegistryRemote[];
65
+ }
66
+
67
+ interface RegistryListResponse {
68
+ servers: Array<{ server: RegistryServer }>;
69
+ metadata?: { nextCursor?: string | null; count?: number };
70
+ }
71
+
72
+ // ---------------------------------------------------------------------------
73
+ // Mapping helpers
74
+ // ---------------------------------------------------------------------------
75
+
76
+ /** Map a registry package registryType to its default CLI runtime. */
77
+ function inferRuntime(registryType: string | undefined): string | null {
78
+ switch (registryType) {
79
+ case 'npm': return 'npx';
80
+ case 'pypi': return 'uvx';
81
+ case 'oci': return 'docker';
82
+ case 'nuget': return 'dnx';
83
+ default: return null;
84
+ }
85
+ }
86
+
87
+ /** Flatten a single registry argument into zero or more CLI tokens. */
88
+ function argTokens(arg: RegistryArgument): string[] {
89
+ const tokens: string[] = [];
90
+ if (arg.type === 'named' && arg.name) tokens.push(arg.name);
91
+ const val = arg.value ?? arg.default;
92
+ if (val != null && val !== '') tokens.push(String(val));
93
+ return tokens;
94
+ }
95
+
96
+ function mapEnvVars(vars: RegistryEnvVar[] | undefined): CatalogEnvVar[] {
97
+ return (vars ?? []).map(v => ({
98
+ name: v.name,
99
+ description: v.description,
100
+ isRequired: Boolean(v.isRequired),
101
+ isSecret: Boolean(v.isSecret),
102
+ default: v.default
103
+ }));
104
+ }
105
+
106
+ /** Build a stdio command + args from a registry package. Returns null if unsupported. */
107
+ function resolveStdioPackage(pkg: RegistryPackage): { command: string; args: string[] } | null {
108
+ const command = pkg.runtimeHint || inferRuntime(pkg.registryType);
109
+ if (!command || !pkg.identifier) return null;
110
+
111
+ const args: string[] = [];
112
+ for (const a of pkg.runtimeArguments ?? []) args.push(...argTokens(a));
113
+
114
+ // Package identifier token (with version for npm-style registries).
115
+ const identifier = pkg.version && pkg.registryType === 'npm'
116
+ ? `${pkg.identifier}@${pkg.version}`
117
+ : pkg.identifier;
118
+ args.push(identifier);
119
+
120
+ for (const a of pkg.packageArguments ?? []) args.push(...argTokens(a));
121
+ return { command, args };
122
+ }
123
+
124
+ /** Normalise one registry server into a single installable target, or null. */
125
+ export function mapRegistryServer(server: RegistryServer): CatalogServer | null {
126
+ const base = {
127
+ registryName: server.name,
128
+ slug: slugifyRegistryName(server.name),
129
+ title: server.title || server.name,
130
+ description: server.description || '',
131
+ version: server.version || ''
132
+ };
133
+
134
+ // Prefer a self-contained stdio package; fall back to a remote URL.
135
+ const pkg = (server.packages ?? []).find(p => (p.transport?.type ?? 'stdio') === 'stdio') ?? server.packages?.[0];
136
+ if (pkg) {
137
+ const stdio = resolveStdioPackage(pkg);
138
+ if (stdio) {
139
+ return {
140
+ ...base,
141
+ transport: 'stdio' as McpTransport,
142
+ command: stdio.command,
143
+ args: stdio.args,
144
+ envVars: mapEnvVars(pkg.environmentVariables),
145
+ headerVars: [],
146
+ packageHint: pkg.registryType && pkg.identifier ? `${pkg.registryType}:${pkg.identifier}` : undefined
147
+ };
148
+ }
149
+ }
150
+
151
+ const remote = server.remotes?.[0];
152
+ if (remote?.url) {
153
+ return {
154
+ ...base,
155
+ transport: (remote.type === 'sse' ? 'sse' : 'http') as McpTransport,
156
+ url: remote.url,
157
+ envVars: [],
158
+ // Auth tokens / API keys the remote server requires as HTTP headers.
159
+ headerVars: mapEnvVars(remote.headers)
160
+ };
161
+ }
162
+
163
+ return null;
164
+ }
165
+
166
+ // ---------------------------------------------------------------------------
167
+ // Public API
168
+ // ---------------------------------------------------------------------------
169
+
170
+ /**
171
+ * List registry servers, normalised. Supports search and cursor pagination.
172
+ * Servers with no installable target are dropped.
173
+ */
174
+ export async function listRegistryServers(opts: { search?: string; cursor?: string; limit?: number } = {}): Promise<CatalogPage> {
175
+ const params = new URLSearchParams();
176
+ if (opts.search) params.set('search', opts.search);
177
+ if (opts.cursor) params.set('cursor', opts.cursor);
178
+ params.set('limit', String(opts.limit ?? 30));
179
+ // Only the latest version of each server — the registry otherwise returns
180
+ // one entry per published version (e.g. 1.0.0 AND 1.0.1).
181
+ params.set('version', 'latest');
182
+
183
+ const url = `${REGISTRY_BASE}?${params.toString()}`;
184
+ const controller = new AbortController();
185
+ const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
186
+
187
+ try {
188
+ const res = await fetch(url, {
189
+ signal: controller.signal,
190
+ headers: { Accept: 'application/json' }
191
+ });
192
+ if (!res.ok) {
193
+ throw new Error(`Registry responded ${res.status} ${res.statusText}`);
194
+ }
195
+ const data = (await res.json()) as RegistryListResponse;
196
+ const servers = (data.servers ?? [])
197
+ .map(entry => mapRegistryServer(entry.server))
198
+ .filter((s): s is CatalogServer => s !== null);
199
+
200
+ debug.log('mcp', `🛰️ Registry catalog page: ${servers.length} installable servers`);
201
+ return { servers, nextCursor: data.metadata?.nextCursor ?? null };
202
+ } catch (error) {
203
+ // The registry is intermittently slow; surface a clean, retryable message
204
+ // instead of the raw "The operation was aborted." DOMException.
205
+ if (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {
206
+ debug.warn('mcp', `MCP registry request timed out after ${FETCH_TIMEOUT_MS}ms`);
207
+ throw new Error('The MCP registry took too long to respond. Please try again.');
208
+ }
209
+ debug.error('mcp', 'Failed to fetch MCP registry:', error);
210
+ throw error;
211
+ } finally {
212
+ clearTimeout(timeout);
213
+ }
214
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * External (user-installed) MCP — shared types.
3
+ *
4
+ * These describe servers sourced from the official MCP registry and stored in
5
+ * the `mcp_servers` table. Distinct from the internal custom-tool servers.
6
+ */
7
+
8
+ import type { McpTransport } from '$backend/database/queries';
9
+
10
+ /** An environment variable an external server needs (surfaced from registry). */
11
+ export interface CatalogEnvVar {
12
+ name: string;
13
+ description?: string;
14
+ isRequired: boolean;
15
+ isSecret: boolean;
16
+ default?: string;
17
+ }
18
+
19
+ /**
20
+ * A registry server normalised into a single installable target.
21
+ *
22
+ * The registry exposes a server as a set of `packages` (stdio runtimes) and/or
23
+ * `remotes` (HTTP/SSE URLs). We pick one preferred target and flatten it into
24
+ * the install config Clopen stores. `envVars` is what the UI prompts for.
25
+ */
26
+ export interface CatalogServer {
27
+ /** Original reverse-DNS registry name, e.g. `io.github.foo/bar`. */
28
+ registryName: string;
29
+ /** Sanitised unique slug; the `<slug>` namespace is derived from it. */
30
+ slug: string;
31
+ title: string;
32
+ description: string;
33
+ version: string;
34
+ transport: McpTransport;
35
+ /** stdio target. */
36
+ command?: string;
37
+ args?: string[];
38
+ /** http/sse target. */
39
+ url?: string;
40
+ /** Env vars the user must/may provide before the server can run (stdio). */
41
+ envVars: CatalogEnvVar[];
42
+ /** HTTP header inputs the remote server requires (auth tokens, API keys). */
43
+ headerVars: CatalogEnvVar[];
44
+ /** Human hint of the underlying package, e.g. `npm:@scope/pkg`. */
45
+ packageHint?: string;
46
+ }
47
+
48
+ /** A page of catalog results plus the registry pagination cursor. */
49
+ export interface CatalogPage {
50
+ servers: CatalogServer[];
51
+ nextCursor: string | null;
52
+ }
53
+
54
+ /**
55
+ * A server resolved from a DB row, ready to be turned into per-engine MCP
56
+ * config. JSON columns are parsed; `namespace` is the `<slug>` key.
57
+ */
58
+ export interface ResolvedExternalServer {
59
+ id: number;
60
+ slug: string;
61
+ namespace: string;
62
+ name: string;
63
+ transport: McpTransport;
64
+ command: string | null;
65
+ args: string[];
66
+ env: Record<string, string>;
67
+ url: string | null;
68
+ headers: Record<string, string>;
69
+ }
@@ -1,25 +1,45 @@
1
1
  /**
2
- * MCP (Model Context Protocol) Custom Tools
2
+ * MCP (Model Context Protocol) — public facade.
3
3
  *
4
- * Main export point for the custom MCP tools system.
4
+ * This is the ONLY entry point the rest of the backend imports from. It hides
5
+ * the internal/external split and merges the two before handing config to an
6
+ * engine adapter:
5
7
  *
6
- * Claude Code: in-process MCP servers via createSdkMcpServer()
7
- * Open Code: remote HTTP MCP server via createRemoteMcpServer()
8
+ * - INTERNAL (`./internal`) — custom tools defined in code via
9
+ * `defineServer()`. Claude runs them in-process; other engines reach them
10
+ * through the `/mcp` remote bridge (namespace `clopen-mcp`).
11
+ * - EXTERNAL (`./external`) — servers the user installs from the official
12
+ * MCP registry, stored in the `mcp_servers` table. Each occupies its own
13
+ * `<slug>` namespace and is connected to directly by the engine.
8
14
  *
9
- * Both use the same tool definitions from defineServer() in servers/helper.ts.
15
+ * Adapters call `getEnabledMcpServers()` / `getXxxMcpConfig()` /
16
+ * `resolveOpenCodeToolName()` here and receive the COMBINED view. The internal
17
+ * builders (which only know about `clopen-mcp`) live in `./internal/config`
18
+ * and are wrapped below.
10
19
  */
11
20
 
12
- // Type definitions
21
+ import type { McpExecutionContext } from '../engine/types';
22
+ import type { McpServerConfig } from '@anthropic-ai/claude-agent-sdk';
23
+
24
+ import * as internal from './internal/config';
25
+ import * as external from './external/config';
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // Types
29
+ // ---------------------------------------------------------------------------
30
+
13
31
  export type {
14
32
  ParsedMcpToolName,
15
33
  McpServerStatus
16
- } from './types';
34
+ } from './internal/types';
35
+
36
+ // ---------------------------------------------------------------------------
37
+ // Internal config — re-exported unchanged (no external dimension)
38
+ // ---------------------------------------------------------------------------
17
39
 
18
- // Main configuration and all utilities
19
40
  export {
20
41
  mcpServers,
21
42
  mcpServersConfig,
22
- getEnabledMcpServers,
23
43
  getAllowedMcpTools,
24
44
  getServerConfig,
25
45
  getToolConfig,
@@ -30,17 +50,82 @@ export {
30
50
  getEnabledServerNames,
31
51
  getEnabledToolsForServer,
32
52
  getMcpStats,
33
- getOpenCodeMcpConfig,
34
- getCodexMcpConfig,
35
- getCopilotMcpConfig,
36
- resolveOpenCodeToolName
37
- } from './config';
53
+ syncInternalServers,
54
+ refreshInternalEnabledCache
55
+ } from './internal/config';
38
56
 
39
- // Server implementations
40
- export * from './servers';
57
+ // Internal server implementations + registries
58
+ export * from './internal/servers';
41
59
 
42
- // Remote MCP HTTP server for Open Code
43
- export { handleMcpRequest, closeMcpServer } from './remote-server';
60
+ // Remote MCP HTTP bridge (serves internal tools to non-Claude engines)
61
+ export { handleMcpRequest, closeMcpServer } from './internal/remote-server';
44
62
 
45
63
  // Project context service for MCP tool handlers
46
- export { projectContextService } from './project-context';
64
+ export { projectContextService } from './internal/project-context';
65
+
66
+ // Shared namespace constants/helpers
67
+ export {
68
+ INTERNAL_BRIDGE_NAMESPACE,
69
+ INTERNAL_PREFIX,
70
+ externalNamespace,
71
+ isInternalNamespace,
72
+ slugifyRegistryName
73
+ } from './shared/constants';
74
+
75
+ // External catalog + types (used by the WS layer and Settings → MCP)
76
+ export { listRegistryServers, mapRegistryServer } from './external/registry-client';
77
+ export { getEnabledExternalServers } from './external/config';
78
+ export type { CatalogServer, CatalogEnvVar, CatalogPage, ResolvedExternalServer } from './external/types';
79
+
80
+ // ---------------------------------------------------------------------------
81
+ // Merged config builders (internal `clopen-mcp` + external bare `<slug>`)
82
+ // ---------------------------------------------------------------------------
83
+
84
+ /** Claude Agent SDK `mcpServers`: in-process internal servers + external stdio/remote. */
85
+ export function getEnabledMcpServers(context?: McpExecutionContext): Record<string, McpServerConfig> {
86
+ return {
87
+ ...internal.getEnabledMcpServers(context),
88
+ ...external.getClaudeExternalMcpConfig()
89
+ };
90
+ }
91
+
92
+ /** Open Code MCP config: internal `clopen-mcp` remote bridge + external servers. */
93
+ export function getOpenCodeMcpConfig() {
94
+ return {
95
+ ...internal.getOpenCodeMcpConfig(),
96
+ ...external.getOpenCodeExternalMcpConfig()
97
+ };
98
+ }
99
+
100
+ /** Codex MCP config. */
101
+ export function getCodexMcpConfig() {
102
+ return {
103
+ ...internal.getCodexMcpConfig(),
104
+ ...external.getCodexExternalMcpConfig()
105
+ };
106
+ }
107
+
108
+ /** Copilot MCP config. */
109
+ export function getCopilotMcpConfig() {
110
+ return {
111
+ ...internal.getCopilotMcpConfig(),
112
+ ...external.getCopilotExternalMcpConfig()
113
+ };
114
+ }
115
+
116
+ /** Qwen Code MCP config. */
117
+ export function getQwenMcpConfig() {
118
+ return {
119
+ ...internal.getQwenMcpConfig(),
120
+ ...external.getQwenExternalMcpConfig()
121
+ };
122
+ }
123
+
124
+ /**
125
+ * Resolve a remote-engine tool name to `mcp__<server>__<tool>`. Tries the
126
+ * internal resolver (handles `clopen-mcp` + already-canonical names) first,
127
+ * then the external resolver (handles `<slug>` namespaces).
128
+ */
129
+ export function resolveOpenCodeToolName(toolName: string): string | null {
130
+ return internal.resolveOpenCodeToolName(toolName) ?? external.resolveExternalToolName(toolName);
131
+ }