@myrialabs/clopen 0.4.32 → 0.4.34

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 (102) hide show
  1. package/backend/auth/permissions.ts +3 -0
  2. package/backend/auth/rate-limiter.test.ts +115 -0
  3. package/backend/auth/rate-limiter.ts +25 -12
  4. package/backend/chat/stream-manager.ts +4 -1
  5. package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
  6. package/backend/database/migrations/index.ts +7 -0
  7. package/backend/database/queries/db-client-connection-queries.ts +7 -2
  8. package/backend/database/queries/file-audit-log-queries.ts +1 -0
  9. package/backend/database/queries/index.ts +3 -0
  10. package/backend/database/queries/ssh-connection-queries.ts +244 -0
  11. package/backend/database/queries/ssh-known-host-queries.ts +67 -0
  12. package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
  13. package/backend/db-client/connection-manager.ts +21 -1
  14. package/backend/engine/adapters/codex/message-converter.ts +18 -12
  15. package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
  16. package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
  17. package/backend/engine/adapters/codex/stream.ts +33 -4
  18. package/backend/engine/adapters/copilot/stream.ts +1 -1
  19. package/backend/engine/adapters/cursor/stream.ts +1 -1
  20. package/backend/engine/adapters/qwen/stream.ts +1 -1
  21. package/backend/engine/docs/adapter-contract.md +7 -0
  22. package/backend/files/file-watcher.ts +283 -51
  23. package/backend/files/git-events.test.ts +110 -0
  24. package/backend/git/git-dirs.test.ts +132 -0
  25. package/backend/git/git-dirs.ts +0 -0
  26. package/backend/git/nested-repos.test.ts +108 -5
  27. package/backend/git/nested-repos.ts +103 -18
  28. package/backend/http/audio.ts +5 -32
  29. package/backend/http/bearer-auth.ts +47 -0
  30. package/backend/http/files-download.test.ts +146 -0
  31. package/backend/http/files-download.ts +109 -0
  32. package/backend/http/files-upload.ts +3 -29
  33. package/backend/http/ssh-sftp.ts +133 -0
  34. package/backend/index.ts +25 -2
  35. package/backend/mcp/README.md +34 -6
  36. package/backend/mcp/index.ts +8 -8
  37. package/backend/mcp/internal/config.ts +69 -19
  38. package/backend/mcp/internal/project-context.test.ts +40 -0
  39. package/backend/mcp/internal/project-context.ts +80 -7
  40. package/backend/mcp/internal/remote-server.test.ts +17 -2
  41. package/backend/mcp/internal/remote-server.ts +36 -3
  42. package/backend/mcp/internal/servers/helper.ts +48 -18
  43. package/backend/middleware/security.test.ts +95 -0
  44. package/backend/middleware/security.ts +114 -0
  45. package/backend/ports/attribute.test.ts +231 -0
  46. package/backend/ports/attribute.ts +444 -0
  47. package/backend/ports/kill.ts +203 -0
  48. package/backend/ports/monitor.ts +365 -0
  49. package/backend/ports/processes.test.ts +98 -0
  50. package/backend/ports/processes.ts +374 -0
  51. package/backend/ports/registry.ts +165 -0
  52. package/backend/ports/runner.ts +195 -0
  53. package/backend/ports/scan-host.ts +260 -0
  54. package/backend/ports/scan.test.ts +341 -0
  55. package/backend/ports/scan.ts +687 -0
  56. package/backend/ports/ssh-lineage.ts +318 -0
  57. package/backend/preview/browser/browser-video-capture.ts +51 -4
  58. package/backend/ssh/client-pool.ts +196 -0
  59. package/backend/ssh/connect.ts +375 -0
  60. package/backend/ssh/disk-usage.test.ts +134 -0
  61. package/backend/ssh/disk-usage.ts +214 -0
  62. package/backend/ssh/forwards.ts +340 -0
  63. package/backend/ssh/health.ts +141 -0
  64. package/backend/ssh/known-hosts.ts +96 -0
  65. package/backend/ssh/pty-backend.ts +215 -0
  66. package/backend/ssh/ptykit.ts +66 -0
  67. package/backend/ssh/sftp.test.ts +242 -0
  68. package/backend/ssh/sftp.ts +967 -0
  69. package/backend/ssh/socks5.test.ts +167 -0
  70. package/backend/ssh/socks5.ts +164 -0
  71. package/backend/ssh/tunnel.ts +87 -0
  72. package/backend/ws/auth/device.ts +1 -1
  73. package/backend/ws/auth/login.ts +8 -4
  74. package/backend/ws/db-client/connections.ts +1 -0
  75. package/backend/ws/files/watch.ts +5 -1
  76. package/backend/ws/index.ts +6 -0
  77. package/backend/ws/ports/index.ts +19 -0
  78. package/backend/ws/ports/kill.ts +80 -0
  79. package/backend/ws/ports/list.ts +60 -0
  80. package/backend/ws/ssh/access.ts +31 -0
  81. package/backend/ws/ssh/connections.ts +224 -0
  82. package/backend/ws/ssh/forwards.ts +109 -0
  83. package/backend/ws/ssh/index.ts +18 -0
  84. package/backend/ws/ssh/sftp.ts +259 -0
  85. package/backend/ws/ssh/tunnel.ts +93 -0
  86. package/dist/assets/{index-hu17G6tX.js → index-gGTMFUa8.js} +1 -1
  87. package/dist/assets/{index-DSvGoxp2.js → index-vW2RpdHu.js} +1 -1
  88. package/dist/assets/main-CYCMEbXB.css +1 -0
  89. package/dist/assets/{main-BccclZsC.js → main-ZCojSzvW.js} +506 -477
  90. package/dist/index.html +2 -2
  91. package/package.json +1 -1
  92. package/shared/types/database/schema.ts +49 -0
  93. package/shared/types/db-client/connection.ts +6 -0
  94. package/shared/types/ports/index.ts +5 -0
  95. package/shared/types/ports/port.ts +192 -0
  96. package/shared/types/ssh/connection.ts +80 -0
  97. package/shared/types/ssh/forward.ts +46 -0
  98. package/shared/types/ssh/index.ts +8 -0
  99. package/shared/types/ssh/known-host.ts +19 -0
  100. package/shared/types/ssh/sftp.ts +141 -0
  101. package/shared/utils/logger.ts +2 -0
  102. package/dist/assets/main-Ciuw0wF0.css +0 -1
