@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
@@ -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
+ }
@@ -10,11 +10,12 @@ import type { McpRemoteConfig } from '@opencode-ai/sdk';
10
10
  import type { MCPHTTPServerConfig } from '@github/copilot-sdk';
11
11
  import type { CLIMcpServerConfig as QwenMcpServerConfig } from '@qwen-code/sdk';
12
12
  import type { ServerConfig, ParsedMcpToolName, ServerName } from './types';
13
- import type { McpExecutionContext } from '../engine/types';
13
+ import type { McpExecutionContext } from '../../engine/types';
14
14
  import { serverRegistry, serverFactories, serverMetadata } from './servers';
15
15
  import { projectContextService } from './project-context';
16
+ import { mcpServerQueries } from '$backend/database/queries';
16
17
  import { debug } from '$shared/utils/logger';
17
- import { SERVER_ENV } from '../utils/env';
18
+ import { SERVER_ENV } from '../../utils/env';
18
19
  import { validateMcpOutput } from './output-validator';
19
20
 
20
21
  /**
@@ -26,12 +27,6 @@ import { validateMcpOutput } from './output-validator';
26
27
  * Type-safe: Server names and tool names are validated at compile time!
27
28
  */
28
29
  export const mcpServersConfig: Record<ServerName, ServerConfig> = {
29
- "weather-service": {
30
- enabled: true,
31
- tools: [
32
- "get_temperature",
33
- ]
34
- },
35
30
  "browser-automation": {
36
31
  enabled: true,
37
32
  tools: [
@@ -83,6 +78,39 @@ function createServerConfig<T extends Record<ServerName, ServerConfig>>(
83
78
  */
84
79
  export const mcpServers: Record<string, ServerConfig & { instance: McpSdkServerConfigWithInstance }> = createServerConfig(mcpServersConfig);
85
80
 
81
+ // ============================================================================
82
+ // Runtime enabled state (DB-backed)
83
+ // ============================================================================
84
+
85
+ /**
86
+ * In-memory mirror of each internal server's enabled toggle, keyed by server
87
+ * name (= the seeded `slug`). The DB row in `mcp_servers` is the source of
88
+ * truth; this cache avoids a query on every tool-name resolution. Refreshed at
89
+ * startup (after `syncInternalServers`) and whenever the user toggles a server.
90
+ */
91
+ let internalEnabledCache: Record<string, boolean> | null = null;
92
+
93
+ /** Reload the internal enabled-state cache from the DB. */
94
+ export function refreshInternalEnabledCache(): void {
95
+ const map: Record<string, boolean> = {};
96
+ for (const row of mcpServerQueries.getBySource('internal')) {
97
+ map[row.slug] = row.is_enabled === 1;
98
+ }
99
+ internalEnabledCache = map;
100
+ }
101
+
102
+ /**
103
+ * Whether an internal server is enabled right now. Combines the static config
104
+ * (which tools exist) with the user's DB-backed toggle. Defaults to enabled if
105
+ * the row hasn't been seeded yet (sync runs at startup, before any stream).
106
+ */
107
+ function serverEnabled(serverName: string): boolean {
108
+ const cfg = mcpServers[serverName];
109
+ if (!cfg?.enabled) return false;
110
+ if (internalEnabledCache === null) refreshInternalEnabledCache();
111
+ return internalEnabledCache?.[serverName] ?? true;
112
+ }
113
+
86
114
  // ============================================================================
87
115
  // Server Registry Functions
88
116
  // ============================================================================
@@ -103,7 +131,7 @@ export function getEnabledMcpServers(context?: McpExecutionContext): Record<stri
103
131
  const enabledServers: Record<string, McpServerConfig> = {};
104
132
 
105
133
  Object.entries(mcpServers).forEach(([serverName, serverConfig]) => {
106
- if (serverConfig.enabled) {
134
+ if (serverEnabled(serverName)) {
107
135
  if (context) {
108
136
  // Create context-bound instance: wrap each tool handler so
109
137
  // AsyncLocalStorage context is restored on invocation, then
@@ -168,13 +196,13 @@ export { abortedToolResult };
168
196
  * Get list of all allowed MCP tool names
169
197
  *
170
198
  * Tool names follow the format: mcp__{server-name}__{tool-name}
171
- * Example: "mcp__weather-service__get_temperature"
199
+ * Example: "mcp__browser-automation__navigate"
172
200
  */
173
201
  export function getAllowedMcpTools(): string[] {
174
202
  const tools: string[] = [];
175
203
 
176
204
  Object.entries(mcpServers).forEach(([serverName, serverConfig]) => {
177
- if (!serverConfig.enabled) return;
205
+ if (!serverEnabled(serverName)) return;
178
206
 
179
207
  serverConfig.tools.forEach((toolName) => {
180
208
  const formattedName = `mcp__${serverName}__${toolName}`;
@@ -211,7 +239,7 @@ export function getToolConfig(serverName: string, toolName: string): boolean {
211
239
  * Check if a server is enabled
212
240
  */
213
241
  export function isServerEnabled(serverName: string): boolean {
214
- return mcpServers[serverName]?.enabled ?? false;
242
+ return serverEnabled(serverName);
215
243
  }
216
244
 
217
245
  /**
@@ -219,7 +247,7 @@ export function isServerEnabled(serverName: string): boolean {
219
247
  */
220
248
  export function isToolEnabled(serverName: string, toolName: string): boolean {
221
249
  const server = mcpServers[serverName];
222
- if (!server?.enabled) return false;
250
+ if (!server || !serverEnabled(serverName)) return false;
223
251
 
224
252
  return server.tools.includes(toolName as any);
225
253
  }
@@ -232,7 +260,7 @@ export function isToolEnabled(serverName: string, toolName: string): boolean {
232
260
  * Parse MCP tool name into components
233
261
  *
234
262
  * Format: mcp__{server-name}__{tool-name}
235
- * Example: "mcp__weather-service__get_temperature"
263
+ * Example: "mcp__browser-automation__navigate"
236
264
  */
237
265
  export function parseMcpToolName(fullName: string): ParsedMcpToolName | null {
238
266
  if (!fullName.startsWith('mcp__')) {
@@ -268,8 +296,8 @@ export function isMcpTool(toolName: string): boolean {
268
296
  */
269
297
  export function getEnabledServerNames(): string[] {
270
298
  return Object.entries(mcpServers)
271
- .filter(([_, config]) => config.enabled)
272
- .map(([name, _]) => name);
299
+ .filter(([name]) => serverEnabled(name))
300
+ .map(([name]) => name);
273
301
  }
274
302
 
275
303
  /**
@@ -277,7 +305,7 @@ export function getEnabledServerNames(): string[] {
277
305
  */
278
306
  export function getEnabledToolsForServer(serverName: string): string[] {
279
307
  const serverConfig = mcpServers[serverName];
280
- if (!serverConfig?.enabled) {
308
+ if (!serverConfig || !serverEnabled(serverName)) {
281
309
  return [];
282
310
  }
283
311
 
@@ -300,6 +328,42 @@ export function getMcpStats() {
300
328
  };
301
329
  }
302
330
 
331
+ // ============================================================================
332
+ // Internal server ↔ DB sync
333
+ // ============================================================================
334
+
335
+ /**
336
+ * Mirror the code-defined internal servers into the `mcp_servers` table so
337
+ * Settings → MCP can list them alongside external servers and the user can
338
+ * toggle them on/off. Definitions stay the source of truth in code; the DB row
339
+ * only carries display metadata + the enabled flag.
340
+ *
341
+ * Idempotent: refreshes title/description/version for known servers (preserving
342
+ * the user's enabled toggle), seeds new ones as enabled, and prunes rows whose
343
+ * code definition was removed. Call once at startup, after the DB is ready.
344
+ */
345
+ export function syncInternalServers(): void {
346
+ const metas = Object.values(serverMetadata) as Array<{
347
+ name: string;
348
+ title: string;
349
+ description: string;
350
+ version: string;
351
+ }>;
352
+ const slugs: string[] = [];
353
+ for (const meta of metas) {
354
+ mcpServerQueries.upsertInternal({
355
+ slug: meta.name,
356
+ name: meta.title,
357
+ description: meta.description,
358
+ version: meta.version
359
+ });
360
+ slugs.push(meta.name);
361
+ }
362
+ mcpServerQueries.pruneInternalExcept(slugs);
363
+ refreshInternalEnabledCache();
364
+ debug.log('mcp', `🔄 Synced ${slugs.length} internal MCP server(s) to DB`);
365
+ }
366
+
303
367
  // ============================================================================
304
368
  // Open Code Tool Name Resolution (single source of truth)
305
369
  // ============================================================================
@@ -342,7 +406,7 @@ export function resolveOpenCodeToolName(toolName: string): string | null {
342
406
 
343
407
  // Look up which server owns this tool
344
408
  for (const [serverName, serverConfig] of Object.entries(mcpServers)) {
345
- if (!serverConfig.enabled) continue;
409
+ if (!serverEnabled(serverName)) continue;
346
410
  if ((serverConfig.tools as readonly string[]).includes(rawName)) {
347
411
  return `mcp__${serverName}__${rawName}`;
348
412
  }
@@ -12,9 +12,9 @@ import { describe, expect, test, beforeAll, afterAll, beforeEach } from 'bun:tes
12
12
  import { randomUUID } from 'node:crypto';
13
13
 
14
14
  import { handleMcpRequest } from './remote-server';
15
- import { authQueries, settingsQueries } from '../database/queries';
16
- import { generatePAT, generateSessionToken, hashToken } from '../auth/tokens';
17
- import { initializeDatabase, closeDatabase, getDatabase } from '../database';
15
+ import { authQueries, settingsQueries } from '../../database/queries';
16
+ import { generatePAT, generateSessionToken, hashToken } from '../../auth/tokens';
17
+ import { initializeDatabase, closeDatabase, getDatabase } from '../../database';
18
18
 
19
19
  let testUserId: string;
20
20
  let sessionToken: string;
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { browserPreviewServiceManager, type BrowserPreviewService } from "$backend/preview";
6
6
  import type { BrowserAutonomousAction } from "$backend/preview/browser/types";
7
- import { projectContextService } from "$backend/mcp/project-context";
7
+ import { projectContextService } from "$backend/mcp/internal/project-context";
8
8
  import { getActiveTabSession } from "./browser";
9
9
  import { debug } from "$shared/utils/logger";
10
10
 
@@ -15,7 +15,7 @@
15
15
 
16
16
  import { debug } from "$shared/utils/logger";
17
17
  import { browserMcpControl, browserPreviewServiceManager, type BrowserPreviewService } from "$backend/preview";
18
- import { projectContextService } from "$backend/mcp/project-context";
18
+ import { projectContextService } from "$backend/mcp/internal/project-context";
19
19
 
20
20
  /**
21
21
  * Get BrowserPreviewService for current MCP execution context
@@ -14,6 +14,8 @@ import { getConsoleLogsHandler, clearConsoleLogsHandler, executeConsoleHandler,
14
14
 
15
15
  export default defineServer({
16
16
  name: "browser-automation",
17
+ title: "Browser Automation",
18
+ description: "Drives the built-in Preview Browser panel — navigate, click, type, and inspect pages, running multiple actions in one call for efficient interaction.",
17
19
  version: "1.0.0",
18
20
  tools: {
19
21
  // ============================================================================
@@ -3,7 +3,7 @@
3
3
  */
4
4
 
5
5
  import { browserPreviewServiceManager, type BrowserPreviewService } from "$backend/preview";
6
- import { projectContextService } from "$backend/mcp/project-context";
6
+ import { projectContextService } from "$backend/mcp/internal/project-context";
7
7
  import { getActiveTabSession } from "./browser";
8
8
  import { debug } from "$shared/utils/logger";
9
9