@myrialabs/clopen 0.3.8 โ†’ 0.3.10

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 (146) hide show
  1. package/README.md +22 -19
  2. package/backend/auth/auth-service.ts +56 -1
  3. package/backend/auth/permissions.ts +66 -2
  4. package/backend/auth/session-cleanup.ts +58 -0
  5. package/backend/chat/stream-manager.ts +143 -13
  6. package/backend/database/migrations/032_seed_copilot_provider.ts +19 -0
  7. package/backend/database/migrations/033_seed_codex_provider.ts +19 -0
  8. package/backend/database/migrations/034_seed_qwen_provider.ts +119 -0
  9. package/backend/database/migrations/035_add_owner_to_db_client_connections.ts +34 -0
  10. package/backend/database/migrations/index.ts +29 -1
  11. package/backend/database/queries/db-client-connection-queries.ts +160 -54
  12. package/backend/database/queries/engine-queries.ts +12 -0
  13. package/backend/database/queries/project-queries.ts +10 -5
  14. package/backend/db-client/connection-manager.ts +9 -3
  15. package/backend/engine/README.md +1702 -0
  16. package/backend/engine/adapters/claude/models.ts +141 -0
  17. package/backend/engine/adapters/claude/stream.ts +1 -1
  18. package/backend/engine/adapters/codex/credential.ts +179 -0
  19. package/backend/engine/adapters/codex/error-handler.ts +65 -0
  20. package/backend/engine/adapters/codex/index.ts +1 -0
  21. package/backend/engine/adapters/codex/message-converter.ts +646 -0
  22. package/backend/engine/adapters/codex/models.ts +105 -0
  23. package/backend/engine/adapters/codex/patch-rollout.ts +169 -0
  24. package/backend/engine/adapters/codex/session-fork.ts +149 -0
  25. package/backend/engine/adapters/codex/stream.ts +310 -0
  26. package/backend/engine/adapters/codex/usage-rollout.ts +145 -0
  27. package/backend/engine/adapters/copilot/error-handler.ts +94 -0
  28. package/backend/engine/adapters/copilot/index.ts +1 -0
  29. package/backend/engine/adapters/copilot/message-converter.ts +973 -0
  30. package/backend/engine/adapters/copilot/models.ts +92 -0
  31. package/backend/engine/adapters/copilot/session-fork.ts +111 -0
  32. package/backend/engine/adapters/copilot/stream.ts +570 -0
  33. package/backend/engine/adapters/opencode/config.ts +56 -104
  34. package/backend/engine/adapters/opencode/error-handler.ts +71 -0
  35. package/backend/engine/adapters/opencode/models.ts +79 -0
  36. package/backend/engine/adapters/opencode/presets.ts +91 -0
  37. package/backend/engine/adapters/opencode/stream.ts +8 -114
  38. package/backend/engine/adapters/qwen/credential.ts +78 -0
  39. package/backend/engine/adapters/qwen/environment.ts +84 -0
  40. package/backend/engine/adapters/qwen/error-handler.ts +71 -0
  41. package/backend/engine/adapters/qwen/index.ts +1 -0
  42. package/backend/engine/adapters/qwen/message-converter.ts +1055 -0
  43. package/backend/engine/adapters/qwen/models.ts +81 -0
  44. package/backend/engine/adapters/qwen/presets.ts +51 -0
  45. package/backend/engine/adapters/qwen/session-fork.ts +97 -0
  46. package/backend/engine/adapters/qwen/stream.ts +379 -0
  47. package/backend/engine/index.ts +35 -0
  48. package/backend/engine/install-recipes.ts +80 -1
  49. package/backend/engine/install-runner.ts +4 -0
  50. package/backend/files/path-browsing.ts +20 -0
  51. package/backend/git/git-service.ts +81 -11
  52. package/backend/git/git-spawn-validation.test.ts +75 -0
  53. package/backend/git/git-spawn-validation.ts +77 -0
  54. package/backend/index.ts +5 -0
  55. package/backend/mcp/README.md +84 -14
  56. package/backend/mcp/config.ts +218 -17
  57. package/backend/mcp/index.ts +2 -0
  58. package/backend/mcp/project-context.ts +55 -0
  59. package/backend/mcp/servers/browser-automation/actions.ts +6 -1
  60. package/backend/mcp/servers/helper.ts +13 -0
  61. package/backend/middleware/error-handler.ts +16 -2
  62. package/backend/preview/browser/browser-preview-service.ts +4 -4
  63. package/backend/preview/browser/browser-tab-manager.ts +23 -3
  64. package/backend/snapshot/gitignore.ts +4 -9
  65. package/backend/tunnel/cloudflared/binary.ts +2 -2
  66. package/backend/tunnel/global-tunnel-manager.ts +9 -3
  67. package/backend/utils/ws.ts +5 -1
  68. package/backend/ws/README.md +128 -3
  69. package/backend/ws/access.ts +56 -0
  70. package/backend/ws/auth/index.ts +14 -0
  71. package/backend/ws/auth/login.ts +3 -0
  72. package/backend/ws/auth/users.ts +61 -1
  73. package/backend/ws/chat/stream.ts +139 -22
  74. package/backend/ws/db-client/access.ts +19 -0
  75. package/backend/ws/db-client/connections.ts +31 -17
  76. package/backend/ws/db-client/io.ts +7 -9
  77. package/backend/ws/db-client/query.ts +86 -32
  78. package/backend/ws/db-client/schema.ts +9 -4
  79. package/backend/ws/db-client/structure.ts +22 -10
  80. package/backend/ws/engine/access.ts +39 -0
  81. package/backend/ws/engine/claude/accounts.ts +15 -10
  82. package/backend/ws/engine/codex/accounts.ts +516 -0
  83. package/backend/ws/engine/codex/index.ts +14 -0
  84. package/backend/ws/engine/codex/status.ts +87 -0
  85. package/backend/ws/engine/copilot/accounts.ts +122 -0
  86. package/backend/ws/engine/copilot/index.ts +13 -0
  87. package/backend/ws/engine/copilot/status.ts +54 -0
  88. package/backend/ws/engine/index.ts +7 -1
  89. package/backend/ws/engine/opencode/providers.ts +1 -1
  90. package/backend/ws/engine/qwen/accounts.ts +137 -0
  91. package/backend/ws/engine/qwen/index.ts +15 -0
  92. package/backend/ws/engine/qwen/presets.ts +40 -0
  93. package/backend/ws/engine/qwen/status.ts +54 -0
  94. package/backend/ws/files/path-access.ts +101 -0
  95. package/backend/ws/files/read.ts +26 -11
  96. package/backend/ws/files/search.ts +10 -6
  97. package/backend/ws/files/state.ts +3 -0
  98. package/backend/ws/files/watch.ts +7 -1
  99. package/backend/ws/files/write.ts +109 -15
  100. package/backend/ws/git/branch.ts +13 -19
  101. package/backend/ws/git/commit-message.ts +3 -4
  102. package/backend/ws/git/commit.ts +5 -7
  103. package/backend/ws/git/conflict.ts +7 -10
  104. package/backend/ws/git/diff.ts +7 -10
  105. package/backend/ws/git/log.ts +3 -4
  106. package/backend/ws/git/remote.ts +30 -43
  107. package/backend/ws/git/staging.ts +13 -19
  108. package/backend/ws/git/status.ts +7 -11
  109. package/backend/ws/messages/crud.ts +7 -13
  110. package/backend/ws/preview/access.ts +45 -0
  111. package/backend/ws/preview/browser/cleanup.ts +3 -11
  112. package/backend/ws/preview/browser/console.ts +7 -42
  113. package/backend/ws/preview/browser/interact.ts +2 -6
  114. package/backend/ws/preview/browser/native-ui.ts +5 -18
  115. package/backend/ws/preview/browser/stats.ts +2 -12
  116. package/backend/ws/preview/browser/tab-info.ts +4 -20
  117. package/backend/ws/preview/browser/tab.ts +4 -27
  118. package/backend/ws/preview/browser/webcodecs.ts +6 -47
  119. package/backend/ws/projects/crud.ts +15 -16
  120. package/backend/ws/projects/status.ts +5 -1
  121. package/backend/ws/sessions/crud.ts +31 -36
  122. package/backend/ws/settings/crud.ts +13 -13
  123. package/backend/ws/snapshot/restore.ts +5 -2
  124. package/backend/ws/snapshot/timeline.ts +3 -1
  125. package/backend/ws/system-tools/access.ts +28 -0
  126. package/backend/ws/system-tools/install.ts +13 -4
  127. package/backend/ws/system-tools/status.ts +5 -2
  128. package/backend/ws/terminal/access.ts +56 -0
  129. package/backend/ws/terminal/persistence.ts +13 -7
  130. package/backend/ws/terminal/session.ts +35 -14
  131. package/backend/ws/terminal/stream.ts +4 -1
  132. package/dist/assets/{index-DqAGCTFT.js โ†’ index-C1afGwHY.js} +2 -2
  133. package/dist/assets/main-CZb3Y_Z_.js +315 -0
  134. package/dist/assets/main-Cn8cX2DY.css +1 -0
  135. package/dist/index.html +2 -2
  136. package/package.json +5 -1
  137. package/shared/constants/engines.ts +45 -140
  138. package/shared/types/database/schema.ts +1 -0
  139. package/shared/types/unified/common.ts +1 -1
  140. package/shared/types/unified/engine.ts +29 -1
  141. package/shared/types/unified/index.ts +2 -0
  142. package/shared/types/unified/message.ts +1 -1
  143. package/shared/types/unified/tool.ts +17 -2
  144. package/shared/utils/ws-server.ts +14 -0
  145. package/dist/assets/main-DsED0rLr.js +0 -304
  146. package/dist/assets/main-eWY9R8g9.css +0 -1