@@ -0,0 +1,109 @@
1
+ /**
2
+ * HTTP download route for files.
3
+ *
4
+ * The counterpart to `/api/files/upload`, and it exists for the same reason
5
+ * plus one more. Reading a file over the WebSocket (`files:read-content`)
6
+ * base64-encodes the whole thing into a single message: the transfer is
7
+ * invisible until it lands, it costs a third more bytes on the wire, and both
8
+ * ends hold the entire file in memory. Streaming over HTTP with a known
9
+ * `Content-Length` lets the browser report progress while the bytes arrive.
10
+ *
11
+ * Auth: `Authorization: Bearer <session-token>` (same token as the upload
12
+ * route), followed by the same project-scoped path check the WS handlers use.
13
+ *
14
+ * Query: `path` (absolute path of the file to download).
15
+ */
16
+
17
+ import { Elysia } from 'elysia';
18
+ import { stat } from 'node:fs/promises';
19
+ import { basename } from 'node:path';
20
+
21
+ import { debug } from '$shared/utils/logger';
22
+ import { fileAuditLogQueries } from '../database/queries';
23
+ import { findContainingProjectId, requireFilePathAccessFor } from '../ws/files/path-access';
24
+ import { clientIpFromRequest } from '../utils/client-ip';
25
+ import { authenticateRequest, type AuthIdentity } from './bearer-auth';
26
+
27
+ export const filesDownloadRoute = new Elysia().get('/api/files/download', async ({ request, query, server }) => {
28
+ let identity: AuthIdentity;
29
+ try {
30
+ identity = authenticateRequest(request);
31
+ } catch (error) {
32
+ const status = (error as { status?: number }).status ?? 401;
33
+ const message = error instanceof Error ? error.message : 'Unauthorized';
34
+ return new Response(message, { status });
35
+ }
36
+
37
+ const pathParam = typeof query.path === 'string' ? query.path : '';
38
+ if (!pathParam) {
39
+ return new Response('Missing required query parameter: path', { status: 400 });
40
+ }
41
+
42
+ const ipAddress = clientIpFromRequest(request, server);
43
+ const userAgent = request.headers.get('user-agent') ?? undefined;
44
+ const projectId = await findContainingProjectId(pathParam);
45
+
46
+ const logFailure = (message: string, size: number | null = null) => {
47
+ fileAuditLogQueries.logOperation({
48
+ userId: identity.userId,
49
+ projectId,
50
+ action: 'download',
51
+ filePath: pathParam,
52
+ fileSize: size,
53
+ ipAddress,
54
+ userAgent,
55
+ success: false,
56
+ errorMessage: message
57
+ });
58
+ };
59
+
60
+ let resolvedPath: string;
61
+ try {
62
+ resolvedPath = await requireFilePathAccessFor(pathParam, identity.role, identity.userId);
63
+ } catch (error) {
64
+ logFailure('Path access denied');
65
+ return new Response(error instanceof Error ? error.message : 'Access denied', { status: 403 });
66
+ }
67
+
68
+ try {
69
+ const stats = await stat(resolvedPath).catch(() => null);
70
+ if (!stats) {
71
+ logFailure('File not found');
72
+ return new Response('File not found', { status: 404 });
73
+ }
74
+ if (stats.isDirectory()) {
75
+ logFailure('Not a file');
76
+ return new Response('Cannot download a directory — compress it first', { status: 400 });
77
+ }
78
+
79
+ const file = Bun.file(resolvedPath);
80
+
81
+ const name = basename(resolvedPath);
82
+
83
+ fileAuditLogQueries.logOperation({
84
+ userId: identity.userId,
85
+ projectId,
86
+ action: 'download',
87
+ filePath: resolvedPath,
88
+ fileSize: stats.size,
89
+ ipAddress,
90
+ userAgent
91
+ });
92
+
93
+ // Streamed straight from disk — a large file must never be buffered in
94
+ // this process just to be handed to the browser. `Content-Length` is what
95
+ // makes the client's progress event computable, so it is always set.
96
+ return new Response(file.stream(), {
97
+ headers: {
98
+ 'Content-Type': file.type || 'application/octet-stream',
99
+ 'Content-Length': String(stats.size),
100
+ 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}`
101
+ }
102
+ });
103
+ } catch (error) {
104
+ debug.error('file', 'HTTP download error:', error);
105
+ const message = error instanceof Error ? error.message : 'Download failed';
106
+ logFailure(message);
107
+ return new Response(message, { status: 500 });
108
+ }
109
+ });
@@ -19,43 +19,17 @@ import { join } from 'node:path';
19
19
  import { link, mkdir, stat, unlink } from 'node:fs/promises';
20
20
 
21
21
  import { debug } from '$shared/utils/logger';
22
- import { hashToken } from '../auth/tokens';
23
- import { authQueries, fileAuditLogQueries } from '../database/queries';
22
+ import { fileAuditLogQueries } from '../database/queries';
24
23
  import { findContainingProjectId, requireFilePathAccessFor } from '../ws/files/path-access';
25
24
  import { clientIpFromRequest } from '../utils/client-ip';
26
25
  import { validateFileSize } from '../files/file-size-limit';
27
26
  import { uploadTempCleanup } from './upload-temp-cleanup';
28
-
29
- type AuthIdentity = { userId: string; role: string };
30
-
31
- function authenticate(request: Request): AuthIdentity {
32
- const header = request.headers.get('authorization') || request.headers.get('Authorization');
33
- if (!header || !header.toLowerCase().startsWith('bearer ')) {
34
- throw Object.assign(new Error('Authorization required'), { status: 401 });
35
- }
36
- const token = header.slice(7).trim();
37
- if (!token) {
38
- throw Object.assign(new Error('Authorization required'), { status: 401 });
39
- }
40
- const session = authQueries.getSessionByTokenHash(hashToken(token));
41
- if (!session) {
42
- throw Object.assign(new Error('Invalid session token'), { status: 401 });
43
- }
44
- if (new Date(session.expires_at) < new Date()) {
45
- throw Object.assign(new Error('Session expired'), { status: 401 });
46
- }
47
- const user = authQueries.getUserById(session.user_id);
48
- if (!user) {
49
- throw Object.assign(new Error('User not found'), { status: 401 });
50
- }
51
- authQueries.updateLastActive(session.id);
52
- return { userId: user.id, role: user.role };
53
- }
27
+ import { authenticateRequest, type AuthIdentity } from './bearer-auth';
54
28
 
55
29
  export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({ request, query, server }) => {
56
30
  let identity: AuthIdentity;
57
31
  try {
58
- identity = authenticate(request);
32
+ identity = authenticateRequest(request);
59
33
  } catch (error) {
60
34
  const status = (error as { status?: number }).status ?? 401;
61
35
  const message = error instanceof Error ? error.message : 'Unauthorized';
@@ -0,0 +1,133 @@
1
+ /**
2
+ * HTTP routes for SFTP file transfer.
3
+ *
4
+ * Same reasoning as `/api/files/upload`: the WebSocket wedges on sustained
5
+ * binary transfer behind the Vite dev proxy, while HTTP streams cleanly through
6
+ * it. Download is here too, so the browser can save a remote file straight to
7
+ * disk without buffering it in JavaScript first.
8
+ *
9
+ * Auth: `Authorization: Bearer <session-token>`, then the same ownership check
10
+ * the WS handlers use — a token is not enough, the caller must own the host.
11
+ */
12
+
13
+ import { Elysia } from 'elysia';
14
+ import { Readable } from 'node:stream';
15
+
16
+ import { debug } from '$shared/utils/logger';
17
+ import { sshConnectionQueries } from '../database/queries';
18
+ import { joinRemote, sftpService } from '../ssh/sftp';
19
+ import { authenticateRequest } from './bearer-auth';
20
+
21
+ /** Resolve the caller and confirm they own the SSH connection they named. */
22
+ function authorizeConnection(request: Request, connectionId: string): void {
23
+ const identity = authenticateRequest(request);
24
+ const connection = sshConnectionQueries.getForUser(
25
+ connectionId,
26
+ identity.userId,
27
+ identity.role === 'admin'
28
+ );
29
+ if (!connection) {
30
+ throw Object.assign(new Error('ssh connection not found'), { status: 404 });
31
+ }
32
+ }
33
+
34
+ function errorResponse(error: unknown, fallbackStatus: number): Response {
35
+ const status = (error as { status?: number }).status ?? fallbackStatus;
36
+ const message = error instanceof Error ? error.message : 'Request failed';
37
+ return new Response(message, { status });
38
+ }
39
+
40
+ export const sshSftpRoute = new Elysia()
41
+ .get('/api/ssh/sftp/download', async ({ request, query }) => {
42
+ const connectionId = typeof query.connectionId === 'string' ? query.connectionId : '';
43
+ const path = typeof query.path === 'string' ? query.path : '';
44
+ if (!connectionId || !path) {
45
+ return new Response('Missing required query parameters: connectionId, path', { status: 400 });
46
+ }
47
+
48
+ try {
49
+ authorizeConnection(request, connectionId);
50
+ } catch (error) {
51
+ return errorResponse(error, 401);
52
+ }
53
+
54
+ try {
55
+ const { stream, size, name } = await sftpService.openDownload(connectionId, path);
56
+ // Stream straight through: a large remote file must never be buffered
57
+ // in this process just to be handed to the browser.
58
+ const body = Readable.toWeb(stream) as unknown as ReadableStream;
59
+ // Typed by name, the way Bun types a local file — a blob built from
60
+ // this response only plays in <video> or renders in a PDF frame if the
61
+ // type came across with it. Nothing is read from disk here; Bun.file
62
+ // infers the type from the extension alone.
63
+ const contentType = Bun.file(name).type || 'application/octet-stream';
64
+ return new Response(body, {
65
+ headers: {
66
+ 'Content-Type': contentType,
67
+ 'Content-Length': String(size),
68
+ 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}`
69
+ }
70
+ });
71
+ } catch (error) {
72
+ debug.error('ssh', 'SFTP download failed:', error);
73
+ return errorResponse(error, 500);
74
+ }
75
+ })
76
+
77
+ .post('/api/ssh/sftp/upload', async ({ request, query }) => {
78
+ const connectionId = typeof query.connectionId === 'string' ? query.connectionId : '';
79
+ const targetPath = typeof query.targetPath === 'string' ? query.targetPath : '';
80
+ const fileName = typeof query.fileName === 'string' ? query.fileName : '';
81
+ if (!connectionId || !targetPath || !fileName) {
82
+ return new Response('Missing required query parameters: connectionId, targetPath, fileName', {
83
+ status: 400
84
+ });
85
+ }
86
+ if (fileName.includes('/')) {
87
+ return new Response('fileName must not contain a path separator', { status: 400 });
88
+ }
89
+
90
+ try {
91
+ authorizeConnection(request, connectionId);
92
+ } catch (error) {
93
+ return errorResponse(error, 401);
94
+ }
95
+
96
+ if (!request.body) {
97
+ return new Response('Request body is empty', { status: 400 });
98
+ }
99
+
100
+ const remotePath = joinRemote(targetPath, fileName);
101
+
102
+ try {
103
+ const { stream, done } = await sftpService.openUpload(connectionId, remotePath);
104
+
105
+ const reader = request.body.getReader();
106
+ let written = 0;
107
+ try {
108
+ while (true) {
109
+ const { done: finished, value } = await reader.read();
110
+ if (finished) break;
111
+ if (!value) continue;
112
+ // Respect backpressure: an SFTP channel is far slower than the
113
+ // browser's upload, and ignoring `write`'s return value would
114
+ // queue the whole file in memory.
115
+ if (!stream.write(value)) {
116
+ await new Promise<void>((resolvePromise) => stream.once('drain', resolvePromise));
117
+ }
118
+ written += value.byteLength;
119
+ }
120
+ } catch (error) {
121
+ stream.destroy();
122
+ throw error;
123
+ }
124
+
125
+ stream.end();
126
+ await done;
127
+
128
+ return Response.json({ path: remotePath, size: written });
129
+ } catch (error) {
130
+ debug.error('ssh', 'SFTP upload failed:', error);
131
+ return errorResponse(error, 500);
132
+ }
133
+ });
package/backend/index.ts CHANGED
@@ -20,6 +20,7 @@ import { Elysia } from 'elysia';
20
20
  import { corsMiddleware } from './middleware/cors';
