@myrialabs/clopen 0.4.32 → 0.4.33

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/chat/stream-manager.ts +4 -1
  2. package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
  3. package/backend/database/migrations/index.ts +7 -0
  4. package/backend/database/queries/db-client-connection-queries.ts +7 -2
  5. package/backend/database/queries/file-audit-log-queries.ts +1 -0
  6. package/backend/database/queries/index.ts +3 -0
  7. package/backend/database/queries/ssh-connection-queries.ts +244 -0
  8. package/backend/database/queries/ssh-known-host-queries.ts +67 -0
  9. package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
  10. package/backend/db-client/connection-manager.ts +8 -1
  11. package/backend/engine/adapters/codex/message-converter.ts +18 -12
  12. package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
  13. package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
  14. package/backend/engine/adapters/codex/stream.ts +33 -4
  15. package/backend/engine/adapters/copilot/stream.ts +1 -1
  16. package/backend/engine/adapters/cursor/stream.ts +1 -1
  17. package/backend/engine/adapters/qwen/stream.ts +1 -1
  18. package/backend/engine/docs/adapter-contract.md +7 -0
  19. package/backend/files/file-watcher.ts +283 -51
  20. package/backend/files/git-events.test.ts +110 -0
  21. package/backend/git/git-dirs.test.ts +132 -0
  22. package/backend/git/git-dirs.ts +0 -0
  23. package/backend/git/nested-repos.test.ts +108 -5
  24. package/backend/git/nested-repos.ts +103 -18
  25. package/backend/http/audio.ts +5 -32
  26. package/backend/http/bearer-auth.ts +47 -0
  27. package/backend/http/files-download.test.ts +146 -0
  28. package/backend/http/files-download.ts +109 -0
  29. package/backend/http/files-upload.ts +3 -29
  30. package/backend/http/ssh-sftp.ts +133 -0
  31. package/backend/index.ts +16 -2
  32. package/backend/mcp/README.md +34 -6
  33. package/backend/mcp/index.ts +8 -8
  34. package/backend/mcp/internal/config.ts +69 -19
  35. package/backend/mcp/internal/project-context.test.ts +40 -0
  36. package/backend/mcp/internal/project-context.ts +80 -7
  37. package/backend/mcp/internal/remote-server.test.ts +17 -2
  38. package/backend/mcp/internal/remote-server.ts +36 -3
  39. package/backend/mcp/internal/servers/helper.ts +48 -18
  40. package/backend/preview/browser/browser-video-capture.ts +51 -4
  41. package/backend/ssh/client-pool.ts +196 -0
  42. package/backend/ssh/connect.ts +375 -0
  43. package/backend/ssh/disk-usage.test.ts +134 -0
  44. package/backend/ssh/disk-usage.ts +214 -0
  45. package/backend/ssh/forwards.ts +309 -0
  46. package/backend/ssh/health.ts +141 -0
  47. package/backend/ssh/known-hosts.ts +96 -0
  48. package/backend/ssh/pty-backend.ts +215 -0
  49. package/backend/ssh/ptykit.ts +66 -0
  50. package/backend/ssh/sftp.test.ts +242 -0
  51. package/backend/ssh/sftp.ts +967 -0
  52. package/backend/ssh/socks5.test.ts +167 -0
  53. package/backend/ssh/socks5.ts +164 -0
  54. package/backend/ssh/tunnel.ts +87 -0
  55. package/backend/ws/db-client/connections.ts +1 -0
  56. package/backend/ws/files/watch.ts +5 -1
  57. package/backend/ws/index.ts +4 -0
  58. package/backend/ws/ssh/access.ts +31 -0
  59. package/backend/ws/ssh/connections.ts +224 -0
  60. package/backend/ws/ssh/forwards.ts +109 -0
  61. package/backend/ws/ssh/index.ts +18 -0
  62. package/backend/ws/ssh/sftp.ts +259 -0
  63. package/backend/ws/ssh/tunnel.ts +93 -0
  64. package/dist/assets/{index-DSvGoxp2.js → index-BF4buYmI.js} +1 -1
  65. package/dist/assets/{index-hu17G6tX.js → index-BW0DA8NV.js} +1 -1
  66. package/dist/assets/{main-BccclZsC.js → main-BbwWLJRN.js} +499 -473
  67. package/dist/assets/main-CCvRMXlP.css +1 -0
  68. package/dist/index.html +2 -2
  69. package/package.json +1 -1
  70. package/shared/types/database/schema.ts +49 -0
  71. package/shared/types/db-client/connection.ts +6 -0
  72. package/shared/types/ssh/connection.ts +80 -0
  73. package/shared/types/ssh/forward.ts +46 -0
  74. package/shared/types/ssh/index.ts +8 -0
  75. package/shared/types/ssh/known-host.ts +19 -0
  76. package/shared/types/ssh/sftp.ts +141 -0
  77. package/shared/utils/logger.ts +1 -0
  78. 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
