@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
@@ -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,
@@ -20,3 +20,43 @@ describe('projectContextService.clearByProjectId', () => {
20
20
  expect(projectContextService.getLastUsedProjectId()).toBe('project-2');
21
21
  });
22
22
  });
23
+
24
+ describe('projectContextService bridge identity', () => {
25
+ beforeEach(() => {
26
+ projectContextService.clear();
27
+ });
28
+
29
+ test('a bound project wins over the most recently started stream', () => {
30
+ projectContextService.registerSession('session-a', 'project-a');
31
+ projectContextService.registerStream('stream-a', 'project-a', 'session-a', 'codex');
32
+ // The user moves to another project and prompts there — this is the stream
33
+ // the old ambient fallback would have attributed project-a's tool call to.
34
+ projectContextService.registerSession('session-b', 'project-b');
35
+ projectContextService.registerStream('stream-b', 'project-b', 'session-b', 'codex');
36
+
37
+ projectContextService.runWithContext({ projectId: 'project-a' }, () => {
38
+ expect(projectContextService.getCurrentProjectId()).toBe('project-a');
39
+ expect(projectContextService.getCurrentChatSessionId()).toBe('session-a');
40
+ });
41
+ });
42
+
43
+ test('engine scoping ignores streams belonging to another engine', () => {
44
+ projectContextService.registerSession('session-a', 'project-a');
45
+ projectContextService.registerStream('stream-a', 'project-a', 'session-a', 'opencode');
46
+ projectContextService.registerSession('session-b', 'project-b');
47
+ projectContextService.registerStream('stream-b', 'project-b', 'session-b', 'claude-code');
48
+
49
+ expect(projectContextService.getContextForEngine('opencode')).toMatchObject({
50
+ projectId: 'project-a',
51
+ chatSessionId: 'session-a'
52
+ });
53
+ expect(projectContextService.getContextForEngine('cursor')).toBeUndefined();
54
+ });
55
+
56
+ test('an unidentified caller still falls back to the most recent stream', () => {
57
+ projectContextService.registerSession('session-a', 'project-a');
58
+ projectContextService.registerStream('stream-a', 'project-a', 'session-a', 'codex');
59
+
60
+ expect(projectContextService.getCurrentProjectId()).toBe('project-a');
61
+ });
62
+ });
@@ -11,6 +11,7 @@
11
11
 
12
12
  import { AsyncLocalStorage } from 'node:async_hooks';
13
13
  import { debug } from '$shared/utils/logger';
14
+ import type { EngineType } from '$shared/types/unified';
14
15
 
15
16
  // Execution context for MCP tool handlers
