@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
@@ -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
  }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Integration tests for MCP Remote Server authentication.
3
+ *
4
+ * These exercise the real `handleMcpRequest` against the real auth queries and
5
+ * a real test database — the same pattern as files-upload.test.ts. We avoid
6
+ * `mock.module` for shared modules (`$backend/database/queries`,
7
+ * `$backend/auth/tokens`) because Bun applies module mocks process-globally,
8
+ * and a partial `authQueries` stub would leak into other integration tests.
9
+ */
10
+
11
+ import { describe, expect, test, beforeAll, afterAll, beforeEach } from 'bun:test';
12
+ import { randomUUID } from 'node:crypto';
13
+
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';
18
+
19
+ let testUserId: string;
20
+ let sessionToken: string;
21
+ let patToken: string;
22
+
23
+ function setAuthMode(mode: 'none' | 'required'): void {
24
+ settingsQueries.set('system:settings', JSON.stringify({ authMode: mode }));
25
+ }
26
+
27
+ function sessionCount(userId: string): number {
28
+ const row = getDatabase()
29
+ .prepare('SELECT COUNT(*) as count FROM auth_sessions WHERE user_id = ?')
30
+ .get(userId) as { count: number };
31
+ return row.count;
32
+ }
33
+
34
+ function mcpRequest(token?: string): Request {
35
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };
36
+ if (token) headers['Authorization'] = `Bearer ${token}`;
37
+ return new Request('http://localhost/mcp', {
38
+ method: 'POST',
39
+ headers,
40
+ body: JSON.stringify({
41
+ jsonrpc: '2.0',
42
+ method: 'initialize',
43
+ params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'test', version: '1.0' } },
44
+ id: 1
45
+ })
46
+ });
47
+ }
48
+
49
+ beforeAll(async () => {
50
+ await initializeDatabase();
51
+
52
+ // Test user authenticates with both a session token and a PAT.
53
+ patToken = generatePAT();
54
+ testUserId = `user-${randomUUID()}`;
55
+ authQueries.createUser({
56
+ id: testUserId,
57
+ name: 'MCP Test User',
58
+ color: '#000000',
59
+ avatar: 'mcp',
60
+ role: 'admin',
61
+ personal_access_token_hash: hashToken(patToken),
62
+ created_at: new Date().toISOString()
63
+ });
64
+
65
+ sessionToken = generateSessionToken();
66
+ authQueries.createSession({
67
+ id: randomUUID(),
68
+ user_id: testUserId,
69
+ token_hash: hashToken(sessionToken),
70
+ expires_at: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
71
+ created_at: new Date().toISOString(),
72
+ last_active_at: new Date().toISOString()
73
+ });
74
+ });
75
+
76
+ afterAll(() => {
77
+ authQueries.deleteSessionsByUserId(testUserId);
78
+ authQueries.deleteUser(testUserId);
79
+ settingsQueries.set('system:settings', JSON.stringify({ authMode: 'required' }));
80
+ closeDatabase();
81
+ });
82
+
83
+ describe('MCP Remote Server Authentication', () => {
84
+ beforeEach(() => {
85
+ setAuthMode('required');
86
+ });
87
+
88
+ test('rejects requests without an Authorization header', async () => {
89
+ const response = await handleMcpRequest(mcpRequest());
90
+ expect(response.status).toBe(401);
91
+
92
+ const body = await response.json();
93
+ expect(body.error).toBeDefined();
94
+ expect(body.error.code).toBe(-32001);
95
+ expect(body.error.message).toContain('Unauthorized');
96
+ });
97
+
98
+ test('rejects requests with an invalid Bearer token', async () => {
99
+ const response = await handleMcpRequest(mcpRequest('invalid-token-12345'));
100
+ expect(response.status).toBe(401);
101
+
102
+ const body = await response.json();
103
+ expect(body.error.code).toBe(-32001);
104
+ });
105
+
106
+ test('rejects requests with a malformed Authorization header', async () => {
107
+ const request = new Request('http://localhost/mcp', {
108
+ method: 'POST',
109
+ headers: { 'Content-Type': 'application/json', 'Authorization': 'InvalidFormat token123' },
110
+ body: JSON.stringify({ jsonrpc: '2.0', method: 'initialize', params: {}, id: 1 })
111
+ });
112
+ const response = await handleMcpRequest(request);
113
+ expect(response.status).toBe(401);
114
+ });
115
+
116
+ test('includes a WWW-Authenticate header in 401 responses', async () => {
117
+ const response = await handleMcpRequest(mcpRequest());
118
+ expect(response.status).toBe(401);
119
+ expect(response.headers.get('WWW-Authenticate')).toBe('Bearer realm="MCP Server"');
120
+ });
121
+
122
+ test('accepts a valid session token', async () => {
123
+ const response = await handleMcpRequest(mcpRequest(sessionToken));
124
+ // Past auth — the MCP transport handles the body from here.
125
+ expect(response.status).not.toBe(401);
126
+ });
127
+
128
+ test('accepts a valid PAT token', async () => {
129
+ const response = await handleMcpRequest(mcpRequest(patToken));
130
+ expect(response.status).not.toBe(401);
131
+ });
132
+
133
+ test('skips authentication in no-auth mode', async () => {
134
+ setAuthMode('none');
135
+ const response = await handleMcpRequest(mcpRequest());
136
+ expect(response.status).not.toBe(401);
137
+ });
138
+
139
+ test('validates via pure lookup without minting a session', async () => {
140
+ // Pins blocker #1: the validator must not behave like loginWithToken,
141
+ // which inserts a fresh session row on every call.
142
+ const before = sessionCount(testUserId);
143
+
144
+ await handleMcpRequest(mcpRequest(sessionToken));
145
+ await handleMcpRequest(mcpRequest(patToken));
146
+ await handleMcpRequest(mcpRequest(sessionToken));
147
+
148
+ expect(sessionCount(testUserId)).toBe(before);
149
+ });
150
+ });
@@ -16,6 +16,9 @@ import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
16
16
  import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