@@ -28,6 +28,8 @@ import { startEngineConfigWatcher } from './engine/config-revision';
28
28
  import { startEngineHotReload } from './engine/hot-reload';
29
29
  import { disposeAllEngines } from './engine';
30
30
  import { connectionManager } from './db-client/connection-manager';
31
+ import { sshClientPool } from './ssh/client-pool';
32
+ import { sshForwardManager } from './ssh/forwards';
31
33
  import { refreshProcessPath } from './utils/path-enrich';
32
34
  import { installProcessWarningFilter } from './utils/process-warnings';
33
35
  import { debug } from '$shared/utils/logger';
@@ -41,10 +43,14 @@ import { wsRouter } from './ws';
41
43
  // HTTP upload route — bypasses the Vite WS proxy, which corrupts sustained
42
44
  // binary transfers with `write EPIPE`. See backend/http/files-upload.ts.
43
45
  import { filesUploadRoute } from './http/files-upload';
46
+ import { filesDownloadRoute } from './http/files-download';
44
47
 
45
48
  // HTTP routes for per-user notification sounds (upload / serve / delete).
46
49
  import { audioRoute } from './http/audio';
47
50
 
51
+ // HTTP routes for SFTP transfer — same reason as the file upload route above.
52
+ import { sshSftpRoute } from './http/ssh-sftp';
53
+
48
54
  // Import browser preview manager for graceful shutdown
49
55
  import { browserPreviewServiceManager } from './preview';
50
56
 
@@ -176,13 +182,17 @@ const app = new Elysia()
176
182
  }
177
183
  })
178
184
 
179
- // HTTP file upload — mounted before the WS plugin so /api/files/upload
180
- // stays on the HTTP path through the Vite dev proxy.
185
+ // HTTP file transfer — mounted before the WS plugin so /api/files/* stays
186
+ // on the HTTP path through the Vite dev proxy.
181
187
  .use(filesUploadRoute)
188
+ .use(filesDownloadRoute)
182
189
 
183
190
  // Per-user notification sound upload/serve/delete.
184
191
  .use(audioRoute)
185
192
 
193
+ // SSH file transfer (SFTP download/upload).
194
+ .use(sshSftpRoute)
195
+
186
196
  // Mount WebSocket router (all functionality now via WebSocket)
187
197
  .use(wsRouter.asPlugin('/ws'));
188
198
 
@@ -310,6 +320,10 @@ async function gracefulShutdown() {
310
320
  // and browser teardown below — otherwise the old process keeps those
311
321
  // sockets open long enough to overlap the new process ("too many clients").
312
322
  await connectionManager.closeAll();
323
+ // Same reasoning for SSH: stop the forwards' listeners and close every
324
+ // transport so their remote sessions and bound ports are released now.
325
+ await sshForwardManager.stopAll();
326
+ sshClientPool.closeAll();
313
327
  // Dispose rate limiter timer
314
328
  authRateLimiter.dispose();
315
329
  // Dispose expired session cleanup timer
@@ -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
  }
@@ -12,6 +12,7 @@ import type { CLIMcpServerConfig as QwenMcpServerConfig } from '@qwen-code/sdk';
12
12
  import type { McpServerConfig as CursorMcpServerConfig } from '@cursor/sdk';
13
13
  import type { ServerConfig, ParsedMcpToolName, ServerName } from './types';
14
14
  import type { McpExecutionContext } from '../../engine/types';
15
+ import type { EngineType } from '$shared/types/unified';
15
16
  import { serverMetadata } from './servers';
16
17
  import { loadEngineSdk } from '$backend/engine/sdk-loader';
17
18
  import { projectContextService } from './project-context';
@@ -434,6 +435,40 @@ export function resolveOpenCodeToolName(toolName: string): string | null {
434
435
  return null;
435
436
  }
436
437
 