@@ -1,6 +1,6 @@
1
1
  # Custom MCP Tools
2
2
 
3
- Custom MCP (Model Context Protocol) tools for adding specialized functionality to both **Claude Code** and **Open Code** engines. Servers are defined once and shared across both engines via a single-source-of-truth architecture.
3
+ Custom MCP (Model Context Protocol) tools for adding specialized functionality to all AI engines (**Claude Code**, **Open Code**, **Codex**, **Copilot**, โ€ฆ). Servers are defined once and shared across every engine via a single-source-of-truth architecture.
4
4
 
5
5
  ## ๐Ÿ“š Table of Contents
6
6
 
@@ -22,10 +22,11 @@ Custom MCP (Model Context Protocol) tools for adding specialized functionality t
22
22
  System for adding custom tools to AI engines with type-safe TypeScript definitions. Tools are defined once using `defineServer()` and automatically available to both Claude Code (in-process) and Open Code (remote HTTP MCP server).
23
23
 
24
24
  **Features:**
25
- - Single source of truth โ€” define tools once, use in both engines
25
+ - Single source of truth โ€” define tools once, use in every engine
26
26
  - In-process execution for Claude Code via `createSdkMcpServer`
27
- - Remote HTTP MCP server for Open Code via `createRemoteMcpServer`
28
- - Both engines execute handlers in-process (no subprocess, no bridge)
27
+ - Remote HTTP MCP server (Streamable HTTP) for Open Code, Codex, and
28
+ Copilot via `createRemoteMcpServer` mounted at `/mcp`
29
+ - All engines execute handlers in-process (no subprocess, no bridge)
29
30
  - Type-safe with TypeScript
