@myrialabs/clopen 0.3.21 → 0.4.0
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.ts +11 -1
- package/backend/chat/stream-manager.ts +14 -3
- package/backend/database/migrations/040_create_mcp_servers_table.ts +34 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/index.ts +3 -1
- package/backend/database/queries/mcp-server-queries.ts +166 -0
- package/backend/engine/README.md +2 -2
- package/backend/engine/adapters/claude/environment.ts +0 -17
- package/backend/engine/adapters/claude/error-handler.ts +0 -4
- package/backend/engine/adapters/codex/message-converter.ts +1 -1
- package/backend/engine/adapters/codex/stream.ts +1 -1
- package/backend/engine/adapters/copilot/message-converter.ts +1 -1
- package/backend/engine/adapters/copilot/stream.ts +1 -1
- package/backend/engine/adapters/qwen/message-converter.ts +1 -1
- package/backend/engine/adapters/qwen/stream.ts +1 -1
- package/backend/engine/docs/adapter-contract.md +2 -2
- package/backend/engine/docs/lessons-learned.md +3 -3
- package/backend/engine/docs/quick-reference.md +1 -1
- package/backend/engine/install-recipes.ts +26 -95
- package/backend/files/file-operations.test.ts +75 -0
- package/backend/files/file-operations.ts +10 -56
- package/backend/files/image-processing.test.ts +52 -0
- package/backend/files/image-processing.ts +11 -1
- package/backend/files/path-browsing.ts +141 -139
- package/backend/git/git-service.ts +13 -2
- package/backend/http/files-upload.test.ts +174 -0
- package/backend/http/files-upload.ts +27 -7
- package/backend/http/upload-temp-cleanup.ts +53 -0
- package/backend/index.ts +9 -1
- package/backend/mcp/README.md +67 -32
- package/backend/mcp/external/config.ts +200 -0
- package/backend/mcp/external/registry-client.ts +214 -0
- package/backend/mcp/external/types.ts +69 -0
- package/backend/mcp/index.ts +104 -19
- package/backend/mcp/{config.ts → internal/config.ts} +82 -18
- package/backend/mcp/internal/remote-server.test.ts +150 -0
- package/backend/mcp/{remote-server.ts → internal/remote-server.ts} +68 -0
- package/backend/mcp/{servers → internal/servers}/browser-automation/actions.ts +1 -1
- package/backend/mcp/{servers → internal/servers}/browser-automation/browser.ts +1 -1
- package/backend/mcp/{servers → internal/servers}/browser-automation/index.ts +2 -0
- package/backend/mcp/{servers → internal/servers}/browser-automation/inspection.ts +1 -1
- package/backend/mcp/{servers → internal/servers}/helper.ts +11 -0
- package/backend/mcp/{servers → internal/servers}/index.ts +0 -2
- package/backend/mcp/{types.ts → internal/types.ts} +3 -3
- package/backend/mcp/shared/constants.ts +66 -0
- package/backend/projects/project-cleanup.ts +1 -1
- package/backend/terminal/pty-session-manager.ts +18 -11
- package/backend/ws/engine/index.ts +3 -1
- package/backend/ws/engine/restart.ts +54 -0
- package/backend/ws/files/index.ts +5 -0
- package/backend/ws/files/reveal.ts +61 -0
- package/backend/ws/files/search.test.ts +115 -0
- package/backend/ws/files/search.ts +77 -26
- package/backend/ws/files/write.ts +3 -1
- package/backend/ws/git/branch-name.ts +170 -0
- package/backend/ws/git/branch.ts +15 -2
- package/backend/ws/git/commit-message.ts +8 -2
- package/backend/ws/git/index.ts +3 -1
- package/backend/ws/index.ts +5 -1
- package/backend/ws/mcp/catalog.ts +56 -0
- package/backend/ws/mcp/crud.ts +174 -0
- package/backend/ws/mcp/index.ts +18 -0
- package/backend/ws/user/crud.ts +8 -4
- package/dist/assets/main-B7f2Gzb3.css +1 -0
- package/dist/assets/main-DYt1fDrp.js +383 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/constants/git.ts +5 -0
- package/shared/types/git.ts +5 -0
- package/shared/types/stores/settings.ts +19 -0
- package/backend/mcp/servers/weather/get-temperature.ts +0 -56
- package/backend/mcp/servers/weather/index.ts +0 -31
- package/dist/assets/main-BgOiIS43.js +0 -360
- package/dist/assets/main-CJdJeen6.css +0 -1
- /package/backend/mcp/{output-validator.test.ts → internal/output-validator.test.ts} +0 -0
- /package/backend/mcp/{output-validator.ts → internal/output-validator.ts} +0 -0
- /package/backend/mcp/{project-context.test.ts → internal/project-context.test.ts} +0 -0
- /package/backend/mcp/{project-context.ts → internal/project-context.ts} +0 -0
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Integration tests for file upload race condition fix.
|
|
3
|
+
*
|
|
4
|
+
* These tests verify that the atomic hard-link approach prevents race
|
|
5
|
+
* conditions when multiple uploads target the same file name by calling
|
|
6
|
+
* the actual filesUploadRoute handler with mock HTTP requests.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
|
|
10
|
+
import { mkdir, rm, readFile } from 'node:fs/promises';
|
|
11
|
+
import { join } from 'node:path';
|
|
12
|
+
import { randomUUID } from 'node:crypto';
|
|
13
|
+
|
|
14
|
+
import { filesUploadRoute } from './files-upload';
|
|
15
|
+
import { authQueries } from '../database/queries';
|
|
16
|
+
import { hashToken } from '../auth/tokens';
|
|
17
|
+
import { projectQueries } from '../database/queries/project-queries';
|
|
18
|
+
import { initializeDatabase, closeDatabase } from '../database';
|
|
19
|
+
|
|
20
|
+
const TEST_DIR = join(import.meta.dir, '.test-upload-integration');
|
|
21
|
+
const TEST_WORKSPACE = join(TEST_DIR, 'workspace');
|
|
22
|
+
|
|
23
|
+
let testUserId: string;
|
|
24
|
+
let testToken: string;
|
|
25
|
+
let testProjectId: string;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Helper to create a mock upload request with proper authentication and parameters.
|
|
29
|
+
*/
|
|
30
|
+
function createMockUploadRequest(
|
|
31
|
+
file: File,
|
|
32
|
+
targetPath: string,
|
|
33
|
+
fileName: string,
|
|
34
|
+
token: string
|
|
35
|
+
): Request {
|
|
36
|
+
const url = new URL('http://localhost/api/files/upload');
|
|
37
|
+
url.searchParams.set('targetPath', targetPath);
|
|
38
|
+
url.searchParams.set('fileName', fileName);
|
|
39
|
+
url.searchParams.set('fileSize', String(file.size));
|
|
40
|
+
|
|
41
|
+
return new Request(url.toString(), {
|
|
42
|
+
method: 'POST',
|
|
43
|
+
body: file,
|
|
44
|
+
headers: {
|
|
45
|
+
'authorization': `Bearer ${token}`
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
beforeAll(async () => {
|
|
51
|
+
// Initialize database
|
|
52
|
+
await initializeDatabase();
|
|
53
|
+
|
|
54
|
+
// Create test directory structure
|
|
55
|
+
await mkdir(TEST_WORKSPACE, { recursive: true });
|
|
56
|
+
|
|
57
|
+
// Create test user
|
|
58
|
+
testUserId = randomUUID();
|
|
59
|
+
authQueries.createUser({
|
|
60
|
+
id: testUserId,
|
|
61
|
+
name: 'Test User',
|
|
62
|
+
color: '#000000',
|
|
63
|
+
avatar: 'test',
|
|
64
|
+
role: 'admin',
|
|
65
|
+
personal_access_token_hash: null,
|
|
66
|
+
created_at: new Date().toISOString()
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
// Create test session
|
|
70
|
+
testToken = randomUUID();
|
|
71
|
+
const sessionId = randomUUID();
|
|
72
|
+
const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(); // 24 hours
|
|
73
|
+
authQueries.createSession({
|
|
74
|
+
id: sessionId,
|
|
75
|
+
user_id: testUserId,
|
|
76
|
+
token_hash: hashToken(testToken),
|
|
77
|
+
expires_at: expiresAt,
|
|
78
|
+
created_at: new Date().toISOString(),
|
|
79
|
+
last_active_at: new Date().toISOString()
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// Create test project
|
|
83
|
+
const project = projectQueries.create({
|
|
84
|
+
name: 'Test Project',
|
|
85
|
+
path: TEST_WORKSPACE,
|
|
86
|
+
created_at: new Date().toISOString(),
|
|
87
|
+
last_opened_at: new Date().toISOString()
|
|
88
|
+
});
|
|
89
|
+
testProjectId = project.id;
|
|
90
|
+
|
|
91
|
+
// Link user to project
|
|
92
|
+
projectQueries.addUserProject(testUserId, testProjectId);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
afterAll(async () => {
|
|
96
|
+
// Clean up database
|
|
97
|
+
authQueries.deleteSessionsByUserId(testUserId);
|
|
98
|
+
authQueries.deleteUser(testUserId);
|
|
99
|
+
projectQueries.deleteProject(testProjectId);
|
|
100
|
+
|
|
101
|
+
// Close database
|
|
102
|
+
closeDatabase();
|
|
103
|
+
|
|
104
|
+
// Clean up filesystem
|
|
105
|
+
await rm(TEST_DIR, { recursive: true, force: true });
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
beforeEach(async () => {
|
|
109
|
+
// Clean workspace between tests
|
|
110
|
+
await rm(TEST_WORKSPACE, { recursive: true, force: true });
|
|
111
|
+
await mkdir(TEST_WORKSPACE, { recursive: true });
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
describe('File upload integration tests', () => {
|
|
115
|
+
it('concurrent uploads of same file - link-based exclusive create prevents overwrite', async () => {
|
|
116
|
+
const file1 = new File(['content from upload 1'], 'test.txt', { type: 'text/plain' });
|
|
117
|
+
const file2 = new File(['content from upload 2'], 'test.txt', { type: 'text/plain' });
|
|
118
|
+
|
|
119
|
+
// Create mock requests
|
|
120
|
+
const request1 = createMockUploadRequest(file1, TEST_WORKSPACE, 'test.txt', testToken);
|
|
121
|
+
const request2 = createMockUploadRequest(file2, TEST_WORKSPACE, 'test.txt', testToken);
|
|
122
|
+
|
|
123
|
+
// Fire both concurrently
|
|
124
|
+
const [response1, response2] = await Promise.all([
|
|
125
|
+
filesUploadRoute.handle(request1),
|
|
126
|
+
filesUploadRoute.handle(request2)
|
|
127
|
+
]);
|
|
128
|
+
|
|
129
|
+
// Exactly one 200, one 409
|
|
130
|
+
const statuses = [response1.status, response2.status].sort();
|
|
131
|
+
expect(statuses).toEqual([200, 409]);
|
|
132
|
+
|
|
133
|
+
// Winner's content is on disk (not empty)
|
|
134
|
+
const finalPath = join(TEST_WORKSPACE, 'test.txt');
|
|
135
|
+
const content = await readFile(finalPath, 'utf-8');
|
|
136
|
+
expect(content).toMatch(/content from upload [12]/);
|
|
137
|
+
expect(content.length).toBeGreaterThan(0); // Not empty placeholder
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it('atomic link-based create prevents race', async () => {
|
|
141
|
+
const file = new File(['test content'], 'atomic.txt', { type: 'text/plain' });
|
|
142
|
+
|
|
143
|
+
// First upload succeeds
|
|
144
|
+
const request1 = createMockUploadRequest(file, TEST_WORKSPACE, 'atomic.txt', testToken);
|
|
145
|
+
const response1 = await filesUploadRoute.handle(request1);
|
|
146
|
+
expect(response1.status).toBe(200);
|
|
147
|
+
|
|
148
|
+
// Second upload fails immediately with 409
|
|
149
|
+
const request2 = createMockUploadRequest(file, TEST_WORKSPACE, 'atomic.txt', testToken);
|
|
150
|
+
const response2 = await filesUploadRoute.handle(request2);
|
|
151
|
+
expect(response2.status).toBe(409);
|
|
152
|
+
|
|
153
|
+
// File has first upload's content
|
|
154
|
+
const finalPath = join(TEST_WORKSPACE, 'atomic.txt');
|
|
155
|
+
const content = await readFile(finalPath, 'utf-8');
|
|
156
|
+
expect(content).toBe('test content');
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it('file appears atomically with full content (no partial-file window)', async () => {
|
|
160
|
+
const largeContent = 'x'.repeat(10000); // 10KB
|
|
161
|
+
const file = new File([largeContent], 'large.txt', { type: 'text/plain' });
|
|
162
|
+
|
|
163
|
+
const request = createMockUploadRequest(file, TEST_WORKSPACE, 'large.txt', testToken);
|
|
164
|
+
const response = await filesUploadRoute.handle(request);
|
|
165
|
+
expect(response.status).toBe(200);
|
|
166
|
+
|
|
167
|
+
// File has full content, not empty
|
|
168
|
+
const finalPath = join(TEST_WORKSPACE, 'large.txt');
|
|
169
|
+
const content = await readFile(finalPath, 'utf-8');
|
|
170
|
+
expect(content).toBe(largeContent);
|
|
171
|
+
expect(content.length).toBe(10000);
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
|
|
17
17
|
import { Elysia } from 'elysia';
|
|
18
18
|
import { join } from 'node:path';
|
|
19
|
-
import {
|
|
19
|
+
import { link, mkdir, stat, unlink } from 'node:fs/promises';
|
|
20
20
|
|
|
21
21
|
import { debug } from '$shared/utils/logger';
|
|
22
22
|
import { hashToken } from '../auth/tokens';
|
|
@@ -24,6 +24,7 @@ import { authQueries, fileAuditLogQueries } from '../database/queries';
|
|
|
24
24
|
import { findContainingProjectId, requireFilePathAccessFor } from '../ws/files/path-access';
|
|
25
25
|
import { clientIpFromRequest } from '../utils/client-ip';
|
|
26
26
|
import { validateFileSize } from '../files/file-size-limit';
|
|
27
|
+
import { uploadTempCleanup } from './upload-temp-cleanup';
|
|
27
28
|
|
|
28
29
|
type AuthIdentity = { userId: string; role: string };
|
|
29
30
|
|
|
@@ -125,6 +126,7 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
|
|
|
125
126
|
return new Response(message, { status: 500 });
|
|
126
127
|
}
|
|
127
128
|
|
|
129
|
+
// Early existence check — fast-path rejection before streaming the body
|
|
128
130
|
if (await Bun.file(resolvedFinal).exists()) {
|
|
129
131
|
fileAuditLogQueries.logOperation({
|
|
130
132
|
userId: identity.userId,
|
|
@@ -144,11 +146,16 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
|
|
|
144
146
|
return new Response('Request body is empty', { status: 400 });
|
|
145
147
|
}
|
|
146
148
|
|
|
149
|
+
// Stream to a unique temp file, then atomically link into place.
|
|
150
|
+
// link() uses O_EXCL semantics — fails with EEXIST if final already exists.
|
|
151
|
+
// The final path only appears with full content (no partial-file visibility).
|
|
147
152
|
const tempPath = `${resolvedFinal}.${crypto.randomUUID()}.partial`;
|
|
153
|
+
uploadTempCleanup.register(tempPath);
|
|
148
154
|
const writer = Bun.file(tempPath).writer();
|
|
149
155
|
let written = 0;
|
|
150
156
|
|
|
151
157
|
const cleanupTemp = async () => {
|
|
158
|
+
uploadTempCleanup.deregister(tempPath);
|
|
152
159
|
try { await writer.end(); } catch { /* best-effort */ }
|
|
153
160
|
try { await unlink(tempPath); } catch { /* best-effort */ }
|
|
154
161
|
};
|
|
@@ -171,6 +178,7 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
|
|
|
171
178
|
await writer.end();
|
|
172
179
|
|
|
173
180
|
if (written !== fileSizeParam) {
|
|
181
|
+
uploadTempCleanup.deregister(tempPath);
|
|
174
182
|
await unlink(tempPath).catch(() => {});
|
|
175
183
|
return new Response(`Incomplete upload: received ${written} of ${fileSizeParam} bytes`, { status: 400 });
|
|
176
184
|
}
|
|
@@ -178,6 +186,7 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
|
|
|
178
186
|
try {
|
|
179
187
|
validateFileSize(written);
|
|
180
188
|
} catch (error) {
|
|
189
|
+
uploadTempCleanup.deregister(tempPath);
|
|
181
190
|
await unlink(tempPath).catch(() => {});
|
|
182
191
|
fileAuditLogQueries.logOperation({
|
|
183
192
|
userId: identity.userId,
|
|
@@ -193,8 +202,15 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
|
|
|
193
202
|
return new Response(error instanceof Error ? error.message : 'File too large', { status: 413 });
|
|
194
203
|
}
|
|
195
204
|
|
|
196
|
-
//
|
|
197
|
-
|
|
205
|
+
// Atomic exclusive link — fails with EEXIST if final already exists
|
|
206
|
+
try {
|
|
207
|
+
await link(tempPath, resolvedFinal);
|
|
208
|
+
} catch (error: unknown) {
|
|
209
|
+
if (error && typeof error === 'object' && 'code' in error && error.code === 'EEXIST') {
|
|
210
|
+
uploadTempCleanup.deregister(tempPath);
|
|
211
|
+
await unlink(tempPath).catch(() => {});
|
|
212
|
+
return new Response('File already exists', { status: 409 });
|
|
213
|
+
}
|
|
198
214
|
await unlink(tempPath).catch(() => {});
|
|
199
215
|
fileAuditLogQueries.logOperation({
|
|
200
216
|
userId: identity.userId,
|
|
@@ -205,12 +221,15 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
|
|
|
205
221
|
ipAddress,
|
|
206
222
|
userAgent,
|
|
207
223
|
success: false,
|
|
208
|
-
errorMessage:
|
|
224
|
+
errorMessage: `link() failed: ${(error as Error).message}`
|
|
209
225
|
});
|
|
210
|
-
|
|
226
|
+
throw error;
|
|
211
227
|
}
|
|
212
228
|
|
|
213
|
-
|
|
229
|
+
uploadTempCleanup.deregister(tempPath);
|
|
230
|
+
// Clean up temp — the real file is now the hard-link
|
|
231
|
+
await unlink(tempPath).catch(() => {});
|
|
232
|
+
|
|
214
233
|
const stats = await stat(resolvedFinal);
|
|
215
234
|
|
|
216
235
|
fileAuditLogQueries.logOperation({
|
|
@@ -230,7 +249,8 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
|
|
|
230
249
|
modified: stats.mtime.toISOString()
|
|
231
250
|
});
|
|
232
251
|
} catch (error) {
|
|
233
|
-
|
|
252
|
+
uploadTempCleanup.deregister(tempPath);
|
|
253
|
+
await unlink(tempPath).catch(() => {});
|
|
234
254
|
debug.error('file', 'HTTP upload error:', error);
|
|
235
255
|
const message = error instanceof Error ? error.message : 'Upload failed';
|
|
236
256
|
fileAuditLogQueries.logOperation({
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { stat, unlink } from 'node:fs/promises';
|
|
2
|
+
|
|
3
|
+
import { debug } from '$shared/utils/logger';
|
|
4
|
+
|
|
5
|
+
const CLEANUP_INTERVAL_MS = 60 * 60_000;
|
|
6
|
+
const TEMP_FILE_AGE_MS = 2 * 60 * 60_000;
|
|
7
|
+
|
|
8
|
+
class UploadTempCleanup {
|
|
9
|
+
private timer: ReturnType<typeof setInterval> | null = null;
|
|
10
|
+
private activeTemps = new Map<string, number>();
|
|
11
|
+
|
|
12
|
+
register(tempPath: string): void {
|
|
13
|
+
this.activeTemps.set(tempPath, Date.now());
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
deregister(tempPath: string): void {
|
|
17
|
+
this.activeTemps.delete(tempPath);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
start(): void {
|
|
21
|
+
if (this.timer) return;
|
|
22
|
+
this.timer = setInterval(() => this.cleanup(), CLEANUP_INTERVAL_MS);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
private async cleanup(): Promise<void> {
|
|
26
|
+
const now = Date.now();
|
|
27
|
+
let removed = 0;
|
|
28
|
+
|
|
29
|
+
for (const [tempPath, createdAt] of this.activeTemps) {
|
|
30
|
+
if (now - createdAt <= TEMP_FILE_AGE_MS) continue;
|
|
31
|
+
try {
|
|
32
|
+
await unlink(tempPath);
|
|
33
|
+
this.activeTemps.delete(tempPath);
|
|
34
|
+
removed++;
|
|
35
|
+
} catch {
|
|
36
|
+
this.activeTemps.delete(tempPath);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (removed > 0) {
|
|
41
|
+
debug.log('file', `Upload temp cleanup: removed ${removed} stale partial file(s)`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
dispose(): void {
|
|
46
|
+
if (this.timer) {
|
|
47
|
+
clearInterval(this.timer);
|
|
48
|
+
this.timer = null;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export const uploadTempCleanup = new UploadTempCleanup();
|
package/backend/index.ts
CHANGED
|
@@ -18,6 +18,7 @@ import { loggerMiddleware } from './middleware/logger';
|
|
|
18
18
|
|
|
19
19
|
// Database initialization
|
|
20
20
|
import { initializeDatabase, closeDatabase } from './database';
|
|
21
|
+
import { syncInternalServers } from './mcp';
|
|
21
22
|
import { disposeAllEngines } from './engine';
|
|
22
23
|
import { refreshProcessPath } from './utils/path-enrich';
|
|
23
24
|
import { debug } from '$shared/utils/logger';
|
|
@@ -39,12 +40,13 @@ import { audioRoute } from './http/audio';
|
|
|
39
40
|
import { browserPreviewServiceManager } from './preview';
|
|
40
41
|
|
|
41
42
|
// MCP remote server for Open Code custom tools
|
|
42
|
-
import { handleMcpRequest, closeMcpServer } from './mcp
|
|
43
|
+
import { handleMcpRequest, closeMcpServer } from './mcp';
|
|
43
44
|
|
|
44
45
|
// Auth middleware
|
|
45
46
|
import { checkRouteAccess } from './auth/permissions';
|
|
46
47
|
import { authRateLimiter } from './auth';
|
|
47
48
|
import { sessionCleanupScheduler } from './auth/session-cleanup';
|
|
49
|
+
import { uploadTempCleanup } from './http/upload-temp-cleanup';
|
|
48
50
|
import { ws as wsServer } from './utils/ws';
|
|
49
51
|
import { messageRateLimiter } from './ws/message-rate-limiter';
|
|
50
52
|
|
|
@@ -162,8 +164,12 @@ async function startServer() {
|
|
|
162
164
|
try {
|
|
163
165
|
await initializeDatabase();
|
|
164
166
|
debug.log('database', '✅ Database initialized successfully');
|
|
167
|
+
// Mirror code-defined internal MCP servers into the DB so Settings → MCP
|
|
168
|
+
// can list and toggle them. Idempotent; preserves the user's toggles.
|
|
169
|
+
syncInternalServers();
|
|
165
170
|
// Start expired session cleanup now that the database is ready
|
|
166
171
|
sessionCleanupScheduler.start();
|
|
172
|
+
uploadTempCleanup.start();
|
|
167
173
|
} catch (error) {
|
|
168
174
|
debug.warn('database', '⚠️ Database initialization failed:', error);
|
|
169
175
|
}
|
|
@@ -214,6 +220,8 @@ async function gracefulShutdown() {
|
|
|
214
220
|
authRateLimiter.dispose();
|
|
215
221
|
// Dispose expired session cleanup timer
|
|
216
222
|
sessionCleanupScheduler.dispose();
|
|
223
|
+
// Dispose upload temp cleanup timer
|
|
224
|
+
uploadTempCleanup.dispose();
|
|
217
225
|
// Close MCP remote server (before engines, as they may still reference it)
|
|
218
226
|
await closeMcpServer();
|
|
219
227
|
// Cleanup browser preview sessions
|
package/backend/mcp/README.md
CHANGED
|
@@ -1,6 +1,28 @@
|
|
|
1
|
-
#
|
|
1
|
+
# MCP (Model Context Protocol)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Clopen integrates MCP from **two distinct sources**, kept cleanly separated on
|
|
4
|
+
disk and in their namespace keys:
|
|
5
|
+
|
|
6
|
+
| | **Internal** (`internal/`) | **External** (`external/`) |
|
|
7
|
+
|---|---|---|
|
|
8
|
+
| What | Custom tools defined in code via `defineServer()` | Servers the user installs from the official MCP registry |
|
|
9
|
+
| Managed | By developers (this README) | By users in **Settings → MCP** |
|
|
10
|
+
| Stored | In code (`internal/servers/`) | In the DB (`mcp_servers` table) |
|
|
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) |
|
|
13
|
+
|
|
14
|
+
Both are merged behind the **facade** `backend/mcp/index.ts` — the only module
|
|
15
|
+
the rest of the backend imports from (`getEnabledMcpServers()`,
|
|
16
|
+
`getXxxMcpConfig()`, `resolveOpenCodeToolName()` all return the combined view).
|
|
17
|
+
|
|
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`.
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## Custom (Internal) MCP Tools
|
|
24
|
+
|
|
25
|
+
Custom MCP tools add 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
26
|
|
|
5
27
|
## 📚 Table of Contents
|
|
6
28
|
|
|
@@ -38,9 +60,9 @@ System for adding custom tools to AI engines with type-safe TypeScript definitio
|
|
|
38
60
|
|
|
39
61
|
### 1. Create a New Server
|
|
40
62
|
|
|
41
|
-
Create a new folder in `./servers/` (e.g., `calculator/`) and create an `index.ts` file using the `defineServer` helper:
|
|
63
|
+
Create a new folder in `./internal/servers/` (e.g., `calculator/`) and create an `index.ts` file using the `defineServer` helper:
|
|
42
64
|
|
|
43
|
-
**File: `./servers/calculator/index.ts`**
|
|
65
|
+
**File: `./internal/servers/calculator/index.ts`**
|
|
44
66
|
```typescript
|
|
45
67
|
import { z } from "zod";
|
|
46
68
|
import { defineServer } from "../helper";
|
|
@@ -85,7 +107,7 @@ export default defineServer({
|
|
|
85
107
|
|
|
86
108
|
### 2. Register the Server
|
|
87
109
|
|
|
88
|
-
Add to `./servers/index.ts` to auto-build registries:
|
|
110
|
+
Add to `./internal/servers/index.ts` to auto-build registries:
|
|
89
111
|
|
|
90
112
|
```typescript
|
|
91
113
|
import weather from './weather';
|
|
@@ -106,7 +128,7 @@ export const serverRegistry = registry;
|
|
|
106
128
|
|
|
107
129
|
### 3. Configure the Server
|
|
108
130
|
|
|
109
|
-
Add to `./config.ts` (only specify `enabled` and `tools`):
|
|
131
|
+
Add to `./internal/config.ts` (only specify `enabled` and `tools`):
|
|
110
132
|
|
|
111
133
|
```typescript
|
|
112
134
|
const mcpServersConfig: Record<ServerName, ServerConfig> = {
|
|
@@ -133,24 +155,33 @@ Tool available to Claude as: `mcp__calculator__calculate`
|
|
|
133
155
|
|
|
134
156
|
```
|
|
135
157
|
backend/mcp/
|
|
136
|
-
├──
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
├──
|
|
141
|
-
├──
|
|
142
|
-
├──
|
|
143
|
-
│
|
|
144
|
-
│ ├──
|
|
145
|
-
│ ├──
|
|
146
|
-
│
|
|
147
|
-
│
|
|
148
|
-
│
|
|
149
|
-
│ ├──
|
|
150
|
-
│ ├──
|
|
151
|
-
│ ├──
|
|
152
|
-
│ └──
|
|
153
|
-
└──
|
|
158
|
+
├── index.ts # FACADE — the only public entry point. Merges
|
|
159
|
+
│ # internal + external before handing config to adapters.
|
|
160
|
+
├── shared/
|
|
161
|
+
│ └── constants.ts # Namespace constants/helpers (clopen-mcp, clopen-reserved prefix, slugify)
|
|
162
|
+
├── internal/ # Custom tools defined in code (this README)
|
|
163
|
+
│ ├── types.ts # TypeScript type definitions (auto-inferred from metadata)
|
|
164
|
+
│ ├── config.ts # User configuration (enabled, tools) + auto-merge with registry
|
|
165
|
+
│ │ # + resolveOpenCodeToolName() & getXxxMcpConfig() (clopen-mcp)
|
|
166
|
+
│ ├── remote-server.ts# Remote HTTP MCP bridge for non-Claude engines (/mcp)
|
|
167
|
+
│ ├── project-context.ts # Project context service for MCP tool handlers
|
|
168
|
+
│ ├── output-validator.ts # Caps oversized tool outputs
|
|
169
|
+
│ └── servers/ # Server implementations (single source of truth)
|
|
170
|
+
│ ├── index.ts # Auto-build registries from server array + export allServers
|
|
171
|
+
│ ├── helper.ts # defineServer, buildServerRegistries & createRemoteMcpServer
|
|
172
|
+
│ ├── weather/ # Example: Weather service
|
|
173
|
+
│ │ ├── index.ts
|
|
174
|
+
│ │ └── get-temperature.ts
|
|
175
|
+
│ └── browser-automation/ # Example: Browser automation service
|
|
176
|
+
│ ├── index.ts
|
|
177
|
+
│ ├── actions.ts
|
|
178
|
+
│ ├── browser.ts
|
|
179
|
+
│ └── inspection.ts
|
|
180
|
+
├── external/ # User-installed servers from the official registry
|
|
181
|
+
│ ├── types.ts # CatalogServer / ResolvedExternalServer
|
|
182
|
+
│ ├── registry-client.ts # Fetch + normalise registry.modelcontextprotocol.io
|
|
183
|
+
│ └── config.ts # Per-engine builders (bare <slug>) + resolveExternalToolName
|
|
184
|
+
└── README.md # This file
|
|
154
185
|
```
|
|
155
186
|
|
|
156
187
|
### Server Organization
|
|
@@ -258,9 +289,9 @@ its own transport and `McpServer` instance. Handles session lifecycle
|
|
|
258
289
|
|
|
259
290
|
### Folder Structure
|
|
260
291
|
|
|
261
|
-
Each MCP server should be in its own folder under `./servers/`:
|
|
292
|
+
Each MCP server should be in its own folder under `./internal/servers/`:
|
|
262
293
|
|
|
263
|
-
1. **Create a folder**: `./servers/your-server-name/`
|
|
294
|
+
1. **Create a folder**: `./internal/servers/your-server-name/`
|
|
264
295
|
2. **Create index.ts**: Main server definition file
|
|
265
296
|
3. **Optional**: Create separate files for tool handlers (e.g., `tool-name.ts`)
|
|
266
297
|
|
|
@@ -1040,7 +1071,7 @@ export default defineServer({
|
|
|
1040
1071
|
**Problem:** My custom tool doesn't appear in Claude's available tools.
|
|
1041
1072
|
|
|
1042
1073
|
**Solutions:**
|
|
1043
|
-
1. Verify server folder exists in `./servers/` with an `index.ts` file
|
|
1074
|
+
1. Verify server folder exists in `./internal/servers/` with an `index.ts` file
|
|
1044
1075
|
2. Verify server is defined using `defineServer` and exported as default (`export default defineServer(...)`)
|
|
1045
1076
|
3. Check server is imported and added to `allServers` array in `servers/index.ts`
|
|
1046
1077
|
4. Check that server is enabled in `mcpServersConfig` in `config.ts`
|
|
@@ -1171,11 +1202,15 @@ checklist in `backend/engine/README.md` §9.12. The summary:
|
|
|
1171
1202
|
|
|
1172
1203
|
| File | Location | Purpose |
|
|
1173
1204
|
|------|----------|---------|
|
|
1174
|
-
|
|
|
1175
|
-
|
|
|
1176
|
-
|
|
|
1177
|
-
|
|
|
1178
|
-
|
|
|
1205
|
+
| Public facade | `backend/mcp/index.ts` | Only public entry; merges internal + external |
|
|
1206
|
+
| Tool definitions | `backend/mcp/internal/servers/` | Single source of truth (internal) |
|
|
1207
|
+
| Remote MCP server | `backend/mcp/internal/remote-server.ts` | HTTP bridge for every non-Claude engine |
|
|
1208
|
+
| Server factory | `backend/mcp/internal/servers/helper.ts` | `createRemoteMcpServer()` |
|
|
1209
|
+
| Per-engine config (internal) | `backend/mcp/internal/config.ts` | `getOpenCodeMcpConfig()`, `getCodexMcpConfig()`, … (clopen-mcp) |
|
|
1210
|
+
| Tool name resolver | `backend/mcp/internal/config.ts` | `resolveOpenCodeToolName()` (handles every engine's prefix variant) |
|
|
1211
|
+
| External catalog | `backend/mcp/external/registry-client.ts` | Browse the official MCP registry |
|
|
1212
|
+
| Per-engine config (external) | `backend/mcp/external/config.ts` | `getXxxExternalMcpConfig()` (<slug>) |
|
|
1213
|
+
| Namespace constants | `backend/mcp/shared/constants.ts` | `clopen-mcp`, clopen-reserved prefix, slugify |
|
|
1179
1214
|
|
|
1180
1215
|
---
|
|
1181
1216
|
|