@myrialabs/clopen 0.4.5 → 0.4.7

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 (58) hide show
  1. package/backend/auth/permissions.ts +14 -1
  2. package/backend/auth/session-invalidation.test.ts +17 -21
  3. package/backend/auth/session-invalidation.ts +10 -11
  4. package/backend/database/migrations/044_create_skills_table.ts +29 -0
  5. package/backend/database/migrations/index.ts +7 -0
  6. package/backend/database/queries/index.ts +3 -1
  7. package/backend/database/queries/skill-queries.ts +105 -0
  8. package/backend/engine/adapters/claude/models.ts +46 -3
  9. package/backend/engine/adapters/claude/stream.ts +5 -0
  10. package/backend/engine/adapters/codex/credential.ts +114 -13
  11. package/backend/engine/adapters/codex/stream.ts +34 -8
  12. package/backend/engine/adapters/copilot/stream.ts +4 -0
  13. package/backend/engine/adapters/opencode/stream.ts +4 -0
  14. package/backend/engine/adapters/qwen/stream.ts +3 -0
  15. package/backend/engine/docs/lessons-learned.md +54 -50
  16. package/backend/files/file-archive.test.ts +86 -26
  17. package/backend/files/file-archive.ts +214 -134
  18. package/backend/index.ts +10 -1
  19. package/backend/mcp/README.md +77 -24
  20. package/backend/mcp/external/config.ts +82 -101
  21. package/backend/mcp/external/proxy.ts +202 -0
  22. package/backend/mcp/index.ts +4 -3
  23. package/backend/mcp/internal/remote-server.ts +103 -55
  24. package/backend/skills/index.ts +21 -0
  25. package/backend/skills/marketplace.ts +172 -0
  26. package/backend/skills/service.ts +245 -0
  27. package/backend/skills/spec.ts +214 -0
  28. package/backend/skills/store.ts +99 -0
  29. package/backend/skills/sync.ts +187 -0
  30. package/backend/terminal/index.ts +2 -5
  31. package/backend/terminal/ptykit.ts +64 -0
  32. package/backend/tunnel/tunnel-config.ts +1 -1
  33. package/backend/utils/ws.ts +14 -0
  34. package/backend/ws/files/write.ts +23 -7
  35. package/backend/ws/index.ts +5 -1
  36. package/backend/ws/projects/crud.ts +4 -4
  37. package/backend/ws/skills/catalog.ts +79 -0
  38. package/backend/ws/skills/crud.ts +123 -0
  39. package/backend/ws/skills/index.ts +15 -0
  40. package/backend/ws/system/operations.ts +23 -0
  41. package/backend/ws/terminal/index.ts +6 -33
  42. package/backend/ws/terminal/tunnel.ts +76 -0
  43. package/dist/assets/index-xrB3zcfA.js +1 -0
  44. package/dist/assets/main-BXS8bjJ6.css +1 -0
  45. package/dist/assets/{main-zXKH_C5O.js → main-LBI3a0n5.js} +304 -261
  46. package/dist/index.html +2 -2
  47. package/package.json +7 -11
  48. package/shared/constants/engines.ts +4 -4
  49. package/shared/utils/logger.ts +1 -0
  50. package/backend/terminal/helpers.ts +0 -14
  51. package/backend/terminal/pty-manager.ts +0 -4
  52. package/backend/terminal/pty-session-manager.ts +0 -349
  53. package/backend/terminal/stream-manager.ts +0 -300
  54. package/backend/ws/terminal/access.ts +0 -56
  55. package/backend/ws/terminal/persistence.ts +0 -145
  56. package/backend/ws/terminal/session.ts +0 -470
  57. package/backend/ws/terminal/stream.ts +0 -82
  58. package/dist/assets/main-gNUEJAC5.css +0 -1
@@ -1,102 +1,165 @@
1
- import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
1
+ import { isAbsolute, join, relative, sep } from 'node:path';
2
2
  import { mkdir, readdir, stat, writeFile } from 'node:fs/promises';
3
- import { zipSync, Unzip, UnzipInflate, UnzipPassThrough } from 'fflate';
3
+ import {
4
+ zip,
5
+ tar,
6
+ tarGz,
7
+ tarZstd,
8
+ sevenZip,
9
+ extractStream,
10
+ type ZipEntryInput,
11
+ type TarEntryInput,
12
+ type SevenZipEntryInput,
13
+ type ArchiveFormat
14
+ } from '@myrialabs/zipkit';
4
15
 
5
16
  import { debug } from '$shared/utils/logger';
6
17
  import { getMaxFileSize, validateFileSize } from './file-size-limit';
7
18
 