21
21
  import { errorHandlerMiddleware } from './middleware/error-handler';
22
22
  import { loggerMiddleware } from './middleware/logger';
23
+ import { securityMiddleware } from './middleware/security';
23
24
 
24
25
  // Database initialization
25
26
  import { initializeDatabase, closeDatabase } from './database';
@@ -28,6 +29,8 @@ import { startEngineConfigWatcher } from './engine/config-revision';
28
29
  import { startEngineHotReload } from './engine/hot-reload';
29
30
  import { disposeAllEngines } from './engine';
30
31
  import { connectionManager } from './db-client/connection-manager';
32
+ import { sshClientPool } from './ssh/client-pool';
33
+ import { sshForwardManager } from './ssh/forwards';
31
34
  import { refreshProcessPath } from './utils/path-enrich';
32
35
  import { installProcessWarningFilter } from './utils/process-warnings';
33
36
  import { debug } from '$shared/utils/logger';
@@ -41,10 +44,14 @@ import { wsRouter } from './ws';
41
44
  // HTTP upload route — bypasses the Vite WS proxy, which corrupts sustained
42
45
  // binary transfers with `write EPIPE`. See backend/http/files-upload.ts.
43
46
  import { filesUploadRoute } from './http/files-upload';
47
+ import { filesDownloadRoute } from './http/files-download';
44
48
 