438
+ // ============================================================================
439
+ // Internal bridge URL
440
+ // ============================================================================
441
+
442
+ /**
443
+ * Loopback URL of the internal `clopen-mcp` bridge, addressed to the caller.
444
+ *
445
+ * The in-process engines (Claude, Pi, Cline) bind `McpExecutionContext` around
446
+ * every tool handler, so a tool call always knows which project asked. The
447
+ * engines that reach the bridge over HTTP had no such thing: the request
448
+ * carries no identity, so the handler fell back to "the most recently started
449
+ * stream" — which is the project the *user* last prompted in, not the one the
450
+ * agent is working in. An agent running in project A opened its tabs in project
451
+ * B the moment the user moved over there.
452
+ *
453
+ * The query string closes that. Each config says as much as its own lifetime
454
+ * allows, and the bridge binds whatever it is told:
455
+ *
456
+ * - `project` + `session` — the caller named outright. Copilot, Cursor and Qwen
457
+ * build their config per stream, so both are true for the whole MCP session.
458
+ * - `project` alone — Codex, whose client (and therefore this URL) is built
459
+ * once per project and reused by every chat session in it.
460
+ * - `engine` alone — Open Code, whose URL is baked into a server the pool shares
461
+ * across projects. All it can honestly say is which engine is asking.
462
+ */
463
+ function internalBridgeUrl(engine: EngineType, context?: McpExecutionContext): string {
464
+ const params = new URLSearchParams({ engine });
465
+
466
+ if (context?.projectId) params.set('project', context.projectId);
467
+ if (context?.chatSessionId) params.set('session', context.chatSessionId);
468
+
469
+ return `http://localhost:${SERVER_ENV.PORT}/mcp?${params.toString()}`;
470
+ }
471
+
437
472
  // ============================================================================
438
473
  // Open Code MCP Configuration
439
474
  // ============================================================================
@@ -454,14 +489,17 @@ export function getOpenCodeMcpConfig(profileFilter?: Set<string>): Record<string
454
489
  return {};
455
490
  }
456
491
 
457
- const port = SERVER_ENV.PORT;
492
+ // No caller binding: this URL is baked into a server the pool shares across
493
+ // projects and chat sessions (see `scopeKeyFor` in the Open Code adapter),
494
+ // so the engine marker is all it can honestly carry.
495
+ const url = internalBridgeUrl('opencode');
458
496
 
459
- debug.log('mcp', `📦 Open Code MCP: remote server at http://localhost:${port}/mcp`);
497
+ debug.log('mcp', `📦 Open Code MCP: remote server at ${url}`);
460
498
 