30
31
  - Auto metadata extraction and registration
31
32
  - Configuration-based enable/disable
@@ -537,7 +538,22 @@ const mcpConfig = getOpenCodeMcpConfig();
537
538
  ```
538
539
 
539
540
  #### `resolveOpenCodeToolName(toolName)`
540
- Resolve an Open Code tool name to `mcp__server__tool` format (single source of truth).
541
+ Resolve a remote-MCP tool name to `mcp__server__tool` format (single source
542
+ of truth โ€” used by every non-Claude engine adapter).
543
+
544
+ The remote-MCP namespace key is always `clopen-mcp`, but engines disagree on
545
+ the separator they use to join the namespace and the bare tool name:
546
+
547
+ | Engine | Tool name shape | Separator |
548
+ | --------- | -------------------------------- | --------- |
549
+ | Open Code | `clopen-mcp_open_new_tab` | `_` |
550
+ | Copilot | `clopen-mcp-open_new_tab` | `-` |
551
+ | Codex | `open_new_tab` (bare) | n/a |
552
+
553
+ The resolver strips **both** `clopen-mcp_` and `clopen-mcp-` prefixes and
554
+ falls back to the bare-name path. **Adapters must call this helper instead
555
+ of building a per-engine resolver** โ€” if a future SDK introduces yet another
556
+ separator, extend the prefix list here, not at the call site.
541
557
 
542
558
  ```typescript
543
559
  import { resolveOpenCodeToolName } from '$backend/mcp';
@@ -545,6 +561,9 @@ import { resolveOpenCodeToolName } from '$backend/mcp';
545
561
  resolveOpenCodeToolName("clopen-mcp_get_temperature");
546
562
  // Returns: "mcp__weather-service__get_temperature"
547
563
 
564
+ resolveOpenCodeToolName("clopen-mcp-get_temperature");
565
+ // Returns: "mcp__weather-service__get_temperature"
566
+
548
567
  resolveOpenCodeToolName("get_temperature");
549
568
  // Returns: "mcp__weather-service__get_temperature"
550
569
 
@@ -552,6 +571,30 @@ resolveOpenCodeToolName("unknown_tool");
552
571
  // Returns: null
553
572
  ```
554
573
 
574
+ **Symptom of skipping this helper:** the UI renders the tool with a
575
+ doubled-up name like `mcp__clopen-mcp__clopen-mcp-open_new_tab` instead
576
+ of `mcp__browser-automation__open_new_tab`. The prefix didn't strip and
577
+ the registry lookup fell through.
578
+
579
+ #### `getCodexMcpConfig()` / `getCopilotMcpConfig()`
580
+ Sibling helpers to `getOpenCodeMcpConfig()` for the Codex and Copilot
581
+ engines. Each returns the **same** `/mcp` URL in the SDK-specific shape:
582
+
583
+ ```typescript
584
+ // Codex (config object flattened to --config flags)
585
+ getCodexMcpConfig();
586
+ // { 'clopen-mcp': { url: 'http://localhost:9151/mcp', tools: { ... } } }
587
+
588
+ // Copilot (MCPHTTPServerConfig from @github/copilot-sdk)
589
+ getCopilotMcpConfig();
590
+ // { 'clopen-mcp': { type: 'http', url: 'http://localhost:9151/mcp', tools: [...] } }
591
+ ```
592
+
593
+ When adding a new engine that consumes streamable-HTTP MCP, add a sibling
594
+ `getXxxMcpConfig()` here โ€” do **not** introduce a new HTTP listener or a
595
+ new namespace key. See `backend/engine/README.md` ยง9.12 for the full
596
+ checklist (variable naming, type imports, auto-approval surface, etc.).
597
+
555
598
  ### Helper Functions
556
599
 
557
600
  ```typescript