45
49
  // HTTP routes for per-user notification sounds (upload / serve / delete).
46
50
  import { audioRoute } from './http/audio';
47
51
 
52
+ // HTTP routes for SFTP transfer — same reason as the file upload route above.
53
+ import { sshSftpRoute } from './http/ssh-sftp';
54
+
48
55
  // Import browser preview manager for graceful shutdown
49
56
  import { browserPreviewServiceManager } from './preview';
50
57
 
@@ -57,6 +64,7 @@ import { getAuthMode } from './settings/system-settings';
57
64
  import { authQueries } from './database/queries';
58
65
  import { authRateLimiter } from './auth';
59
66
  import { sessionCleanupScheduler } from './auth/session-cleanup';
67
+ import { portMonitor } from './ports/monitor';
60
68
  import { uploadTempCleanup } from './http/upload-temp-cleanup';
61
69
  import { ws as wsServer } from './utils/ws';
62
70
  import { messageRateLimiter } from './ws/message-rate-limiter';
@@ -123,6 +131,7 @@ const HOST = SERVER_ENV.HOST;
123
131
  const app = new Elysia()
124
132
  // Apply middleware
125
133
  .use(corsMiddleware)
134
+ .use(securityMiddleware)
126
135
  .use(errorHandlerMiddleware)