461
499
  return {
462
500
  'clopen-mcp': {
463
501
  type: 'remote',
464
- url: `http://localhost:${port}/mcp`,
502
+ url,
465
503
  enabled: true,
466
504
  timeout: MCP_TOOL_CALL_TIMEOUT_MS,
467
505
  headers: { Authorization: `Bearer ${getMcpServiceToken()}` },
@@ -507,13 +545,16 @@ type CodexMcpServerConfig = {
507
545
  * `--config mcp_servers.clopen-mcp.<dotted-key>=<value>` flags when the SDK
508
546
  * invokes the CLI subprocess for each turn.
509
547
  */
510
- export function getCodexMcpConfig(profileFilter?: Set<string>): Record<string, CodexMcpServerConfig> {
548
+ export function getCodexMcpConfig(
549
+ profileFilter?: Set<string>,
550
+ context?: McpExecutionContext
551
+ ): Record<string, CodexMcpServerConfig> {
511
552
  const enabledServers = activeInternalServerNames(profileFilter);
512
553
  if (enabledServers.length === 0) {
513
554
  return {};
514
555
  }
515
556
 
516
- const port = SERVER_ENV.PORT;
557
+ const url = internalBridgeUrl('codex', context);
517
558
 
518
559
  const tools: Record<string, { approval_mode: 'approve' }> = {};
519
560
  for (const serverName of enabledServers) {
@@ -523,11 +564,11 @@ export function getCodexMcpConfig(profileFilter?: Set<string>): Record<string, C
523
564
  }
524
565
  }
525
566
 
526
- debug.log('mcp', `📦 Codex MCP: remote server at http://localhost:${port}/mcp (auto-approving ${Object.keys(tools).length} tools)`);
567
+ debug.log('mcp', `📦 Codex MCP: remote server at ${url} (auto-approving ${Object.keys(tools).length} tools)`);
527
568
 
528
569
  return {
529
570
  'clopen-mcp': {
530
- url: `http://localhost:${port}/mcp`,
571
+ url,
531
572
  http_headers: { Authorization: `Bearer ${getMcpServiceToken()}` },
532
573
  tools,
533
574
  },
@@ -557,13 +598,16 @@ export function getCodexMcpConfig(profileFilter?: Set<string>): Record<string, C
557
598
  * `resolveOpenCodeToolName()` to recover the canonical
558
599
  * `mcp__<server>__<tool>` form.
559
600
  */
560
- export function getCopilotMcpConfig(profileFilter?: Set<string>): Record<string, MCPHTTPServerConfig> {
601
+ export function getCopilotMcpConfig(
602
+ profileFilter?: Set<string>,
603
+ context?: McpExecutionContext
604
+ ): Record<string, MCPHTTPServerConfig> {
561
605
  const enabledServers = activeInternalServerNames(profileFilter);
562
606
  if (enabledServers.length === 0) {
563
607
  return {};
564
608
  }
565
609
 
566
- const port = SERVER_ENV.PORT;
610
+ const url = internalBridgeUrl('copilot', context);
567
611
 
568
612
  const tools: string[] = [];
569
613
  for (const serverName of enabledServers) {
@@ -573,12 +617,12 @@ export function getCopilotMcpConfig(profileFilter?: Set<string>): Record<string,
573
617
  }
574
618
  }
575
619
 
576
- debug.log('mcp', `📦 Copilot MCP: remote server at http://localhost:${port}/mcp (${tools.length} tools)`);
620
+ debug.log('mcp', `📦 Copilot MCP: remote server at ${url} (${tools.length} tools)`);
577
621
 
578
622
  return {
579
623
  'clopen-mcp': {
580
624
  type: 'http',
581
- url: `http://localhost:${port}/mcp`,
625
+ url,
582
626
  tools,
583
627
  timeout: MCP_TOOL_CALL_TIMEOUT_MS,
584
628
  headers: { Authorization: `Bearer ${getMcpServiceToken()}` },
@@ -598,20 +642,23 @@ export function getCopilotMcpConfig(profileFilter?: Set<string>): Record<string,
598
642
  * Open Code, Codex, Copilot and Qwen already consume — no new HTTP server, no
599
643
  * per-engine bridge (README §10.12). The service-token bearer authorises the hop.
600
644
  */
601
- export function getCursorMcpConfig(profileFilter?: Set<string>): Record<string, CursorMcpServerConfig> {
645
+ export function getCursorMcpConfig(
646
+ profileFilter?: Set<string>,
647
+ context?: McpExecutionContext
648
+ ): Record<string, CursorMcpServerConfig> {
602
649
  const enabledServers = activeInternalServerNames(profileFilter);
603
650
  if (enabledServers.length === 0) {
604
651
  return {};
605
652
  }
606
653
 
607
- const port = SERVER_ENV.PORT;
654
+ const url = internalBridgeUrl('cursor', context);
608
655
 
609
- debug.log('mcp', `📦 Cursor MCP: remote server at http://localhost:${port}/mcp`);
656
+ debug.log('mcp', `📦 Cursor MCP: remote server at ${url}`);
610
657
 
611
658
  return {
612
659
  'clopen-mcp': {
613
660
  type: 'http',
614
- url: `http://localhost:${port}/mcp`,
661
+ url,
615
662
  headers: { Authorization: `Bearer ${getMcpServiceToken()}` },
616
663
  },
617
664
  };
@@ -636,13 +683,16 @@ export function getCursorMcpConfig(profileFilter?: Set<string>): Record<string,
636
683
  * so the model never sees it. The callback covers MCP tool calls too — no
637
684
  * per-tool enumeration needed.
638
685
  */
639
- export function getQwenMcpConfig(profileFilter?: Set<string>): Record<string, QwenMcpServerConfig> {
686
+ export function getQwenMcpConfig(
687
+ profileFilter?: Set<string>,
688
+ context?: McpExecutionContext
689
+ ): Record<string, QwenMcpServerConfig> {
640
690
  const enabledServers = activeInternalServerNames(profileFilter);
641
691
  if (enabledServers.length === 0) {
642
692
  return {};
643
693
  }
644
694
 
645
- const port = SERVER_ENV.PORT;
695
+ const url = internalBridgeUrl('qwen', context);
646
696
 
647
697
  const includeTools: string[] = [];
648
698
  for (const serverName of enabledServers) {
@@ -652,11 +702,11 @@ export function getQwenMcpConfig(profileFilter?: Set<string>): Record<string, Qw
652
702
  }
653
703
  }
654
704
 
655
- debug.log('mcp', `📦 Qwen MCP: remote server at http://localhost:${port}/mcp (${includeTools.length} tools)`);
705
+ debug.log('mcp', `📦 Qwen MCP: remote server at ${url} (${includeTools.length} tools)`);
656
706
 
657
707
  return {
658
708
  'clopen-mcp': {
659
- httpUrl: `http://localhost:${port}/mcp`,
709
+ httpUrl: url,
660
710
  includeTools,
661
711
  timeout: MCP_TOOL_CALL_TIMEOUT_MS,
662
712
  trust: true,