8
- interface ZipTree {
9
- [path: string]: Uint8Array | ZipTree;
19
+ /** Container formats Clopen can produce. */
20
+ export type ArchiveKind = 'zip' | 'tar' | 'tar.gz' | 'tar.zst' | '7z';
21
+
22
+ /** Options for {@link createArchiveOperation}. */
23
+ export interface CreateArchiveOptions {
24
+ /** Container format (default `'zip'`). */
25
+ format?: ArchiveKind;
26
+ /** ZIP compression method (default `'deflate'`). Ignored by tar/7z. */
27
+ method?: 'store' | 'deflate' | 'zstd';
28
+ /** Compression level (codec-specific; left to the codec default when omitted). */
29
+ level?: number;
30
+ /** Encrypt the archive with WinZip AES-256. ZIP only. */
31
+ password?: string;
10
32
  }
11
33
 
12
- function setInTree(tree: ZipTree, parts: string[], value: Uint8Array | ZipTree): void {
13
- if (parts.length === 0) return;
14
- if (parts.length === 1) {
15
- tree[parts[0]] = value;
16
- return;
17
- }
18
- const head = parts[0];
19
- const existing = tree[head];
20
- const child: ZipTree = existing && !(existing instanceof Uint8Array)
21
- ? (existing as ZipTree)
22
- : {};
23
- tree[head] = child;
24
- setInTree(child, parts.slice(1), value);
34
+ interface FlatFile {
35
+ name: string;
36
+ data: Uint8Array;
37
+ mode: number;
38
+ }
39
+
40
+ interface FlatDir {
41
+ name: string;
42
+ mode: number;
25
43
  }
26
44
 
27
- async function readPathIntoTree(sourcePath: string, rootName: string, tree: ZipTree): Promise<void> {
45
+ /** Recursively collect files (and empty directories) under `sourcePath`. */
46
+ async function collectEntries(sourcePath: string, rootName: string, files: FlatFile[], emptyDirs: FlatDir[]): Promise<void> {
28
47
  const stats = await stat(sourcePath);
29
48
  if (stats.isFile()) {
30
49
  const data = new Uint8Array(await Bun.file(sourcePath).arrayBuffer());
31
- setInTree(tree, rootName.split('/'), data);
50
+ files.push({ name: rootName, data, mode: stats.mode & 0o777 });
32
51
  return;
33
52
  }
34
53
  if (stats.isDirectory()) {
35
54
  const entries = await readdir(sourcePath);
36
55
  if (entries.length === 0) {
37
- setInTree(tree, rootName.split('/'), {} as ZipTree);
56
+ emptyDirs.push({ name: `${rootName}/`, mode: stats.mode & 0o777 });
38
57
  return;
39
58
  }
40
59
  for (const entry of entries) {
41
- await readPathIntoTree(
42
- join(sourcePath, entry),
43
- `${rootName}/${entry}`,
44
- tree
45
- );
60
+ await collectEntries(join(sourcePath, entry), `${rootName}/${entry}`, files, emptyDirs);
46
61
  }
47
62
  }
48
63
  }
49
64
 
50
- export async function createZipOperation(sourcePaths: string[], targetZipPath: string): Promise<{ message: string; path: string; size: number; modified: string }> {
65
+ /** Build the archive bytes for the requested container from collected entries. */
66
+ async function buildArchive(
67
+ format: ArchiveKind,
68
+ files: FlatFile[],
69
+ emptyDirs: FlatDir[],
70
+ opts: CreateArchiveOptions
71
+ ): Promise<Uint8Array> {
72
+ if (opts.password && format !== 'zip') {
73
+ throw new Error('Password protection is only supported for ZIP archives');
74
+ }
75
+
76
+ if (format === 'zip') {
77
+ const method = opts.method ?? 'deflate';
78
+ const entries: ZipEntryInput[] = [
79
+ ...files.map((f) => ({ name: f.name, data: f.data, method, level: opts.level, unixPermissions: f.mode })),
80
+ ...emptyDirs.map((d) => ({ name: d.name, data: new Uint8Array(0), unixPermissions: d.mode }))
81
+ ];
82
+ return zip(entries, opts.password ? { password: opts.password } : {});
83
+ }
84
+
85
+ if (format === '7z') {
86
+ // 7z entries are files only; empty directories aren't represented.
87
+ const entries: SevenZipEntryInput[] = files.map((f) => ({
88
+ name: f.name,
89
+ data: f.data,
90
+ method: opts.method === 'store' ? 'copy' : 'lzma',
91
+ level: opts.level
92
+ }));
93
+ return sevenZip(entries);
94
+ }
95
+
96
+ // tar family
97
+ const entries: TarEntryInput[] = [
98
+ ...files.map((f) => ({ name: f.name, data: f.data, mode: f.mode })),
99
+ ...emptyDirs.map((d) => ({ name: d.name, type: 'directory' as const, mode: d.mode }))
100
+ ];
101
+ if (format === 'tar') return tar(entries);
102
+ if (format === 'tar.gz') return tarGz(entries, opts.level !== undefined ? { level: opts.level } : undefined);
103
+ return tarZstd(entries, opts.level !== undefined ? { level: opts.level } : undefined);
104
+ }
105
+
106
+ /**
107
+ * Compress a set of files/directories into a single archive. Supports ZIP
108
+ * (store/deflate/zstd, optional AES-256), tar/`.tar.gz`/`.tar.zst`, and 7z.
109
+ */
110
+ export async function createArchiveOperation(
111
+ sourcePaths: string[],
112
+ targetPath: string,
113
+ opts: CreateArchiveOptions = {}
114
+ ): Promise<{ message: string; path: string; size: number; modified: string }> {
51
115
  if (!Array.isArray(sourcePaths) || sourcePaths.length === 0) {
52
116
  throw new Error('At least one source path is required');
53
117
  }
54
- if (!targetZipPath) {
55
- throw new Error('Target zip path is required');
118
+ if (!targetPath) {
119
+ throw new Error('Target archive path is required');
56
120
  }
57
121
 
122
+ const format = opts.format ?? 'zip';
123
+
58
124
  try {
59
- const targetFile = Bun.file(targetZipPath);
125
+ const targetFile = Bun.file(targetPath);
60
126
  if (await targetFile.exists()) {
61
127
  throw new Error('Target archive already exists');
62
128
  }
63
129
 
64
- const tree: ZipTree = {};
65
-
130
+ const files: FlatFile[] = [];
131
+ const emptyDirs: FlatDir[] = [];
66
132
  for (const source of sourcePaths) {
67
- const name = basename(source);
133
+ const name = source.split(sep).pop() ?? '';
68
134
  if (!name || name === '.' || name === '..') {
69
135
  throw new Error(`Invalid source path: ${source}`);
70
136
  }
71
- await readPathIntoTree(source, name, tree);
137
+ await collectEntries(source, name, files, emptyDirs);
72
138
  }
73
139
 
74
- const zipped = zipSync(tree as Record<string, Uint8Array>, { level: 6 });
75
- validateFileSize(zipped.byteLength);
76
- await Bun.write(targetZipPath, zipped);
77
- const stats = await stat(targetZipPath);
140
+ const archive = await buildArchive(format, files, emptyDirs, opts);
141
+ validateFileSize(archive.byteLength);
142
+ await Bun.write(targetPath, archive);
143
+ const stats = await stat(targetPath);
78
144
 
79
145
  return {
80
146
  message: 'Archive created successfully',
81
- path: targetZipPath,
147
+ path: targetPath,
82
148
  size: stats.size,
83
149
  modified: stats.mtime.toISOString()
84
150
  };
85
151
  } catch (error) {
86
- debug.error('file', 'Create zip error:', error);
152
+ debug.error('file', 'Create archive error:', error);
87
153
  if (error instanceof Error) {
88
- if (error.message.includes('EPERM')) {
89
- throw new Error('Permission denied while creating archive');
90
- }
91
- if (error.message.includes('ENOSPC')) {
92
- throw new Error('Not enough space on disk');
93
- }
154
+ if (error.message.includes('EPERM')) throw new Error('Permission denied while creating archive');
155
+ if (error.message.includes('ENOSPC')) throw new Error('Not enough space on disk');
94
156
  throw error;
95
157
  }
96
158
  throw new Error('Failed to create archive');
97
159
  }
98
160
  }
99
161
 
162
+ /** Reject entry paths that are absolute or escape the extraction root. */
100
163
  function isSafeEntryPath(entryPath: string, targetRoot: string): boolean {
101
164
  if (!entryPath) return false;
102
165
  if (isAbsolute(entryPath)) return false;
@@ -107,18 +170,54 @@ function isSafeEntryPath(entryPath: string, targetRoot: string): boolean {
107
170
  return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
108
171
  }
109
172
 
110
- export async function extractZipOperation(archivePath: string, targetDir: string): Promise<{ message: string; path: string; entries: number; modified: string }> {
111
- if (!archivePath) {
112
- throw new Error('Archive path is required');
113
- }
114
- if (!targetDir) {
115
- throw new Error('Target directory is required');
173
+ /** Map a filename to a ZipKit container format; `undefined` → auto-detect. */
174
+ function formatFromPath(archivePath: string): ArchiveFormat | undefined {
175
+ const n = archivePath.toLowerCase();
176
+ if (n.endsWith('.tar.gz') || n.endsWith('.tgz')) return 'tar.gz';
177
+ if (n.endsWith('.tar.zst') || n.endsWith('.tzst')) return 'tar.zst';
178
+ if (n.endsWith('.tar.xz') || n.endsWith('.txz')) return 'tar.xz';
179
+ if (n.endsWith('.tar.bz2') || n.endsWith('.tbz2')) return 'tar.bz2';
180
+ if (n.endsWith('.tar')) return 'tar';
181
+ if (n.endsWith('.zip')) return 'zip';
182
+ if (n.endsWith('.7z')) return '7z';
183
+ // Lone-stream / ambiguous extensions: let extractStream sniff the magic bytes.
184
+ return undefined;
185
+ }
186
+
187
+ function concatChunks(chunks: Uint8Array[], total: number): Uint8Array {
188
+ const out = new Uint8Array(total);
189
+ let pos = 0;
190
+ for (const chunk of chunks) {
191
+ out.set(chunk, pos);
192
+ pos += chunk.length;
116
193
  }
194
+ return out;
195
+ }
196
+
197
+ async function writeEntry(fullPath: string, chunks: Uint8Array[], total: number): Promise<void> {
198
+ await mkdir(join(fullPath, '..'), { recursive: true });
199
+ await writeFile(fullPath, concatChunks(chunks, total));
200
+ }
201
+
202
+ /**
203
+ * Extract an archive into `targetDir`. Auto-detects the container (ZIP, tar,
204
+ * `.tar.gz`/`.tar.zst`, 7z, …) from the filename or magic bytes and streams via
205
+ * ZipKit's {@link extractStream}, which caps the running total of *actually
206
+ * decompressed* bytes at the configured file-size limit — so a crafted archive
207
+ * that forges its uncompressed-size fields still can't blow past the cap. Each
208
+ * entry is path-checked before it touches disk; symlinks are skipped to avoid
209
+ * symlink-escape writes.
210
+ */
211
+ export async function extractArchiveOperation(
212
+ archivePath: string,
213
+ targetDir: string,
214
+ password?: string
215
+ ): Promise<{ message: string; path: string; entries: number; modified: string }> {
216
+ if (!archivePath) throw new Error('Archive path is required');
217
+ if (!targetDir) throw new Error('Target directory is required');
117
218
 
118
219
  const archiveFile = Bun.file(archivePath);
119
- if (!(await archiveFile.exists())) {
120
- throw new Error('Archive does not exist');
121
- }
220
+ if (!(await archiveFile.exists())) throw new Error('Archive does not exist');
122
221
 
123
222
  const limit = getMaxFileSize();
124
223
  const limitMB = Math.floor(limit / (1024 * 1024));
@@ -131,16 +230,18 @@ export async function extractZipOperation(archivePath: string, targetDir: string
131
230
  const targetExists = await Bun.file(targetDir).exists();
132
231
  if (targetExists) {
133
232
  const targetStats = await stat(targetDir);
134
- if (!targetStats.isDirectory()) {
135
- throw new Error('Target path exists and is not a directory');
136
- }
137
- } else {
138
- await mkdir(targetDir, { recursive: true });
233
+ if (!targetStats.isDirectory()) throw new Error('Target path exists and is not a directory');
139
234
  }
235
+ // The target directory is created lazily, only as entries are written, so a
236
+ // failed extraction — e.g. an encrypted archive before its password is
237
+ // entered, or an incorrect one — never leaves an empty folder behind.
140
238
 
141
239
  const data = new Uint8Array(await archiveFile.arrayBuffer());
142
- const entryCount = await extractWithinLimit(data, targetDir, limit, limitMB);
240
+ const entryCount = await extractWithinLimit(data, archivePath, targetDir, limit, limitMB, password);
143
241
 
242
+ // Ensure the directory exists even for an archive that yielded no file
243
+ // entries, so the stat below has something to read.
244
+ await mkdir(targetDir, { recursive: true });
144
245
  const targetStats = await stat(targetDir);
145
246
  return {
146
247
  message: 'Archive extracted successfully',
@@ -149,104 +250,83 @@ export async function extractZipOperation(archivePath: string, targetDir: string
149
250
  modified: targetStats.mtime.toISOString()
150
251
  };
151
252
  } catch (error) {
152
- debug.error('file', 'Extract zip error:', error);
253
+ debug.error('file', 'Extract archive error:', error);
153
254
  if (error instanceof Error) {
154
- if (error.message.includes('EPERM')) {
155
- throw new Error('Permission denied while extracting archive');
156
- }
157
- if (error.message.includes('ENOSPC')) {
158
- throw new Error('Not enough space on disk');
255
+ // Translate ZipKit's technical encryption errors into a clean message the
256
+ // UI can detect to prompt for (or re-prompt) a password.
257
+ if (/encrypted|wrong password|bad password|decrypt/i.test(error.message)) {
258
+ throw new Error(password ? 'Incorrect password for this archive' : 'This archive is password-protected');
159
259
  }
260
+ if (error.message.includes('EPERM')) throw new Error('Permission denied while extracting archive');
261
+ if (error.message.includes('ENOSPC')) throw new Error('Not enough space on disk');
160
262
  throw error;
161
263
  }
162
264
  throw new Error('Failed to extract archive');
163
265
  }
164
266
  }
165
267
 
166
- const STREAM_CHUNK_SIZE = 64 * 1024;
167
-
168
- function concatChunks(chunks: Uint8Array[], total: number): Uint8Array {
169
- const out = new Uint8Array(total);
170
- let pos = 0;
171
- for (const chunk of chunks) {
172
- out.set(chunk, pos);
173
- pos += chunk.length;
174
- }
175
- return out;
176
- }
177
-
178
- async function writeEntry(fullPath: string, content: Uint8Array): Promise<void> {
179
- await mkdir(dirname(fullPath), { recursive: true });
180
- await writeFile(fullPath, content);
181
- }
182
-
183
268
  /**
184
- * Stream-extract a ZIP, aborting as soon as the running total of *actual*
185
- * decompressed bytes exceeds the limit. Feeding the compressed data in small
186
- * chunks bounds how much a single decode step can emit, so a crafted archive
187
- * cannot allocate more than the limit before being rejected — unlike trusting
188
- * the uncompressed-size fields in the central directory, which an attacker
189
- * controls and can forge to defeat a pre-decompression size check.
269
+ * Stream-extract an archive, translating ZipKit's cap error into Clopen's
270
+ * user-facing size-limit message. `maxTotalBytes` bounds actual decompressed
271
+ * output, so a zip bomb (or one that forges its metadata) is rejected before it
272
+ * can allocate past the limit.
190
273
  */
191
274
  async function extractWithinLimit(
192
275
  data: Uint8Array,
276
+ archivePath: string,
193
277
  targetDir: string,
194
278
  limit: number,
195
- limitMB: number
279
+ limitMB: number,
280
+ password?: string
196
281
  ): Promise<number> {
197
- let totalBytes = 0;
198
282
  let entryCount = 0;
199
- let failure: Error | null = null;
200
- const writes: Promise<void>[] = [];
201
-
202
- const unzipper = new Unzip((file) => {
203
- if (failure) return;
204
-
205
- if (!isSafeEntryPath(file.name, targetDir)) {
206
- failure = new Error(`Unsafe path in archive: ${file.name}`);
207
- return;
208
- }
283
+ let currentPath: string | null = null;
284
+ let chunks: Uint8Array[] = [];
285
+ let currentTotal = 0;
209
286
 
210
- const normalized = file.name.replace(/\\/g, '/');
211
- const fullPath = join(targetDir, normalized.split('/').join(sep));
287
+ try {
288
+ for await (const { info, chunk, done } of extractStream(data, {
289
+ maxTotalBytes: limit,
290
+ format: formatFromPath(archivePath),
291
+ password
292
+ })) {
293
+ if (!isSafeEntryPath(info.name, targetDir)) {
294
+ throw new Error(`Unsafe path in archive: ${info.name}`);
295
+ }
296
+ const normalized = info.name.replace(/\\/g, '/');
297
+ const fullPath = join(targetDir, normalized.split('/').join(sep));
212
298
 
213
- if (normalized.endsWith('/')) {
214
- writes.push(mkdir(fullPath, { recursive: true }).then(() => undefined));
215
- return;
216
- }
299
+ if (info.type === 'directory') {
300
+ await mkdir(fullPath, { recursive: true });
301
+ continue;
302
+ }
303
+ // Skip symlinks: recreating them from an untrusted archive risks
304
+ // symlink-escape writes on later entries.
305
+ if (info.type === 'symlink') continue;
217
306
 
218
- const chunks: Uint8Array[] = [];
219
- let fileBytes = 0;
220
- file.ondata = (err, chunk, final) => {
221
- if (failure) return;
222
- if (err) {
223
- failure = err;
224
- return;
307
+ if (currentPath !== fullPath) {
308
+ currentPath = fullPath;
309
+ chunks = [];
310
+ currentTotal = 0;
225
311
  }
226
- totalBytes += chunk.length;
227
- if (totalBytes > limit) {
228
- failure = new Error(`Extracted content exceeds maximum allowed size of ${limitMB}MB`);
229
- return;
312
+ if (chunk.length) {
313
+ chunks.push(chunk);
314
+ currentTotal += chunk.length;
230
315
  }
231
- chunks.push(chunk);
232
- fileBytes += chunk.length;
233
- if (final) {
234
- writes.push(writeEntry(fullPath, concatChunks(chunks, fileBytes)));
316
+ if (done) {
317
+ await writeEntry(fullPath, chunks, currentTotal);
235
318
  entryCount++;
319
+ currentPath = null;
320
+ chunks = [];
321
+ currentTotal = 0;
236
322
  }
237
- };
238
- file.start();
239
- });
240
- unzipper.register(UnzipInflate);
241
- unzipper.register(UnzipPassThrough);
242
-
243
- for (let offset = 0; offset < data.length && !failure; offset += STREAM_CHUNK_SIZE) {
244
- const end = Math.min(offset + STREAM_CHUNK_SIZE, data.length);
245
- unzipper.push(data.subarray(offset, end), end >= data.length);
323
+ }
324
+ } catch (error) {
325
+ if (error instanceof Error && /maxTotalBytes|remaining cap/.test(error.message)) {
326
+ throw new Error(`Extracted content exceeds maximum allowed size of ${limitMB}MB`);
327
+ }
328
+ throw error;
246
329
  }
247
330
 
248
- if (failure) throw failure;
249
- await Promise.all(writes);
250
331
  return entryCount;
251
332
  }
252
-
package/backend/index.ts CHANGED
@@ -40,7 +40,7 @@ import { audioRoute } from './http/audio';
40
40
  import { browserPreviewServiceManager } from './preview';
41
41
 
42
42
  // MCP remote server for Open Code custom tools
43
- import { handleMcpRequest, closeMcpServer, completeAuthorization } from './mcp';
43
+ import { handleMcpRequest, handleExternalMcpRequest, closeMcpServer, completeAuthorization } from './mcp';
44
44
 
45
45
  // Auth middleware
46
46
  import { checkRouteAccess } from './auth/permissions';
@@ -109,6 +109,15 @@ const app = new Elysia()
109
109
  return handleMcpRequest(request);
110
110
  })
111
111
 
112
+ // Per-server proxy for user-installed (external) MCP servers. Clopen connects
113
+ // to the upstream third-party server and re-exposes its sanitized tools here,
114
+ // so engines never connect to it directly — see backend/mcp/external/proxy.ts.
115
+ // Same long-lived semantics as `/mcp`: disable Bun's idle timeout.
116
+ .all('/mcp/ext/:slug', async ({ request, params, server }) => {
117
+ server?.timeout(request, 0);
118
+ return handleExternalMcpRequest(request, params.slug);
119
+ })
120
+
112
121
  // Stable OAuth redirect target for centralized MCP sign-in. The browser is
113
122
  // redirected here after the user consents; we exchange the code for tokens
114
123
  // (stored against the server) and show a self-closing confirmation page. The
@@ -9,14 +9,21 @@ disk and in their namespace keys:
9
9
  | Managed | By developers (this README) | By users in **Settings → MCP** |
10
10
  | Stored | In code (`internal/servers/`) | In the DB (`mcp_servers` table) |
11
11
  | Namespace | `clopen-mcp` bridge (non-Claude) / server name (Claude) | one bare `<slug>` per server (no prefix) |
12
- | Execution | In-process (no subprocess) | Engine connects directly (stdio subprocess or remote HTTP) |
12
+ | Execution | In-process (no subprocess) | Engine connects to Clopen's `/mcp/ext/<slug>` proxy; Clopen connects to the real upstream (stdio subprocess or remote HTTP) |
13
13
 
14
14
  Both are merged behind the **facade** `backend/mcp/index.ts` — the only module
15
15
  the rest of the backend imports from (`getEnabledMcpServers()`,
16
16
  `getXxxMcpConfig()`, `resolveOpenCodeToolName()` all return the combined view).
17
17
 
18
18
  The rest of this document covers the **internal** custom-tool system. External
19
- servers need no code — see `external/registry-client.ts` and `external/config.ts`.
19
+ servers need no code — see `external/registry-client.ts`, `external/config.ts`,
20
+ and `external/proxy.ts` (the per-server `/mcp/ext/<slug>` proxy bridge).
21
+
22
+ > **External servers are proxied, not direct.** Engines never connect straight
23
+ > to a third-party MCP server. Clopen connects to it (as an MCP client) and
24
+ > re-exposes its **sanitized** tools through a per-server endpoint on the same
25
+ > Streamable-HTTP bridge the internal tools use. See
26
+ > [External Servers, OAuth & Connection Status](#external-servers-oauth--connection-status).
20
27
 
21
28
  ---
22
29
 
@@ -180,7 +187,10 @@ backend/mcp/
180
187
  ├── external/ # User-installed servers from the official registry
181
188
  │ ├── types.ts # CatalogServer / ResolvedExternalServer
182
189
  │ ├── registry-client.ts # Fetch + normalise registry.modelcontextprotocol.io
183
- │ └── config.ts # Per-engine builders (bare <slug>) + resolveExternalToolName
190
+ │ ├── proxy.ts # `/mcp/ext/<slug>` proxy: Clopen ↔ upstream, schema sanitiser
191
+ │ ├── probe.ts # Connection health probe (Settings → MCP status)
192
+ │ ├── oauth.ts # Centralized OAuth (discovery + dynamic reg + PKCE)
193
+ │ └── config.ts # Per-engine builders (bridge URL, bare <slug>) + resolveExternalToolName
184
194
  └── README.md # This file
185
195
  ```
186
196
 
@@ -1198,10 +1208,12 @@ checklist in `backend/engine/README.md` §9.12. The summary:
1198
1208
  4. Wire the engine's auto-approval path (runtime callback or static
1199
1209
  per-tool config) so MCP tool calls don't get cancelled.
1200
1210
  5. Add a sibling `getXxxExternalMcpConfig()` in
1201
- `backend/mcp/external/config.ts` for user-installed registry servers,
1202
- and **forward `headers`** so the centrally-managed OAuth bearer (and
1203
- any static API key) reaches the engine. Use the SDK's real header
1204
- field — Codex uses `http_headers`, **not** `bearer_token`. See
1211
+ `backend/mcp/external/config.ts` for user-installed registry servers.
1212
+ Every external server is proxied, so this is now a one-liner per server:
1213
+ emit the bridge URL `http://localhost:<port>/mcp/ext/<slug>` plus the
1214
+ service-token header in the SDK's shape. No stdio branch, no upstream
1215
+ credential handling (the proxy injects it). Codex still uses
1216
+ `http_headers`, **not** `bearer_token`. See
1205
1217
  [External Servers, OAuth & Connection Status](#external-servers-oauth--connection-status)
1206
1218
  and `backend/engine/docs/lessons-learned.md` §9.18.
1207
1219
 
@@ -1211,7 +1223,8 @@ checklist in `backend/engine/README.md` §9.12. The summary:
1211
1223
  |------|----------|---------|
1212
1224
  | Public facade | `backend/mcp/index.ts` | Only public entry; merges internal + external |
1213
1225
  | Tool definitions | `backend/mcp/internal/servers/` | Single source of truth (internal) |
1214
- | Remote MCP server | `backend/mcp/internal/remote-server.ts` | HTTP bridge for every non-Claude engine |
1226
+ | Remote MCP server | `backend/mcp/internal/remote-server.ts` | HTTP bridge: internal `/mcp` + external `/mcp/ext/<slug>` |
1227
+ | External proxy | `backend/mcp/external/proxy.ts` | Clopen↔upstream MCP client + schema sanitiser |
1215
1228
  | Server factory | `backend/mcp/internal/servers/helper.ts` | `createRemoteMcpServer()` |
1216
1229
  | Per-engine config (internal) | `backend/mcp/internal/config.ts` | `getOpenCodeMcpConfig()`, `getCodexMcpConfig()`, … (clopen-mcp) |
1217
1230
  | Tool name resolver | `backend/mcp/internal/config.ts` | `resolveOpenCodeToolName()` (handles every engine's prefix variant) |
@@ -1225,9 +1238,43 @@ checklist in `backend/engine/README.md` §9.12. The summary:
1225
1238
 
1226
1239
  Everything above describes **internal** custom tools (the `clopen-mcp`
1227
1240
  bridge). **External** servers are the ones a user installs from the official
1228
- registry (Settings → MCP → Browse), stored in the `mcp_servers` table. Unlike
1229
- internal tools, the engine connects to these **directly** — a stdio subprocess
1230
- or a remote third-party URL — so authentication is Clopen's responsibility.
1241
+ registry (Settings → MCP → Browse), stored in the `mcp_servers` table.
1242
+
1243
+ ### Proxied through the bridge (not direct)
1244
+
1245
+ Engines do **not** connect to a third-party MCP server directly. Each enabled
1246
+ external server gets its own endpoint `GET/POST/DELETE /mcp/ext/<slug>` on the
1247
+ same Streamable-HTTP bridge as the internal tools. Clopen connects to the real
1248
+ upstream (stdio subprocess or remote URL) as an MCP **client**, and re-exposes
1249
+ its tools there. The per-engine builders in `external/config.ts` therefore emit
1250
+ the **identical** shape for every server — a loopback bridge URL plus the
1251
+ service-token header — regardless of the upstream's real transport.
1252
+
1253
+ Why proxy (`external/proxy.ts`):
1254
+
1255
+ 1. **Schema sanitising.** The MCP SDK's `Client.listTools()` eagerly compiles an
1256
+ Ajv validator for every tool's `outputSchema`. A single unresolvable `$ref`
1257
+ (e.g. Stitch's `#/$defs/ScreenInstance`) makes it throw, and the engine CLIs'
1258
+ `discoverTools` swallow that error and surface **zero** tools — a "connected"
1259
+ server that advertises nothing. Clopen reads `tools/list` with a **raw**
1260
+ JSON-RPC request (no Ajv), **drops `outputSchema`**, and strips dangling
1261
+ `$ref`s from `inputSchema` before re-serving. One bad schema can no longer
1262
+ hide a whole server.
1263
+ 2. **One credential path.** OAuth bearer / static API key is injected once, on
1264
+ Clopen's upstream hop (`resolveServerRow`). The engine→bridge hop only
1265
+ carries the service token — so a new engine adapter needs no per-transport
1266
+ or per-credential branching.
1267
+ 3. **Uniform behaviour.** stdio and remote external servers behave identically
1268
+ on every engine (this fixed Qwen advertising no remote tools and Copilot
1269
+ advertising no external tools at all).
1270
+
1271
+ Lifecycle: the upstream client (and any stdio subprocess) is created lazily when
1272
+ an engine opens a bridge session and torn down when that session closes
1273
+ (`internal/remote-server.ts`).
1274
+
1275
+ ### Authentication is Clopen's responsibility
1276
+
1277
+ Because Clopen owns the upstream connection, it also owns auth.
1231
1278
 
1232
1279
  ### Centralized OAuth (one sign-in, every engine)
1233
1280
 
@@ -1255,19 +1302,25 @@ Flow (`backend/mcp/external/oauth.ts`):
1255
1302
  WS routes (admin-only): `mcp:oauth-start` (returns the authorization URL; the
1256
1303
  UI opens it and polls status), `mcp:oauth-complete` (manual paste fallback).
1257
1304
 
1258
- ### Per-engine config: forward the auth headers
1259
-
1260
- Each engine's external builder in `backend/mcp/external/config.ts` MUST forward
1261
- `headers`, and must use the engine's real header field. Dropping headers causes
1262
- silent 401s; the wrong field name can make the engine reject its whole config.
1263
-
1264
- | Engine | Header field | Notes |
1265
- |--------|-------------|-------|
1266
- | Claude | `headers` | http/sse |
1267
- | OpenCode | `headers` | `oauth` left unset = auto-detect fallback |
1268
- | Copilot | `headers` | — |
1269
- | Qwen | `headers` (+ `httpUrl`) | — |
1270
- | **Codex** | **`http_headers`** | **NOT `bearer_token`** — that's rejected for `streamable_http` and aborts the run. Matches the internal bridge. |
1305
+ ### Per-engine config: just the bridge URL + service token
1306
+
1307
+ Because every external server is proxied, each engine's external builder in
1308
+ `backend/mcp/external/config.ts` emits the **same** shape: a loopback bridge URL
1309
+ (`http://localhost:<port>/mcp/ext/<slug>`) plus the service-token bearer. The
1310
+ upstream's real credential (OAuth/API key) is injected by the proxy, not the
1311
+ builder — so there is no per-engine header-field bookkeeping anymore. The only
1312
+ remaining per-engine difference is the SDK's config key for the URL/header:
1313
+
1314
+ | Engine | URL field | Auth header field | Notes |
1315
+ |--------|-----------|-------------------|-------|
1316
+ | Claude | `url` (`type:'http'`) | `headers` | — |
1317
+ | OpenCode | `url` (`type:'remote'`) | `headers` | — |
1318
+ | Copilot | `url` (`type:'http'`) | `headers` | `tools:['*']` so the CLI exposes all proxied tools |
1319
+ | Qwen | `httpUrl` | `headers` | — |
1320
+ | **Codex** | `url` | **`http_headers`** | **NOT `bearer_token`** — rejected for `streamable_http`. |
1321
+
1322
+ A new engine that speaks Streamable-HTTP MCP needs only this one-line builder —
1323
+ no stdio branch, no upstream-credential handling.
1271
1324
 
1272
1325
  ### Required-credential validation
1273
1326