@myrialabs/clopen 0.4.31 → 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.
- package/backend/auth/permissions.test.ts +0 -1
- package/backend/auth/permissions.ts +0 -4
- package/backend/chat/stream-manager.ts +31 -12
- package/backend/database/migrations/068_create_engine_config_revision.test.ts +121 -0
- package/backend/database/migrations/068_create_engine_config_revision.ts +117 -0
- package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
- package/backend/database/migrations/index.ts +14 -0
- package/backend/database/queries/db-client-connection-queries.ts +7 -2
- package/backend/database/queries/file-audit-log-queries.ts +1 -0
- package/backend/database/queries/index.ts +3 -0
- package/backend/database/queries/ssh-connection-queries.ts +244 -0
- package/backend/database/queries/ssh-known-host-queries.ts +67 -0
- package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
- package/backend/db-client/connection-manager.ts +8 -1
- package/backend/engine/README.md +16 -0
- package/backend/engine/adapters/claude/stream.ts +89 -49
- package/backend/engine/adapters/cline/stream.ts +62 -24
- package/backend/engine/adapters/codex/message-converter.ts +18 -12
- package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
- package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
- package/backend/engine/adapters/codex/stream.ts +78 -22
- package/backend/engine/adapters/copilot/stream.ts +97 -53
- package/backend/engine/adapters/cursor/stream.ts +75 -35
- package/backend/engine/adapters/opencode/server.ts +511 -134
- package/backend/engine/adapters/opencode/stream.ts +131 -79
- package/backend/engine/adapters/pi/stream.ts +63 -24
- package/backend/engine/adapters/qwen/stream.ts +92 -59
- package/backend/engine/adapters/run-registry.test.ts +75 -0
- package/backend/engine/adapters/run-registry.ts +63 -0
- package/backend/engine/config-revision.ts +150 -0
- package/backend/engine/docs/adapter-contract.md +47 -9
- package/backend/engine/docs/adding-an-engine.md +8 -0
- package/backend/engine/docs/frontend-and-chat.md +39 -0
- package/backend/engine/docs/lessons-learned.md +70 -0
- package/backend/engine/docs/quick-reference.md +3 -1
- package/backend/engine/hot-reload.ts +99 -0
- package/backend/engine/index.ts +96 -24
- package/backend/engine/types.ts +17 -5
- package/backend/files/file-watcher.ts +283 -51
- package/backend/files/git-events.test.ts +110 -0
- package/backend/git/git-dirs.test.ts +132 -0
- package/backend/git/git-dirs.ts +0 -0
- package/backend/git/git-executor.ts +22 -3
- package/backend/git/git-service.ts +1 -1
- package/backend/git/nested-repos.test.ts +224 -0
- package/backend/git/nested-repos.ts +386 -0
- package/backend/http/audio.ts +5 -32
- package/backend/http/bearer-auth.ts +47 -0
- package/backend/http/files-download.test.ts +146 -0
- package/backend/http/files-download.ts +109 -0
- package/backend/http/files-upload.ts +3 -29
- package/backend/http/ssh-sftp.ts +133 -0
- package/backend/index.ts +23 -2
- package/backend/mcp/README.md +34 -6
- package/backend/mcp/index.ts +8 -8
- package/backend/mcp/internal/config.ts +69 -19
- package/backend/mcp/internal/project-context.test.ts +40 -0
- package/backend/mcp/internal/project-context.ts +80 -7
- package/backend/mcp/internal/remote-server.test.ts +17 -2
- package/backend/mcp/internal/remote-server.ts +36 -3
- package/backend/mcp/internal/servers/helper.ts +48 -18
- package/backend/preview/browser/browser-video-capture.ts +51 -4
- package/backend/snapshot/gitignore.ts +10 -174
- package/backend/ssh/client-pool.ts +196 -0
- package/backend/ssh/connect.ts +375 -0
- package/backend/ssh/disk-usage.test.ts +134 -0
- package/backend/ssh/disk-usage.ts +214 -0
- package/backend/ssh/forwards.ts +309 -0
- package/backend/ssh/health.ts +141 -0
- package/backend/ssh/known-hosts.ts +96 -0
- package/backend/ssh/pty-backend.ts +215 -0
- package/backend/ssh/ptykit.ts +66 -0
- package/backend/ssh/sftp.test.ts +242 -0
- package/backend/ssh/sftp.ts +967 -0
- package/backend/ssh/socks5.test.ts +167 -0
- package/backend/ssh/socks5.ts +164 -0
- package/backend/ssh/tunnel.ts +87 -0
- package/backend/ws/chat/stream.ts +24 -0
- package/backend/ws/db-client/connections.ts +1 -0
- package/backend/ws/engine/codex/accounts.ts +0 -12
- package/backend/ws/engine/copilot/accounts.ts +0 -10
- package/backend/ws/engine/cursor/accounts.ts +0 -10
- package/backend/ws/engine/index.ts +17 -2
- package/backend/ws/engine/opencode/providers.ts +0 -52
- package/backend/ws/files/read.ts +1 -1
- package/backend/ws/files/watch.ts +5 -1
- package/backend/ws/git/conflict.ts +1 -1
- package/backend/ws/git/diff.ts +1 -1
- package/backend/ws/git/staging.ts +1 -1
- package/backend/ws/git/status.ts +1 -1
- package/backend/ws/index.ts +4 -0
- package/backend/ws/ssh/access.ts +31 -0
- package/backend/ws/ssh/connections.ts +224 -0
- package/backend/ws/ssh/forwards.ts +109 -0
- package/backend/ws/ssh/index.ts +18 -0
- package/backend/ws/ssh/sftp.ts +259 -0
- package/backend/ws/ssh/tunnel.ts +93 -0
- package/dist/assets/{index-DYwQ5bP8.js → index-BF4buYmI.js} +1 -1
- package/dist/assets/{index-DUc5T21e.js → index-BW0DA8NV.js} +1 -1
- package/dist/assets/main-BbwWLJRN.js +1057 -0
- package/dist/assets/main-CCvRMXlP.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/database/schema.ts +49 -0
- package/shared/types/db-client/connection.ts +6 -0
- package/shared/types/ssh/connection.ts +80 -0
- package/shared/types/ssh/forward.ts +46 -0
- package/shared/types/ssh/index.ts +8 -0
- package/shared/types/ssh/known-host.ts +19 -0
- package/shared/types/ssh/sftp.ts +141 -0
- package/shared/utils/logger.ts +1 -0
- package/backend/ws/engine/restart.ts +0 -54
- package/dist/assets/main-VgdjTBLR.css +0 -1
- package/dist/assets/main-r0iv2PDz.js +0 -1044
package/backend/mcp/README.md
CHANGED
|
@@ -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
|
package/backend/mcp/index.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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
|
|
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(
|
|
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
|
|
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
|
|
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
|
|
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(
|
|
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
|
|
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
|
|
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
|
|
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(
|
|
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
|
|
654
|
+
const url = internalBridgeUrl('cursor', context);
|
|
608
655
|
|
|
609
|
-
debug.log('mcp', `📦 Cursor MCP: remote server at
|
|
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
|
|
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(
|
|
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
|
|
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
|
|
705
|
+
debug.log('mcp', `📦 Qwen MCP: remote server at ${url} (${includeTools.length} tools)`);
|
|
656
706
|
|
|
657
707
|
return {
|
|
658
708
|
'clopen-mcp': {
|
|
659
|
-
httpUrl:
|
|
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<
|
|
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
|
|
47
|
-
*
|
|
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.
|
|
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(
|
|
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
|
-
|
|
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
|
|