127
136
  .use(loggerMiddleware)
128
137
 
@@ -176,13 +185,17 @@ const app = new Elysia()
176
185
  }
177
186
  })
178
187
 
179
- // HTTP file upload — mounted before the WS plugin so /api/files/upload
180
- // stays on the HTTP path through the Vite dev proxy.
188
+ // HTTP file transfer — mounted before the WS plugin so /api/files/* stays
189
+ // on the HTTP path through the Vite dev proxy.
181
190
  .use(filesUploadRoute)
191
+ .use(filesDownloadRoute)
182
192
 
183
193
  // Per-user notification sound upload/serve/delete.
184
194
  .use(audioRoute)
185
195
 
196
+ // SSH file transfer (SFTP download/upload).
197
+ .use(sshSftpRoute)
198
+
186
199
  // Mount WebSocket router (all functionality now via WebSocket)
187
200
  .use(wsRouter.asPlugin('/ws'));
188
201
 
@@ -257,6 +270,10 @@ async function startServer() {
257
270
  // which also runs on the live process during "Clear All Data".
258
271
  startEngineHotReload();
259
272
  startEngineConfigWatcher();
273
+ // Sidebar count for the port manager. Idle-cheap by construction: with no
274
+ // terminal sessions running there are no session-born ports to count, so
275
+ // the tick skips the scan entirely.
276
+ portMonitor.start();
260
277
  } catch (error) {
261
278
  console.error('❌ Database initialization failed — refusing to start:', error);
262
279
  console.error(` Data directory: ${SERVER_ENV.DATA_DIR}`);
@@ -310,12 +327,18 @@ async function gracefulShutdown() {
310
327
  // and browser teardown below — otherwise the old process keeps those
311
328
  // sockets open long enough to overlap the new process ("too many clients").
312
329
  await connectionManager.closeAll();
330
+ // Same reasoning for SSH: stop the forwards' listeners and close every
331
+ // transport so their remote sessions and bound ports are released now.
332
+ await sshForwardManager.stopAll();
333
+ sshClientPool.closeAll();
313
334
  // Dispose rate limiter timer
314
335
  authRateLimiter.dispose();
315
336
  // Dispose expired session cleanup timer
316
337
  sessionCleanupScheduler.dispose();
317
338
  // Dispose upload temp cleanup timer
318
339
  uploadTempCleanup.dispose();
340
+ // Stop port polling and release any SSH leases it holds
341
+ portMonitor.stop();
319
342
  // Close MCP remote server (before engines, as they may still reference it)
320
343
  await closeMcpServer();
321
344
  // Cleanup browser preview sessions
@@ -284,7 +284,7 @@ servers/browser-automation/
284
284
  └─> Mounted at /mcp on the main Elysia server
285
285
  ↓
286
286
  3. Open Code engine (opencode/stream.ts)
287
- └─> Uses getOpenCodeMcpConfig() → { type: 'remote', url: '/mcp' }
287
+ └─> Uses getOpenCodeMcpConfig() → { type: 'remote', url: '/mcp?engine=opencode' }
288
288
  ↓
289
289
  4. Open Code connects via Streamable HTTP transport
290
290
  └─> Sends JSON-RPC tool calls to /mcp endpoint
@@ -612,9 +612,34 @@ Returns MCP configuration for Open Code engine (remote HTTP MCP server).
612
612
  import { getOpenCodeMcpConfig } from '$backend/mcp';
613
613
 
614
614
  const mcpConfig = getOpenCodeMcpConfig();
615
- // Returns: { 'clopen-mcp': { type: 'remote', url: 'http://localhost:9151/mcp', ... } }
615
+ // Returns: { 'clopen-mcp': { type: 'remote', url: 'http://localhost:9151/mcp?engine=opencode', ... } }
616
616
  ```
617
617
 
618
+ ##### Who is calling: the bridge URL carries the caller
619
+
620
+ The in-process engines (Claude, Pi, Cline) wrap every tool handler in the
621
+ stream's `McpExecutionContext`, so a handler that asks "which project is this?"
622
+ always gets the right answer. An HTTP request carries no such context, and the
623
+ fallback — the most recently *started* stream anywhere in the app — is the
624
+ project the **user** last prompted in, not the one the agent is working in. An
625
+ agent driving the Preview Browser in project A opened its tabs in project B the
626
+ moment the user switched over there.
627
+
628
+ So each config builder addresses the bridge with as much identity as its own
629
+ lifetime allows, and `handleMcpRequest` binds that for the MCP session:
630
+
631
+ | Engine | Query string | Why not more |
632
+ | ------------- | --------------------------------------- | ------------ |
633
+ | Copilot, Cursor, Qwen | `engine`, `project`, `session` | — built per stream |
634
+ | Codex | `engine`, `project` | one client per project, shared by its chat sessions |
635
+ | Open Code | `engine` | one pooled server per Profile, shared across projects |
636
+
637
+ A caller that names only its project resolves the chat session to the most
638
+ recent stream *in that project*; a caller that names only its engine resolves to
639
+ the most recent stream *on that engine*. Both are guesses, but confined ones —
640
+ and when a config gains a narrower lifetime, pass the richer context and the
641
+ guess disappears.
642
+
618
643
  #### `resolveOpenCodeToolName(toolName)`
619
644
  Resolve a remote-MCP tool name to `mcp__server__tool` format (single source
620
645
  of truth — used by every non-Claude engine adapter).
@@ -660,14 +685,17 @@ engines. Each returns the **same** `/mcp` URL in the SDK-specific shape:
660
685
 
661
686
  ```typescript
662
687
  // Codex (config object flattened to --config flags)
663
- getCodexMcpConfig();
664
- // { 'clopen-mcp': { url: 'http://localhost:9151/mcp', tools: { ... } } }
688
+ getCodexMcpConfig(profileFilter, mcpContext);
689
+ // { 'clopen-mcp': { url: 'http://localhost:9151/mcp?engine=codex&project=…', tools: { ... } } }
665
690
 
666
691
  // Copilot (MCPHTTPServerConfig from @github/copilot-sdk)
667
- getCopilotMcpConfig();
668
- // { 'clopen-mcp': { type: 'http', url: 'http://localhost:9151/mcp', tools: [...] } }
692
+ getCopilotMcpConfig(profileFilter, mcpContext);
693
+ // { 'clopen-mcp': { type: 'http', url: 'http://localhost:9151/mcp?engine=copilot&project=…&session=…', tools: [...] } }
669
694
  ```
670
695
 
696
+ Pass the stream's `mcpContext` — without it the bridge cannot tell whose tool
697
+ call it is holding (see "Who is calling" above).
698
+
671
699
  When adding a new engine that consumes streamable-HTTP MCP, add a sibling
672
700
  `getXxxMcpConfig()` here — do **not** introduce a new HTTP listener or a
673
701
  new namespace key. See `backend/engine/README.md` §10.12 for the full
@@ -121,33 +121,33 @@ export function getOpenCodeMcpConfig(profileFilter?: Set<string>) {
121
121
  }
122
122
 
123
123
  /** Codex MCP config. */
124
- export function getCodexMcpConfig(profileFilter?: Set<string>) {
124
+ export function getCodexMcpConfig(profileFilter?: Set<string>, context?: McpExecutionContext) {
125
125
  return {
126
- ...internal.getCodexMcpConfig(profileFilter),
126
+ ...internal.getCodexMcpConfig(profileFilter, context),
127
127
  ...external.getCodexExternalMcpConfig(profileFilter)
128
128
  };
129
129
  }
130
130
 
131
131
  /** Copilot MCP config. */
132
- export function getCopilotMcpConfig(profileFilter?: Set<string>) {
132
+ export function getCopilotMcpConfig(profileFilter?: Set<string>, context?: McpExecutionContext) {
133
133
  return {
134
- ...internal.getCopilotMcpConfig(profileFilter),
134
+ ...internal.getCopilotMcpConfig(profileFilter, context),
135
135
  ...external.getCopilotExternalMcpConfig(profileFilter)
136
136
  };
137
137
  }
138
138
 
139
139
  /** Cursor MCP config: internal `clopen-mcp` remote bridge + external servers. */
140
- export function getCursorMcpConfig(profileFilter?: Set<string>) {
140
+ export function getCursorMcpConfig(profileFilter?: Set<string>, context?: McpExecutionContext) {
141
141
  return {
142
- ...internal.getCursorMcpConfig(profileFilter),
142
+ ...internal.getCursorMcpConfig(profileFilter, context),
143
143
  ...external.getCursorExternalMcpConfig(profileFilter)
144
144
  };
145
145
  }
146
146
 
147
147
  /** Qwen Code MCP config. */
148
- export function getQwenMcpConfig(profileFilter?: Set<string>) {
148
+ export function getQwenMcpConfig(profileFilter?: Set<string>, context?: McpExecutionContext) {
149
149
  return {
150
- ...internal.getQwenMcpConfig(profileFilter),
150
+ ...internal.getQwenMcpConfig(profileFilter, context),
151
151
  ...external.getQwenExternalMcpConfig(profileFilter)
152
152
  };
153
153
  }