17
17
  import { createRemoteMcpServer } from './servers/helper';
18
18
  import { debug } from '$shared/utils/logger';
19
+ import { authQueries } from '$backend/database/queries';
20
+ import { hashToken } from '$backend/auth/tokens';
21
+ import { getAuthMode } from '$backend/auth/auth-service';
19
22
 
20
23
  // Lazy imports to avoid circular dependencies at module load time
21
24
  let _allServers: Parameters<typeof createRemoteMcpServer>[0] | null = null;
@@ -41,6 +44,53 @@ const transports = new Map<string, WebStandardStreamableHTTPServerTransport>();
41
44
  /** Active MCP servers keyed by MCP session ID */
42
45
  const servers = new Map<string, McpServer>();
43
46
 
47
+ /**
48
+ * Validate authentication token from request headers.
49
+ * Pure validator - does NOT create new sessions.
50
+ * Returns user info if valid, null otherwise.
51
+ */
52
+ function validateAuthToken(request: Request): { userId: string; role: string } | null {
53
+ const authHeader = request.headers.get('authorization');
54
+ if (!authHeader || !authHeader.toLowerCase().startsWith('bearer ')) {
55
+ return null;
56
+ }
57
+
58
+ const token = authHeader.substring(7).trim();
59
+ if (!token) {
60
+ return null;
61
+ }
62
+
63
+ const tokenHash = hashToken(token);
64
+
65
+ // Try session token first
66
+ const session = authQueries.getSessionByTokenHash(tokenHash);
67
+ if (session) {
68
+ if (new Date(session.expires_at) < new Date()) {
69
+ return null; // Expired
70
+ }
71
+ const user = authQueries.getUserById(session.user_id);
72
+ if (!user) {
73
+ return null;
74
+ }
75
+ return { userId: user.id, role: user.role };
76
+ }
77
+
78
+ // Try PAT (Personal Access Token)
79
+ const user = authQueries.getUserByPatHash(tokenHash);
80
+ if (user) {
81
+ return { userId: user.id, role: user.role };
82
+ }
83
+
84
+ return null;
85
+ }
86
+
87
+ /**
88
+ * Check if authentication is required based on auth mode.
89
+ */
90
+ function isAuthRequired(): boolean {
91
+ return getAuthMode() !== 'none';
92
+ }
93
+
44
94
  /**
45
95
  * Handle an incoming MCP HTTP request (GET/POST/DELETE).
46
96
  *
@@ -52,6 +102,24 @@ const servers = new Map<string, McpServer>();
52
102
  * - DELETE with session: close session
53
103
  */