@@ -1078,34 +1121,61 @@ schema: {
1078
1121
 
1079
1122
  ---
1080
1123
 
1081
- ## Open Code Integration
1124
+ ## Engine Integration (Open Code, Codex, Copilot, โ€ฆ)
1082
1125
 
1083
1126
  ### How It Works
1084
1127
 
1085
- Open Code connects to a **remote HTTP MCP server** running in the main Clopen process. Tool handlers execute directly in-process โ€” no subprocess, no bridge. This is architecturally identical to how Claude Code uses in-process MCP servers.
1128
+ Every non-Claude engine connects to the **same remote HTTP MCP server**
1129
+ running in the main Clopen process. Tool handlers execute directly
1130
+ in-process โ€” no subprocess, no per-engine bridge. This is
1131
+ architecturally identical to how Claude Code uses in-process MCP
1132
+ servers.
1086
1133
 
1087
1134
  1. **`remote-server.ts`** โ€” HTTP MCP server mounted at `/mcp` on the main Elysia server. Uses `WebStandardStreamableHTTPServerTransport` from `@modelcontextprotocol/sdk` for the Streamable HTTP transport protocol.
1088
1135
 
1089
1136
  2. **`createRemoteMcpServer()`** โ€” Factory in `servers/helper.ts` that creates a `McpServer` instance with tools registered from the same `RawToolDef` definitions used by Claude Code. Each MCP session gets its own server instance.
1090
1137
 
1091
- 3. **`getOpenCodeMcpConfig()`** โ€” Returns `{ type: 'remote', url: 'http://localhost:<port>/mcp' }` so Open Code connects directly to the main server.
1138
+ 3. **`getXxxMcpConfig()` per engine** โ€” `config.ts` exports one helper per
1139
+ engine that returns the **same** `/mcp` URL in the engine's expected
1140
+ shape. They all share the `'clopen-mcp'` namespace key:
1141
+ - `getOpenCodeMcpConfig()` โ†’ `{ type: 'remote', url, ... }`
1142
+ - `getCodexMcpConfig()` โ†’ `{ url, tools: { <tool>: { approval_mode: 'approve' } } }`
1143
+ - `getCopilotMcpConfig()` โ†’ `{ type: 'http', url, tools: [...] }`
1092
1144
 
1093
- ### Adding Open Code Support to New Tools
1145
+ ### Adding a New Tool
1094
1146
 
1095
- No extra work needed! When you add a new tool via `defineServer()`, it's automatically available to both engines:
1147
+ No extra work needed! When you add a new tool via `defineServer()`, it's
1148
+ automatically available to **every** engine:
1096
1149
 
1097
1150
  - **Claude Code**: Uses the in-process `createSdkMcpServer` instance
1098
- - **Open Code**: `remote-server.ts` uses `createRemoteMcpServer()` with the same `allServers` and `mcpServersConfig`
1151
+ - **Everyone else**: `remote-server.ts` uses `createRemoteMcpServer()`
1152
+ with the same `allServers` and `mcpServersConfig`
1153
+
1154
+ ### Adding a New Engine
1155
+
1156
+ If your engine's CLI/SDK accepts a streamable-HTTP MCP URL, follow the
1157
+ checklist in `backend/engine/README.md` ยง9.12. The summary:
1158
+
1159
+ 1. Add a sibling `getXxxMcpConfig()` next to the existing helpers in
1160
+ `config.ts`. Reuse the `'clopen-mcp'` namespace key. Use the SDK's
1161
+ exported config type if it has one.
1162
+ 2. In the adapter, name the local variable holding the helper's return
1163
+ value `mcpConfig` (not `mcpServers` โ€” that shadows the registry).
1164
+ 3. Use `resolveOpenCodeToolName()` to canonicalise incoming tool names.
1165
+ If the SDK introduces a new prefix separator, extend the prefix list
1166
+ in that helper rather than building a per-engine resolver.
1167
+ 4. Wire the engine's auto-approval path (runtime callback or static
1168
+ per-tool config) so MCP tool calls don't get cancelled.
1099
1169
 
1100
1170
  ### File Locations
1101
1171
 
1102
1172
  | File | Location | Purpose |
1103
1173
  |------|----------|---------|
1104
1174
  | Tool definitions | `backend/mcp/servers/` | Single source of truth |
1105
- | Remote MCP server | `backend/mcp/remote-server.ts` | HTTP server for Open Code |
1175
+ | Remote MCP server | `backend/mcp/remote-server.ts` | HTTP server for every non-Claude engine |
1106
1176
  | Server factory | `backend/mcp/servers/helper.ts` | `createRemoteMcpServer()` |