16
17
  interface ExecutionContext {
@@ -30,7 +31,10 @@ class ProjectContextService {
30
31
  private streamProjectMap = new Map<string, string>();
31
32
 
32
33
  // Track active streams (streamId -> context)
33
- private activeStreams = new Map<string, { chatSessionId: string; projectId: string; startedAt: number }>();
34
+ private activeStreams = new Map<
35
+ string,
36
+ { chatSessionId: string; projectId: string; startedAt: number; engine?: EngineType }
37
+ >();
34
38
 
35
39
  // Track the most recently active stream (for MCP tool execution context)
36
40
  private mostRecentActiveStream: { streamId: string; chatSessionId: string; projectId: string } | null = null;
@@ -42,9 +46,10 @@ class ProjectContextService {
42
46
  * Per-stream AbortSignal map. The stream-manager registers each stream's
43
47
  * AbortController.signal here when the stream starts so MCP tool handlers
44
48
  * can fast-fail on cancellation. The remote-MCP HTTP transport (used by
45
- * OpenCode/Codex/Copilot/Qwen) does not preserve the engine's
46
- * AsyncLocalStorage context across the HTTP boundary — `mostRecentActiveStream`
47
- * is the practical fallback for resolving "which stream is asking right now".
49
+ * OpenCode/Codex/Copilot/Qwen/Cursor) does not preserve the engine's
50
+ * AsyncLocalStorage context across the HTTP boundary; the bridge re-creates
51
+ * it from the identity in its URL, and `mostRecentActiveStream` is the last
52
+ * resort for a caller that could not be identified at all.
48
53
  */
49
54
  private streamSignals = new Map<string, AbortSignal>();
50
55
 
@@ -69,7 +74,7 @@ class ProjectContextService {
69
74
  * Register a stream ID with its project ID
70
75
  * Should be called when a chat stream starts
71
76
  */
72
- registerStream(streamId: string, projectId: string, chatSessionId?: string): void {
77
+ registerStream(streamId: string, projectId: string, chatSessionId?: string, engine?: EngineType): void {
73
78
  if (!streamId || !projectId) {
74
79
  debug.warn('mcp', `⚠️ Cannot register stream: streamId='${streamId}' projectId='${projectId}'`);
75
80
  return;
@@ -82,7 +87,8 @@ class ProjectContextService {
82
87
  this.activeStreams.set(streamId, {
83
88
  chatSessionId,
84
89
  projectId,
85
- startedAt: Date.now()
90
+ startedAt: Date.now(),
91
+ engine
86
92
  });
87
93
 
88
94
  // Update most recent active stream
@@ -156,6 +162,13 @@ class ProjectContextService {
156
162
  }
157
163
  }
158
164
  }
165
+ if (context?.projectId) {
166
+ const inProject = this.mostRecentStreamInProject(context.projectId);
167
+ if (inProject) {
168
+ const signal = this.streamSignals.get(inProject.streamId);
169
+ if (signal) return signal;
170
+ }
171
+ }
159
172
  if (this.mostRecentActiveStream) {
160
173
  return this.streamSignals.get(this.mostRecentActiveStream.streamId);
161
174
  }
@@ -188,6 +201,60 @@ class ProjectContextService {
188
201
  }
189
202
  }
190
203
 
204
+ /**
205
+ * The most recently started live stream in `projectId`.
206
+ *
207
+ * The bridge can bind a project without a chat session — Codex's client, and
208
+ * therefore its bridge URL, is built once per project and shared by every
209
+ * chat session in it. Resolving the session inside that project is still a
210
+ * guess when several of them stream at once, but it is a guess confined to
211
+ * the right project, which is what tab ownership and cancellation need.
212
+ */
213
+ private mostRecentStreamInProject(projectId: string): { streamId: string; chatSessionId: string } | undefined {
214
+ let best: { streamId: string; chatSessionId: string; startedAt: number } | undefined;
215
+ for (const [streamId, info] of this.activeStreams) {
216
+ if (info.projectId !== projectId) continue;
217
+ if (!best || info.startedAt > best.startedAt) {
218
+ best = { streamId, chatSessionId: info.chatSessionId, startedAt: info.startedAt };
219
+ }
220
+ }
221
+ return best ? { streamId: best.streamId, chatSessionId: best.chatSessionId } : undefined;
222
+ }
223
+
224
+ /**
225
+ * The execution context of the most recent stream running on `engine`.
226
+ *
227
+ * For the engines whose MCP bridge URL cannot carry the calling stream —
228
+ * Open Code bakes its MCP config into a server that is pooled per Profile
229
+ * and shared by every project — this is as precise as the bridge can be. It
230
+ * is still strictly narrower than "the most recent stream anywhere", which
231
+ * is what sent a tool call from the project the agent is working in to
232
+ * whichever project the user had most recently prompted in.
233
+ */
234
+ getContextForEngine(engine: EngineType): ExecutionContext | undefined {
235
+ let best: { streamId: string; chatSessionId: string; projectId: string; startedAt: number } | undefined;
236
+ let candidates = 0;
237
+
238
+ for (const [streamId, info] of this.activeStreams) {
239
+ if (info.engine !== engine) continue;
240
+ candidates++;
241
+ if (!best || info.startedAt > best.startedAt) {
242
+ best = { streamId, chatSessionId: info.chatSessionId, projectId: info.projectId, startedAt: info.startedAt };
243
+ }
244
+ }
245
+
246
+ if (!best) return undefined;
247
+ if (candidates > 1) {
248
+ debug.warn(
249
+ 'mcp',
250
+ `⚠️ ${candidates} ${engine} streams are live and the bridge cannot tell them apart — ` +
251
+ `attributing this call to the most recent one (project ${best.projectId})`
252
+ );
253
+ }
254
+
255
+ return { chatSessionId: best.chatSessionId, projectId: best.projectId, streamId: best.streamId };
256
+ }
257
+
191
258
  /**
192
259
  * Get the last used project ID (fallback)
193
260
  * This is used as a last resort when no session context is available
@@ -286,7 +353,13 @@ class ProjectContextService {
286
353
  return context.chatSessionId;
287
354
  }
288
355
 
289
- // 2. Fallback to most recent active stream
356
+ // 2. Within the bound project, when the caller could only name that much
357
+ if (context?.projectId) {
358
+ const inProject = this.mostRecentStreamInProject(context.projectId);
359
+ if (inProject) return inProject.chatSessionId;
360
+ }
361
+
362
+ // 3. Fallback to most recent active stream
290
363
  if (this.mostRecentActiveStream) {
291
364
  return this.mostRecentActiveStream.chatSessionId;
292
365
  }
@@ -37,10 +37,10 @@ function sessionCount(userId: string): number {
37
37
  return row.count;
38
38
  }
39
39
 
40
- function mcpRequest(token?: string): Request {
40
+ function mcpRequest(token?: string, query = ''): Request {
41
41
  const headers: Record<string, string> = { 'Content-Type': 'application/json' };
42
42
  if (token) headers['Authorization'] = `Bearer ${token}`;
43
- return new Request('http://localhost/mcp', {
43
+ return new Request(`http://localhost/mcp${query}`, {
44
44
  method: 'POST',
45
45
  headers,
46
46
  body: JSON.stringify({
@@ -134,6 +134,21 @@ describe('MCP Remote Server Authentication', () => {
134
134
  expect(response.status).not.toBe(401);
135
135
  });
136
136
 
137
+ test('accepts a caller-identified bridge URL', async () => {
138
+ // Each engine's config builder addresses the bridge with the project (and
139
+ // where its config lives that long, the chat session) driving the call, so
140
+ // tool handlers are bound to it instead of guessing from ambient state.
141
+ // Routing must not care that the query string is there.
142
+ const query = '?engine=codex&project=project-a&session=session-a';
143
+ const response = await handleMcpRequest(mcpRequest(getMcpServiceToken(), query));
144
+ expect(response.status).not.toBe(401);
145
+ });
146
+
147
+ test('rejects a caller-identified bridge URL without a token', async () => {
148
+ const response = await handleMcpRequest(mcpRequest(undefined, '?engine=opencode'));
149
+ expect(response.status).toBe(401);
150
+ });
151
+
137
152
  test('accepts a valid PAT token', async () => {
138
153
  const response = await handleMcpRequest(mcpRequest(patToken));
139
154
  expect(response.status).not.toBe(401);
@@ -18,7 +18,7 @@
18
18
 
19
19
  import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
20
20
  import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
21
- import { createRemoteMcpServer } from './servers/helper';
21
+ import { createRemoteMcpServer, type RemoteMcpCaller } from './servers/helper';
22
22
  import { createExternalProxyServer } from '../external/proxy';
23
23
  import { debug } from '$shared/utils/logger';
24
24
  import { authQueries } from '$backend/database/queries';
@@ -213,14 +213,47 @@ async function handleStreamable(
213
213
  return jsonRpcError(400, -32000, 'Bad Request: No valid session ID provided');
214
214
  }
215
215
 
216
+ /**
217
+ * Who is on the other end of an internal-bridge request.
218
+ *
219
+ * Read from the query string each engine's config builder writes (see
220
+ * `internalBridgeUrl` in `./config.ts`), which says as much as that config's
221
+ * lifetime allows: the calling stream, its project, or only the engine. A URL
222
+ * with none of it — an older config, or a client that stripped the query —
223
+ * yields `undefined` and the handlers fall back to their own resolution, which
224
+ * is what every engine did before this existed.
225
+ */
226
+ function callerFromRequest(request: Request): RemoteMcpCaller | undefined {
227
+ const params = new URL(request.url).searchParams;
228
+ const projectId = params.get('project') ?? undefined;
229
+ const chatSessionId = params.get('session') ?? undefined;
230
+ const engine = (params.get('engine') as EngineType | null) ?? undefined;
231
+
232
+ if (projectId) return { context: { projectId, ...(chatSessionId && { chatSessionId }) }, engine };
233
+ if (engine) return { engine };
234
+ return undefined;
235
+ }
236
+
216
237
  /**
217
238
  * Handle an incoming request to the INTERNAL `clopen-mcp` bridge (`/mcp`).
218
239
  * Serves the in-process custom tools defined via `defineServer()`.
240
+ *
241
+ * The caller is read from the initialize request only, and the resulting server
242
+ * stays bound to that session — the same way the external bridge binds its
243
+ * per-engine tool filter. That is correct because the identity in the URL is a
244
+ * property of the engine session, not of a single tool call: a Codex turn gets
245
+ * a fresh subprocess and therefore a fresh MCP session, while Copilot/Qwen/
246
+ * Cursor keep one per chat session, which is exactly the scope of `session`.
219
247
  */
220
248
  export async function handleMcpRequest(request: Request): Promise<Response> {
221
- return handleStreamable(request, 'Remote MCP', async () => {
249
+ const caller = callerFromRequest(request);
250
+ const label = caller?.context
251
+ ? `Remote MCP (${caller.engine ?? 'engine'}, project ${caller.context.projectId})`
252
+ : `Remote MCP${caller?.engine ? ` (${caller.engine})` : ''}`;
253
+
254
+ return handleStreamable(request, label, async () => {
222
255
  const { allServers, enabledConfig } = await getServerDeps();
223
- return { server: createRemoteMcpServer(allServers, enabledConfig) };
256
+ return { server: createRemoteMcpServer(allServers, enabledConfig, caller) };
224
257
  });
225
258
  }
226
259
 
@@ -13,6 +13,8 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
13
13
  import type { z } from "zod";
14
14
  import { projectContextService } from '../project-context';
15
15
  import { validateMcpOutput } from '../output-validator';
16
+ import type { McpExecutionContext } from '$backend/engine/types';
17
+ import type { EngineType } from '$shared/types/unified';
16
18
 
17
19
  /**
18
20
  * Infer argument types from Zod schema
@@ -143,6 +145,21 @@ export function buildServerRegistries<
143
145
  // Remote MCP Server for Open Code (HTTP transport, in-process execution)
144
146
  // ============================================================================
145
147
 
148
+ /**
149
+ * Who the bridge is talking to.
150
+ *
151
+ * `context` is the calling stream, named by the query string its engine's
152
+ * config builder put on the bridge URL — the HTTP equivalent of the
153
+ * `McpExecutionContext` the in-process engines bind directly. `engine` alone is
154
+ * the fallback for a config that cannot name the caller (Open Code's pooled
155
+ * server), and is resolved per call rather than pinned, because the stream it
156
+ * refers to changes while the MCP session stays open.
157
+ */
158
+ export interface RemoteMcpCaller {
159
+ context?: McpExecutionContext;
160
+ engine?: EngineType;
161
+ }
162
+
146
163
  /**
147
164
  * Create a McpServer instance (from @modelcontextprotocol/sdk) with tools registered
148
165
  * from the same RawToolDef definitions used by Claude Code.
@@ -152,10 +169,12 @@ export function buildServerRegistries<
152
169
  *
153
170
  * @param servers - Server definitions from defineServer()
154
171
  * @param enabledConfig - Which servers/tools are enabled (from mcpServersConfig)
172
+ * @param caller - Identity of the engine/stream on the other end of the bridge
155
173
  */
156
174
  export function createRemoteMcpServer(
157
175
  servers: readonly ServerWithMeta<string, readonly string[]>[],
158
- enabledConfig: Record<string, { enabled: boolean; tools: readonly string[] }>
176
+ enabledConfig: Record<string, { enabled: boolean; tools: readonly string[] }>,
177
+ caller?: RemoteMcpCaller
159
178
  ): McpServer {
160
179
  const mcpServer = new McpServer({
161
180
  name: 'clopen-mcp',
@@ -178,23 +197,34 @@ export function createRemoteMcpServer(
178
197
  // at runtime. Cast to bridge the mismatch.
179
198
  inputSchema: def.schema as Record<string, any>,
180
199
  }, async (args: Record<string, unknown>) => {
181
- // Fast-fail when the owning chat stream has already been
182
- // cancelled — the handler never runs. Without this, the
183
- // engine subprocess dies on cancel but in-flight HTTP-MCP
184
- // tool calls continue to drive puppeteer ops, surfacing as
185
- // "preview keeps moving by itself" after interrupt.
186
- const signal = projectContextService.getCurrentSignal();
187
- if (signal?.aborted) {
188
- return {
189
- content: [{ type: 'text' as const, text: `Tool ${String(toolName)} was cancelled because the chat stream was interrupted.` }],
190
- isError: true,
191
- } as any;
192
- }
193
- const result = await def.handler(args) as any;
194
- if (result?.content) {
195
- result.content = validateMcpOutput(result.content, toolName as string);
196
- }
197
- return result;
200
+ const run = async () => {
201
+ // Fast-fail when the owning chat stream has already been
202
+ // cancelled — the handler never runs. Without this, the
203
+ // engine subprocess dies on cancel but in-flight HTTP-MCP
204
+ // tool calls continue to drive puppeteer ops, surfacing as
205
+ // "preview keeps moving by itself" after interrupt.
206
+ const signal = projectContextService.getCurrentSignal();
207
+ if (signal?.aborted) {
208
+ return {
209
+ content: [{ type: 'text' as const, text: `Tool ${String(toolName)} was cancelled because the chat stream was interrupted.` }],
210
+ isError: true,
211
+ } as any;
212
+ }
213
+ const result = await def.handler(args) as any;
214
+ if (result?.content) {
215
+ result.content = validateMcpOutput(result.content, toolName as string);
216
+ }
217
+ return result;
218
+ };
219
+
220
+ // Bind the caller for the duration of the handler, exactly as the
221
+ // in-process path does. Without it every handler that asks "which
222
+ // project is this?" answers with the most recently started stream
223
+ // anywhere in the app.
224
+ const bound = caller?.context
225
+ ?? (caller?.engine ? projectContextService.getContextForEngine(caller.engine) : undefined);
226
+
227
+ return bound ? projectContextService.runWithContextAsync(bound, run) : run();
198
228
  });
199
229
  }
200
230
  }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * The headers are only worth anything if they survive the way Clopen actually
3
+ * returns responses. The SPA fallback and the static file handler in
4
+ * `backend/index.ts` hand back a raw `Response`, which is a different path
5
+ * through Elysia than a plain object return — so both are exercised here.
6
+ */
7
+
8
+ import { describe, expect, test } from 'bun:test';
9
+ import { Elysia } from 'elysia';
10
+ import { SECURITY_HEADERS, securityMiddleware } from './security';
11
+
12
+ const app = new Elysia()
13
+ .use(securityMiddleware)
14
+ .get('/json', () => ({ ok: true }))
15
+ // Mirrors the production SPA fallback: a raw Response with its own headers.
16
+ .get('/spa', () => new Response('<!doctype html>', {
17
+ headers: { 'Content-Type': 'text/html; charset=utf-8' }
18
+ }));
19
+
20
+ async function headersFor(path: string): Promise<Headers> {
21
+ const response = await app.handle(new Request(`http://localhost${path}`));
22
+ return response.headers;
23
+ }
24
+
25
+ function csp(headers: Headers): string {
26
+ return headers.get('content-security-policy') ?? '';
27
+ }
28
+
29
+ describe('security headers reach the response', () => {
30
+ for (const path of ['/json', '/spa']) {
31
+ test(`every header is set on ${path}`, async () => {
32
+ const headers = await headersFor(path);
33
+ for (const [name, value] of Object.entries(SECURITY_HEADERS)) {
34
+ expect(headers.get(name.toLowerCase())).toBe(value);
35
+ }
36
+ });
37
+ }
38
+
39
+ test('the raw Response keeps its own Content-Type', async () => {
40
+ const headers = await headersFor('/spa');
41
+ expect(headers.get('content-type')).toBe('text/html; charset=utf-8');
42
+ });
43
+ });
44
+
45
+ describe('CSP covers what the app loads', () => {
46
+ test('Monaco can load its scripts, styles and codicon font from the CDN', async () => {
47
+ const policy = csp(await headersFor('/spa'));
48
+ for (const directive of ['script-src', 'style-src', 'font-src', 'connect-src']) {
49
+ expect(policy).toMatch(new RegExp(`${directive} [^;]*https://cdn\\.jsdelivr\\.net`));
50
+ }
51
+ });
52
+
53
+ test("Monaco's blob-bootstrapped language workers are allowed", async () => {
54
+ const policy = csp(await headersFor('/spa'));
55
+ expect(policy).toMatch(/script-src [^;]*blob:/);
56
+ expect(policy).toMatch(/worker-src [^;]*blob:/);
57
+ });
58
+
59
+ test('object-URL previews are allowed for media, frames and images', async () => {
60
+ const policy = csp(await headersFor('/spa'));
61
+ // MediaPreview.svelte: <audio>/<video> src, the PDF <iframe>, and images.
62
+ expect(policy).toMatch(/media-src [^;]*blob:/);
63
+ expect(policy).toMatch(/frame-src [^;]*blob:/);
64
+ expect(policy).toMatch(/img-src [^;]*blob:/);
65
+ });
66
+
67
+ test('remote images in rendered markdown are not blocked', async () => {
68
+ const policy = csp(await headersFor('/spa'));
69
+ expect(policy).toMatch(/img-src [^;]*https:/);
70
+ });
71
+
72
+ test('embedding, base rewriting and off-site form posts are shut down', async () => {
73
+ const policy = csp(await headersFor('/spa'));
74
+ expect(policy).toContain("frame-ancestors 'none'");
75
+ expect(policy).toContain("object-src 'none'");
76
+ expect(policy).toContain("base-uri 'self'");
77
+ expect(policy).toContain("form-action 'self'");
78
+ });
79
+ });
80
+
81
+ describe('Permissions-Policy matches what the host bridge relays', () => {
82
+ test('device APIs the Preview Browser relays stay available to the app', async () => {
83
+ const policy = (await headersFor('/spa')).get('permissions-policy') ?? '';
84
+ for (const feature of ['camera', 'microphone', 'geolocation', 'display-capture', 'clipboard-read']) {
85
+ expect(policy).toContain(`${feature}=(self)`);
86
+ }
87
+ });
88
+
89
+ test('features Clopen never uses are denied', async () => {
90
+ const policy = (await headersFor('/spa')).get('permissions-policy') ?? '';
91
+ for (const feature of ['payment', 'usb', 'serial', 'bluetooth', 'midi', 'hid']) {
92
+ expect(policy).toContain(`${feature}=()`);
93
+ }
94
+ });
95
+ });