54
104
  export async function handleMcpRequest(request: Request): Promise<Response> {
105
+ // Authentication check (skip if authMode is 'none')
106
+ if (isAuthRequired()) {
107
+ const auth = validateAuthToken(request);
108
+ if (!auth) {
109
+ return new Response(JSON.stringify({
110
+ jsonrpc: '2.0',
111
+ error: { code: -32001, message: 'Unauthorized: Valid Bearer token required' },
112
+ id: null,
113
+ }), {
114
+ status: 401,
115
+ headers: {
116
+ 'Content-Type': 'application/json',
117
+ 'WWW-Authenticate': 'Bearer realm="MCP Server"'
118
+ },
119
+ });
120
+ }
121
+ }
122
+
55
123
  const sessionId = request.headers.get('mcp-session-id');
56
124
 
57
125
  // Existing session — route to its transport
@@ -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
 
@@ -61,6 +61,12 @@ interface ServerWithMeta<
61
61
  createInstance: () => ReturnType<typeof createSdkMcpServer>;
62
62
  meta: {
63
63
  readonly name: TName;
64
+ /** Human-facing title shown in Settings → MCP and the Chat tool header. */
65
+ readonly title: string;
66
+ /** Short description of what this server provides. */
67
+ readonly description: string;
68
+ /** Semantic version, e.g. `1.0.0`. */
69
+ readonly version: string;
64
70
  readonly tools: TToolNames;
65
71
  /** Raw tool definitions (schema + description) for reuse by other transports */
66
72
  readonly toolDefs: Record<string, RawToolDef>;
@@ -73,6 +79,8 @@ interface ServerWithMeta<
73
79
  export function defineServer<
74
80
  const TConfig extends {
75
81
  name: string;
82
+ title: string;
83
+ description: string;
76
84
  version: string;
77
85
  tools: Record<string, { description: string; schema?: any; handler: any }>;
78
86
  }
@@ -123,6 +131,9 @@ export function defineServer<
123
131
  createInstance,
124
132
  meta: {
125
133
  name: config.name,
134
+ title: config.title,
135
+ description: config.description,
136
+ version: config.version,
126
137
  tools: toolNames as any,
127
138
  toolDefs,
128
139
  }
@@ -10,7 +10,6 @@
10
10
  * 3. Done! Registries are auto-built and type-safe.
11
11
  */
12
12
 
13
- import weather from './weather/index';
14
13
  import browserAutomation from './browser-automation/index';
15
14
  import { buildServerRegistries } from './helper';
16
15
 
@@ -25,7 +24,6 @@ export { createRemoteMcpServer } from './helper';
25
24
  * Metadata and registry will be automatically built.
26
25
  */
27
26
  export const allServers = [
28
- weather,
29
27
  browserAutomation,
30
28
  // Add more servers here...
31
29
  ] as const;
@@ -41,11 +41,11 @@ export type McpServerConfigWithInstance<S extends ServerName = ServerName> = Ser
41
41
  * Format: mcp__server-name__tool-name
42
42
  */
43
43
  export interface ParsedMcpToolName {
44
- /** Server name (e.g., "weather-service") */
44
+ /** Server name (e.g., "browser-automation") */
45
45
  server: string;
46
- /** Tool name (e.g., "get_temperature") */
46
+ /** Tool name (e.g., "navigate") */
47
47
  tool: string;
48
- /** Full tool name (e.g., "mcp__weather-service__get_temperature") */
48
+ /** Full tool name (e.g., "mcp__browser-automation__navigate") */
49
49
  fullName: string;
50
50
  }
51
51
 
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Shared MCP namespace constants
3
+ *
4
+ * Clopen exposes MCP tools from two distinct sources. Their namespace keys are
5
+ * kept disjoint on purpose so the two systems never collide:
6
+ *
7
+ * - INTERNAL (custom tools defined in `backend/mcp/internal/servers/` via
8
+ * `defineServer()`). Every non-Claude engine consumes them through the
9
+ * single remote-HTTP bridge whose namespace key is
10
+ * `INTERNAL_BRIDGE_NAMESPACE` (`clopen-mcp`). The `clopen` prefix is what
11
+ * marks a namespace as internal.
12
+ *
13
+ * - EXTERNAL (servers the user installs from the official MCP registry, see
14
+ * `backend/mcp/external/`). Each external server uses its BARE slug as the
15
+ * namespace key — no prefix. Tools surface as `mcp__<slug>__<tool>`.
16
+ *
17
+ * Invariants:
18
+ * - The `clopen` prefix is reserved for internal namespaces; external slugs
19
+ * must never start with it (enforced by `slugifyRegistryName`).
20
+ * - External slugs are unique and only contain `[a-z0-9-]`.
21
+ */
22
+
23
+ /** Namespace key of the internal remote-HTTP MCP bridge (`/mcp`). */
24
+ export const INTERNAL_BRIDGE_NAMESPACE = 'clopen-mcp';
25
+
26
+ /** Prefix reserved for internal MCP namespaces (marks a key as "ours"). */
27
+ export const INTERNAL_PREFIX = 'clopen';
28
+
29
+ /**
30
+ * Namespace key for an external server. External servers use their bare slug
31
+ * directly — no prefix. Kept as a function so call sites read intent and a
32
+ * future scheme change has a single seam.
33
+ */
34
+ export function externalNamespace(slug: string): string {
35
+ return slug;
36
+ }
37
+
38
+ /** True when a namespace key belongs to an internal server/bridge. */
39
+ export function isInternalNamespace(namespace: string): boolean {
40
+ return namespace === INTERNAL_BRIDGE_NAMESPACE || namespace.startsWith(`${INTERNAL_PREFIX}-`);
41
+ }
42
+
43
+ /**
44
+ * Sanitize an arbitrary registry server name into a safe, unique slug usable
45
+ * as an MCP namespace segment. Registry names are reverse-DNS
46
+ * (`io.github.foo/bar`) and contain `.` / `/` / uppercase which are illegal
47
+ * in the `mcp__<server>__<tool>` form. We lowercase, replace every
48
+ * non-`[a-z0-9]` run with a single `-`, and trim leading/trailing dashes.
49
+ *
50
+ * `io.github.foo/bar-baz` → `io-github-foo-bar-baz`
51
+ *
52
+ * The `clopen` prefix is reserved for internal namespaces — if a slug would
53
+ * start with it, we prefix `x-` so external keys can never shadow the internal
54
+ * bridge or an internal server.
55
+ */
56
+ export function slugifyRegistryName(name: string): string {
57
+ let slug = name
58
+ .toLowerCase()
59
+ .replace(/[^a-z0-9]+/g, '-')
60
+ .replace(/^-+|-+$/g, '');
61
+ if (!slug) slug = 'server';
62
+ if (slug === INTERNAL_PREFIX || slug.startsWith(`${INTERNAL_PREFIX}-`) || slug.startsWith(INTERNAL_PREFIX)) {
63
+ slug = `x-${slug}`;
64
+ }
65
+ return slug;
66
+ }
@@ -2,7 +2,7 @@
2
2
  * Default backend cleanup handlers for fully removed projects.
3
3
  */
4
4
  import { disposeProjectEngines } from '../engine';
5
- import { projectContextService } from '../mcp/project-context';
5
+ import { projectContextService } from '../mcp';
6
6
  import { fileWatcher } from '../files/file-watcher';
7
7
  import { clearProjectPresence } from '../project/status-manager';
8
8
  import { registerProjectCleanup } from './project-cleanup-registry';
@@ -86,17 +86,7 @@ class PtySessionManager {
86
86
  });
87
87
 
88
88
  debug.log('terminal', `✅ PTY spawned with PID: ${pty.pid}`);
89
-
90
- // CRITICAL: Send initial newline to trigger shell prompt display
91
- // Without this, shell won't show prompt on first connection
92
- setTimeout(() => {
93
- try {
94
- pty.write('\r');
95
- debug.log('terminal', '📝 Sent initial newline to trigger prompt');
96
- } catch (error) {
97
- debug.error('terminal', 'Failed to send initial newline:', error);
98
- }
99
- }, 100);
89
+ let receivedInitialOutput = false;
100
90
 
101
91
  // Create session
102
92
  const session: PtySession = {
@@ -117,6 +107,7 @@ class PtySessionManager {
117
107
 
118
108
  // Setup PTY event handlers with micro-task batching
119
109
  pty.onData((data: string) => {
110
+ receivedInitialOutput = true;
120
111
  session.lastActivityAt = new Date();
121
112
 
122
113
  // IMPORTANT: Always persist output to stream manager FIRST
@@ -158,6 +149,22 @@ class PtySessionManager {
158
149
  }
159
150
  });
160
151
 
152
+ // Some shells do not paint the first prompt until they receive input.
153
+ // Only send a fallback newline if the PTY stayed completely silent after
154
+ // spawn; otherwise it duplicates the initial prompt on normal shells.
155
+ setTimeout(() => {
156
+ if (receivedInitialOutput) {
157
+ return;
158
+ }
159
+
160
+ try {
161
+ pty.write('\r');
162
+ debug.log('terminal', '📝 Sent fallback newline to trigger prompt');
163
+ } catch (error) {
164
+ debug.error('terminal', 'Failed to send fallback newline:', error);
165
+ }
166
+ }, 350);
167
+
161
168
  pty.onExit((event: { exitCode: number; signal?: number | string }) => {
162
169
  debug.log('terminal', `🏁 PTY session ${sessionId} exited with code: ${event.exitCode}`);
163
170
  // Broadcast to all listeners
@@ -11,10 +11,12 @@ import { openCodeEngineRouter } from './opencode';
11
11
  import { copilotEngineRouter } from './copilot';
12
12
  import { codexEngineRouter } from './codex';
13
13
  import { qwenEngineRouter } from './qwen';
14
+ import { engineRestartRouter } from './restart';
14
15
 
15
16
  export const engineRouter = createRouter()
16
17
  .merge(claudeCodeEngineRouter)
17
18
  .merge(openCodeEngineRouter)
18
19
  .merge(copilotEngineRouter)
19
20
  .merge(codexEngineRouter)
20
- .merge(qwenEngineRouter);
21
+ .merge(qwenEngineRouter)
22
+ .merge(engineRestartRouter);