1107
- | Open Code config | `backend/mcp/config.ts` | `getOpenCodeMcpConfig()` |
1108
- | Tool name resolver | `backend/mcp/config.ts` | `resolveOpenCodeToolName()` |
1177
+ | Per-engine config | `backend/mcp/config.ts` | `getOpenCodeMcpConfig()`, `getCodexMcpConfig()`, `getCopilotMcpConfig()` |
1178
+ | Tool name resolver | `backend/mcp/config.ts` | `resolveOpenCodeToolName()` (handles every engine's prefix variant) |
1109
1179
 
1110
1180
  ---
1111
1181
 
@@ -7,6 +7,8 @@
7
7
 
8
8
  import { createSdkMcpServer, tool, type McpSdkServerConfigWithInstance, type McpServerConfig } from "@anthropic-ai/claude-agent-sdk";
9
9
  import type { McpRemoteConfig } from '@opencode-ai/sdk';
10
+ import type { MCPHTTPServerConfig } from '@github/copilot-sdk';
11
+ import type { CLIMcpServerConfig as QwenMcpServerConfig } from '@qwen-code/sdk';
10
12
  import type { ServerConfig, ParsedMcpToolName, ServerName } from './types';
11
13
  import type { McpExecutionContext } from '../engine/types';
12
14
  import { serverRegistry, serverFactories, serverMetadata } from './servers';
@@ -103,12 +105,20 @@ export function getEnabledMcpServers(context?: McpExecutionContext): Record<stri
103
105
  if (serverConfig.enabled) {
104
106
  if (context) {
105
107
  // Create context-bound instance: wrap each tool handler so
106
- // AsyncLocalStorage context is restored on invocation
108
+ // AsyncLocalStorage context is restored on invocation, then
109
+ // short-circuit if the owning stream's AbortSignal has fired
110
+ // โ€” handler never runs, no half-completed browser ops.
107
111
  const meta = serverMetadata[serverName as ServerName];
108
112
  const sdkTools = (serverConfig.tools as readonly string[]).map(toolName => {
109
113
  const def = meta.toolDefs[toolName];
110
114
  const boundHandler = async (args: any) => {
111
- return projectContextService.runWithContextAsync(context, () => def.handler(args));
115
+ return projectContextService.runWithContextAsync(context, async () => {
116
+ const signal = projectContextService.getCurrentSignal();
117
+ if (signal?.aborted) {
118
+ return abortedToolResult(toolName);
119
+ }
120
+ return def.handler(args);
121
+ });
112
122
  };
113
123
  return tool(toolName, def.description, def.schema, boundHandler as any);
114
124
  });
@@ -132,6 +142,25 @@ export function getEnabledMcpServers(context?: McpExecutionContext): Record<stri
132
142
  return enabledServers;
133
143
  }
134
144
 
145
+ /**
146
+ * Standard MCP error response when a tool call is rejected because the
147
+ * owning chat stream has been cancelled. Returned by both the in-process
148
+ * (Claude) wrapper and the remote-HTTP wrapper so engines see a consistent
149
+ * "tool refused" outcome no matter which transport they used.
150
+ */
151
+ function abortedToolResult(toolName: string): { content: Array<{ type: 'text'; text: string }>; isError: true } {
152
+ return {
153
+ content: [{ type: 'text' as const, text: `Tool ${toolName} was cancelled because the chat stream was interrupted.` }],
154
+ isError: true,
155
+ };
156
+ }
157
+
158
+ /**
159
+ * Re-export for use by `backend/mcp/servers/helper.ts::createRemoteMcpServer`,
160
+ * which wraps remote-HTTP handlers with the same abort check.
161
+ */
162
+ export { abortedToolResult };
163
+
135
164
  /**
136
165
  * Get list of all allowed MCP tool names
137
166
  *
@@ -273,30 +302,41 @@ export function getMcpStats() {
273
302
  // ============================================================================
274
303
 
275
304
  /**
276
- * Resolve an Open Code tool name to our mcp__server__tool format.
305
+ * Resolve a remote-MCP tool name to our mcp__server__tool format.
277
306
  *
278
- * Open Code prefixes tool names with the MCP server name:
279
- * e.g. "clopen-mcp_open_new_tab" โ†’ "mcp__browser-automation__open_new_tab"
307
+ * Different SDKs prepend the MCP server config key (`clopen-mcp`) to tool
308
+ * names with different separators:
309
+ * - Open Code: "clopen-mcp_open_new_tab" (underscore)
310
+ * - Copilot: "clopen-mcp-open_new_tab" (hyphen)
311
+ * - Codex: "open_new_tab" (no prefix; mcpServerName carried separately)
312
+ * - Qwen Code: "mcp__clopen-mcp__open_new_tab" (already mcp-prefixed using OUR namespace key)
280
313
  *
281
- * This function strips the prefix and maps back using the mcpServers
282
- * registry โ€” the SAME source that defines which tools exist.
283
- *
284
- * Works for both remote HTTP MCP and legacy stdio MCP (same naming convention).
314
+ * This function strips whichever prefix is present and maps the bare tool
315
+ * name back using the `mcpServers` registry โ€” the SAME source of truth that
316
+ * defines which tools exist.
285
317
  *
286
318
  * Returns null if the tool name is not one of our custom MCP tools.
287
319
  */
288
320
  export function resolveOpenCodeToolName(toolName: string): string | null {
289
- // Already in our format
290
- if (toolName.startsWith('mcp__')) return toolName;
291
-
292
- // Strip Open Code MCP server prefix if present
293
- // Open Code prefixes with the server config key: "clopen-mcp_<tool>"
321
+ // Strip the remote-MCP server prefix if present. Both `_` and `-` are
322
+ // observed in the wild depending on the engine's SDK; Qwen prepends the
323
+ // full `mcp__<namespace>__` form so the bare tool name still needs to be
324
+ // re-resolved against the registry to land on the correct server alias
325
+ // (`mcp__browser-automation__open_new_tab`, not `mcp__clopen-mcp__...`).
294
326
  let rawName = toolName;
295
- const ocPrefix = 'clopen-mcp_';
296
- if (rawName.startsWith(ocPrefix)) {
297
- rawName = rawName.slice(ocPrefix.length);
327
+ let strippedNamespace = false;
328
+ for (const prefix of ['mcp__clopen-mcp__', 'clopen-mcp_', 'clopen-mcp-']) {
329
+ if (rawName.startsWith(prefix)) {
330
+ rawName = rawName.slice(prefix.length);
331
+ strippedNamespace = true;
332
+ break;
333
+ }
298
334
  }
299
335
 
336
+ // Already in our canonical format and not the legacy double-prefixed
337
+ // `mcp__clopen-mcp__<tool>` shape โ€” pass through unchanged.
338
+ if (!strippedNamespace && rawName.startsWith('mcp__')) return rawName;
339
+
300
340
  // Look up which server owns this tool
301
341
  for (const [serverName, serverConfig] of Object.entries(mcpServers)) {
302
342
  if (!serverConfig.enabled) continue;
@@ -340,3 +380,164 @@ export function getOpenCodeMcpConfig(): Record<string, McpRemoteConfig> {
340
380
  },
341
381
  };
342
382
  }
383
+
384
+ // ============================================================================
385
+ // Codex MCP Configuration
386
+ // ============================================================================
387
+
388
+ /**
389
+ * Per-MCP-server config shape consumed by the Codex CLI.
390
+ *
391
+ * Mirrors the subset of `RawMcpServerConfig` we actually emit. The SDK
392
+ * flattens this object to `--config mcp_servers.<server>.<key>=<value>` flags
393
+ * on every `codex exec` invocation.
394
+ */
395
+ type CodexMcpServerConfig = {
396
+ url: string;
397
+ tools?: Record<string, { approval_mode: 'auto' | 'prompt' | 'approve' }>;
398
+ };
399
+
400
+ /**
401
+ * Get MCP configuration for Codex engine.
402
+ *
403
+ * Codex's CLI accepts an `mcp_servers.<name>.url` config that points at any
404
+ * Streamable HTTP MCP endpoint. We reuse the SAME `/mcp` URL Open Code
405
+ * already consumes โ€” no new HTTP server, no per-engine bridge. Tool handlers
406
+ * execute in-process in the Clopen backend.
407
+ *
408
+ * Approval: in non-interactive `codex exec` mode there is no UI to approve
409
+ * MCP tool calls, so the CLI auto-cancels them with
410
+ * "Error: user cancelled MCP tool call". Codex has no top-level
411
+ * "auto-approve all MCP" switch โ€” it only exposes per-tool
412
+ * `mcp_servers.<name>.tools.<tool>.approval_mode`. We enumerate every
413
+ * enabled tool here and set `approval_mode = "approve"` so the subprocess
414
+ * runs them without asking. Open Code achieves the same outcome by replying
415
+ * to permission events at runtime โ€” Codex requires the decision up-front.
416
+ *
417
+ * The shape returned here is flattened by the Codex SDK into
418
+ * `--config mcp_servers.clopen-mcp.<dotted-key>=<value>` flags when the SDK
419
+ * invokes the CLI subprocess for each turn.
420
+ */
421
+ export function getCodexMcpConfig(): Record<string, CodexMcpServerConfig> {
422
+ const enabledServers = getEnabledServerNames();
423
+ if (enabledServers.length === 0) {
424
+ return {};
425
+ }
426
+
427
+ const port = SERVER_ENV.PORT;
428
+
429
+ const tools: Record<string, { approval_mode: 'approve' }> = {};
430
+ for (const serverName of enabledServers) {
431
+ const serverConfig = mcpServers[serverName];
432
+ for (const toolName of serverConfig.tools as readonly string[]) {
433
+ tools[toolName] = { approval_mode: 'approve' };
434
+ }
435
+ }
436
+
437
+ debug.log('mcp', `๐Ÿ“ฆ Codex MCP: remote server at http://localhost:${port}/mcp (auto-approving ${Object.keys(tools).length} tools)`);
438
+
439
+ return {
440
+ 'clopen-mcp': {
441
+ url: `http://localhost:${port}/mcp`,
442
+ tools,
443
+ },
444
+ };
445
+ }
446
+
447
+ // ============================================================================
448
+ // Copilot MCP Configuration
449
+ // ============================================================================
450
+
451
+ /**
452
+ * Get MCP configuration for the Copilot engine.
453
+ *
454
+ * The Copilot SDK accepts a `mcpServers` map on both `SessionConfig` and
455
+ * `ResumeSessionConfig` and supports the streamable-HTTP transport directly
456
+ * (`MCPHTTPServerConfig` with `type: 'http'`). We reuse the SAME `/mcp` URL
457
+ * Open Code and Codex already consume โ€” no new HTTP server, no per-engine
458
+ * bridge. Tool handlers execute in-process in the Clopen backend.
459
+ *
460
+ * Approval: Copilot already auto-approves every tool call via
461
+ * `onPermissionRequest: approveAll` in `copilot/stream.ts`, which covers MCP
462
+ * tools too. No per-tool approval enumeration is required (unlike Codex).
463
+ *
464
+ * The `tools` field lists the bare tool names exposed by our remote MCP
465
+ * server. The SDK delivers tool calls back with `mcpServerName: 'clopen-mcp'`
466
+ * + the bare tool name; `mapCopilotToolName()` then routes them through
467
+ * `resolveOpenCodeToolName()` to recover the canonical
468
+ * `mcp__<server>__<tool>` form.
469
+ */
470
+ export function getCopilotMcpConfig(): Record<string, MCPHTTPServerConfig> {
471
+ const enabledServers = getEnabledServerNames();
472
+ if (enabledServers.length === 0) {
473
+ return {};
474
+ }
475
+
476
+ const port = SERVER_ENV.PORT;
477
+
478
+ const tools: string[] = [];
479
+ for (const serverName of enabledServers) {
480
+ const serverConfig = mcpServers[serverName];
481
+ for (const toolName of serverConfig.tools as readonly string[]) {
482
+ tools.push(toolName);
483
+ }
484
+ }
485
+
486
+ debug.log('mcp', `๐Ÿ“ฆ Copilot MCP: remote server at http://localhost:${port}/mcp (${tools.length} tools)`);
487
+
488
+ return {
489
+ 'clopen-mcp': {
490
+ type: 'http',
491
+ url: `http://localhost:${port}/mcp`,
492
+ tools,
493
+ timeout: 10_000,
494
+ },
495
+ };
496
+ }
497
+
498
+ // ============================================================================
499
+ // Qwen Code MCP Configuration
500
+ // ============================================================================
501
+
502
+ /**
503
+ * Get MCP configuration for the Qwen Code engine.
504
+ *
505
+ * The Qwen Code SDK / CLI accepts a `mcpServers` map keyed by server name with
506
+ * a `CLIMcpServerConfig` value that supports the Streamable-HTTP transport via
507
+ * `httpUrl`. We reuse the SAME `/mcp` URL Open Code, Codex and Copilot already
508
+ * consume โ€” no new HTTP server, no per-engine bridge. Tool handlers run
509
+ * in-process in the Clopen backend (README ยง9.12).
510
+ *
511
+ * Approval: the Qwen adapter uses `permissionMode: 'default'` with a
512
+ * `canUseTool` callback that auto-allows everything. `AskUserQuestion` is
513
+ * blocked at the SDK level via `excludeTools` (highest permission priority),
514
+ * so the model never sees it. The callback covers MCP tool calls too โ€” no
515
+ * per-tool enumeration needed.
516
+ */
517
+ export function getQwenMcpConfig(): Record<string, QwenMcpServerConfig> {
518
+ const enabledServers = getEnabledServerNames();
519
+ if (enabledServers.length === 0) {
520
+ return {};
521
+ }
522
+
523
+ const port = SERVER_ENV.PORT;
524
+
525
+ const includeTools: string[] = [];
526
+ for (const serverName of enabledServers) {
527
+ const serverConfig = mcpServers[serverName];
528
+ for (const toolName of serverConfig.tools as readonly string[]) {
529
+ includeTools.push(toolName);
530
+ }
531
+ }
532
+
533
+ debug.log('mcp', `๐Ÿ“ฆ Qwen MCP: remote server at http://localhost:${port}/mcp (${includeTools.length} tools)`);
534
+
535
+ return {
536
+ 'clopen-mcp': {
537
+ httpUrl: `http://localhost:${port}/mcp`,
538
+ includeTools,
539
+ timeout: 10_000,
540
+ trust: true,
541
+ },
542
+ };
543
+ }
@@ -31,6 +31,8 @@ export {
31
31
  getEnabledToolsForServer,
32
32
  getMcpStats,
33
33
  getOpenCodeMcpConfig,
34
+ getCodexMcpConfig,
35
+ getCopilotMcpConfig,
34
36
  resolveOpenCodeToolName
35
37
  } from './config';
36
38
 
@@ -38,6 +38,16 @@ class ProjectContextService {
38
38
  // Track the most recently used projectId (as a last resort fallback)
39
39
  private lastUsedProjectId: string | null = null;
40
40
 
41
+ /**
42
+ * Per-stream AbortSignal map. The stream-manager registers each stream's
43
+ * AbortController.signal here when the stream starts so MCP tool handlers
44
+ * 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".
48
+ */
49
+ private streamSignals = new Map<string, AbortSignal>();
50
+
41
51
  /**
42
52
  * Register a chat session with its project ID
43
53
  * Should be called when a chat stream starts
@@ -109,12 +119,56 @@ class ProjectContextService {
109
119
  debug.log('mcp', `๐Ÿ—‘๏ธ Unregistered session ${chatSessionId}`);
110
120
  }
111
121
 
122
+ /**
123
+ * Register an AbortSignal for a stream. MCP tool handlers can read this
124
+ * via `getCurrentSignal()` to short-circuit when the engine is cancelled
125
+ * โ€” without it, in-flight browser-automation calls keep running for a
126
+ * second or two after the user interrupts the chat (visible as the
127
+ * "preview keeps moving by itself" symptom).
128
+ */
129
+ registerStreamSignal(streamId: string, signal: AbortSignal): void {
130
+ if (!streamId) return;
131
+ this.streamSignals.set(streamId, signal);
132
+ }
133
+
134
+ /**
135
+ * Resolve the AbortSignal that belongs to the currently-executing MCP
136
+ * tool invocation. Tries (in order):
137
+ * 1. AsyncLocalStorage context's `streamId` (Claude in-process path).
138
+ * 2. AsyncLocalStorage context's `chatSessionId` mapped to its stream.
139
+ * 3. The most recent active stream (fallback for the remote HTTP MCP
140
+ * path โ€” OpenCode/Codex/Copilot/Qwen โ€” where context doesn't carry).
141
+ *
142
+ * Returns `undefined` when no stream is in-flight; handlers should treat
143
+ * absence as "not abortable" rather than as "aborted".
144
+ */
145
+ getCurrentSignal(): AbortSignal | undefined {
146
+ const context = this.getCurrentContext();
147
+ if (context?.streamId) {
148
+ const signal = this.streamSignals.get(context.streamId);
149
+ if (signal) return signal;
150
+ }
151
+ if (context?.chatSessionId) {
152
+ for (const [streamId, info] of this.activeStreams) {
153
+ if (info.chatSessionId === context.chatSessionId) {
154
+ const signal = this.streamSignals.get(streamId);
155
+ if (signal) return signal;
156
+ }
157
+ }
158
+ }
159
+ if (this.mostRecentActiveStream) {
160
+ return this.streamSignals.get(this.mostRecentActiveStream.streamId);
161
+ }
162
+ return undefined;
163
+ }
164
+
112
165
  /**
113
166
  * Unregister a stream (cleanup)
114
167
  */
115
168
  unregisterStream(streamId: string): void {
116
169
  this.streamProjectMap.delete(streamId);
117
170
  this.activeStreams.delete(streamId);
171
+ this.streamSignals.delete(streamId);
118
172
 
119
173
  // Clear most recent if it was this stream
120
174
  if (this.mostRecentActiveStream?.streamId === streamId) {
@@ -158,6 +212,7 @@ class ProjectContextService {
158
212
  clear(): void {
159
213
  this.sessionProjectMap.clear();
160
214
  this.streamProjectMap.clear();
215
+ this.streamSignals.clear();
161
216
  this.lastUsedProjectId = null;
162
217
  debug.log('mcp', '๐Ÿงน Cleared all project context mappings');
163
218
  }
@@ -114,7 +114,12 @@ export async function actionsHandler(args: {
114
114
 
115
115
  // Note: Cursor events are emitted by performAutonomousActions internally
116
116
  // with proper delays between each action. No need to emit here.
117
- const results = await previewService.performAutonomousActions(sessionId, processedActions);
117
+ // Pass the chat stream's AbortSignal so the action loop breaks the
118
+ // moment the user clicks interrupt โ€” without this, multi-step click
119
+ // sequences keep firing for a few seconds after the engine subprocess
120
+ // dies (the "preview keeps moving by itself" symptom).
121
+ const abortSignal = projectContextService.getCurrentSignal();
122
+ const results = await previewService.performAutonomousActions(sessionId, processedActions, abortSignal);
118
123
 
119
124
  // Format response with extracted data if any
120
125
  const extractedData = results?.filter((r: any) => r.action === 'extract_data') || [];
@@ -12,6 +12,7 @@
12
12
  import { createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk";
13
13
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
14
14
  import type { z } from "zod";
15
+ import { projectContextService } from '../project-context';
15
16
 
16
17
  /**
17
18
  * Infer argument types from Zod schema
@@ -191,6 +192,18 @@ export function createRemoteMcpServer(
191
192
  description: def.description,
192
193
  inputSchema: def.schema,
193
194
  }, async (args: Record<string, unknown>) => {
195
+ // Fast-fail when the owning chat stream has already been
196
+ // cancelled โ€” the handler never runs. Without this, the
197
+ // engine subprocess dies on cancel but in-flight HTTP-MCP
198
+ // tool calls continue to drive puppeteer ops, surfacing as
199
+ // "preview keeps moving by itself" after interrupt.
200
+ const signal = projectContextService.getCurrentSignal();
201
+ if (signal?.aborted) {
202
+ return {
203
+ content: [{ type: 'text' as const, text: `Tool ${String(toolName)} was cancelled because the chat stream was interrupted.` }],
204
+ isError: true,
205
+ } as any;
206
+ }
194
207
  return await def.handler(args) as any;
195
208
  });
196
209
  }
@@ -6,12 +6,20 @@ import { SERVER_ENV } from '../utils/env';
6
6
  * Catches all errors and returns consistent error responses
7
7
  */
8
8
  export function errorHandlerMiddleware(app: Elysia) {
9
- return app.onError(({ code, error, set }) => {
10
- console.error('[Error]', code, error);
9
+ return app.onError(({ code, error, set, request }) => {
10
+ // Build a single-line request descriptor so 404s/etc. can be traced
11
+ // back to the offending URL without dumping the full Error stack
12
+ // (which previously logged just "NOT_FOUND" with no path info).
13
+ let reqInfo = '';
14
+ try {
15
+ const url = new URL(request.url);
16
+ reqInfo = `${request.method} ${url.pathname}${url.search}`;
17
+ } catch { /* request.url unavailable */ }
11
18
 
12
19
  // Handle different error types
13
20
  switch (code) {
14
21
  case 'VALIDATION':
22
+ console.error('[Error]', code, reqInfo, error.message);
15
23
  set.status = 400;
16
24
  return {
17
25
  success: false,
@@ -20,6 +28,10 @@ export function errorHandlerMiddleware(app: Elysia) {
20
28
  };
21
29
 
22
30
  case 'NOT_FOUND':
31
+ // 404s are common in dev (probes, hot-reload pings, deep-link
32
+ // refreshes). Log the path at warn level instead of dumping
33
+ // the full Error stack on every miss.
34
+ console.warn('[404]', reqInfo || '(unknown path)');
23
35
  set.status = 404;
24
36
  return {
25
37
  success: false,
@@ -28,6 +40,7 @@ export function errorHandlerMiddleware(app: Elysia) {
28
40
  };
29
41
 
30
42
  case 'PARSE':
43
+ console.error('[Error]', code, reqInfo);
31
44
  set.status = 400;
32
45
  return {
33
46
  success: false,
@@ -36,6 +49,7 @@ export function errorHandlerMiddleware(app: Elysia) {
36
49
  };
37
50
 
38
51
  default:
52
+ console.error('[Error]', code, reqInfo, error);
39
53
  set.status = 500;
40
54
  return {
41
55
  success: false,
@@ -479,7 +479,7 @@ export class BrowserPreviewService extends EventEmitter {
479
479
  // ============================================================================
480
480
  // Interaction & Autonomous Actions Methods
481
481
  // ============================================================================
482
- async performAutonomousActions(tabId: string, actions: BrowserAutonomousAction[]) {
482
+ async performAutonomousActions(tabId: string, actions: BrowserAutonomousAction[], abortSignal?: AbortSignal) {
483
483
  const tab = this.getTab(tabId);
484
484
  if (!tab) throw new Error('Tab not found or invalid');
485
485
 
@@ -487,7 +487,7 @@ export class BrowserPreviewService extends EventEmitter {
487
487
  tabId,
488
488
  tab,
489
489
  actions,
490
- () => this.isValidTab(tabId)
490
+ () => this.isValidTab(tabId) && !(abortSignal?.aborted ?? false)
491
491
  );
492
492
 
493
493
  return results;
@@ -497,12 +497,12 @@ export class BrowserPreviewService extends EventEmitter {
497
497
  * Perform autonomous actions using tab object directly
498
498
  * More efficient when tab is already available
499
499
  */
500
- async performAutonomousActionsWithTab(tab: BrowserTab, actions: BrowserAutonomousAction[]) {
500
+ async performAutonomousActionsWithTab(tab: BrowserTab, actions: BrowserAutonomousAction[], abortSignal?: AbortSignal) {
501
501
  const results = await this.interactionHandler.performAutonomousActions(
502
502
  tab.id,
503
503
  tab,
504
504
  actions,
505
- () => this.isValidTab(tab.id)
505
+ () => this.isValidTab(tab.id) && !(abortSignal?.aborted ?? false)
506
506
  );
507
507
 
508
508
  return results;