@myrialabs/clopen 0.4.2 → 0.4.3
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 +4 -1
- package/backend/chat/stream-manager.ts +7 -1
- package/backend/database/migrations/041_add_mcp_config_schema.ts +16 -0
- package/backend/database/migrations/042_add_mcp_oauth.ts +20 -0
- package/backend/database/migrations/index.ts +14 -0
- package/backend/database/queries/index.ts +1 -1
- package/backend/database/queries/mcp-server-queries.ts +28 -2
- package/backend/engine/adapters/opencode/server.ts +21 -16
- package/backend/engine/docs/adding-an-engine.md +8 -0
- package/backend/engine/docs/lessons-learned.md +60 -0
- package/backend/git/git-service.ts +11 -1
- package/backend/index.ts +23 -1
- package/backend/mcp/README.md +81 -0
- package/backend/mcp/external/config.ts +70 -14
- package/backend/mcp/external/oauth.ts +329 -0
- package/backend/mcp/external/probe.ts +258 -0
- package/backend/mcp/index.ts +12 -1
- package/backend/mcp/internal/config.ts +6 -0
- package/backend/mcp/internal/remote-server.test.ts +14 -0
- package/backend/mcp/internal/remote-server.ts +8 -0
- package/backend/mcp/internal/service-token.ts +51 -0
- package/backend/ws/git/remote.ts +3 -2
- package/backend/ws/mcp/crud.ts +119 -11
- package/dist/assets/{main-qT_RedHf.js → main-D-AcjotJ.js} +264 -264
- package/dist/assets/main-DJf71Zum.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/dist/assets/main-DKLZPDUN.css +0 -1
|
@@ -19,6 +19,7 @@ import { debug } from '$shared/utils/logger';
|
|
|
19
19
|
import { authQueries } from '$backend/database/queries';
|
|
20
20
|
import { hashToken } from '$backend/auth/tokens';
|
|
21
21
|
import { getAuthMode } from '$backend/auth/auth-service';
|
|
22
|
+
import { isMcpServiceToken } from './service-token';
|
|
22
23
|
|
|
23
24
|
// Lazy imports to avoid circular dependencies at module load time
|
|
24
25
|
let _allServers: Parameters<typeof createRemoteMcpServer>[0] | null = null;
|
|
@@ -60,6 +61,13 @@ function validateAuthToken(request: Request): { userId: string; role: string } |
|
|
|
60
61
|
return null;
|
|
61
62
|
}
|
|
62
63
|
|
|
64
|
+
// Internal bridge credential: the non-Claude engines authenticate to this
|
|
65
|
+
// loopback endpoint with the process-scoped service token, not a user
|
|
66
|
+
// session. Accept it regardless of auth mode — it never leaves the host.
|
|
67
|
+
if (isMcpServiceToken(token)) {
|
|
68
|
+
return { userId: 'mcp-service', role: 'admin' };
|
|
69
|
+
}
|
|
70
|
+
|
|
63
71
|
const tokenHash = hashToken(token);
|
|
64
72
|
|
|
65
73
|
// Try session token first
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Internal MCP service token.
|
|
3
|
+
*
|
|
4
|
+
* The non-Claude engines (Open Code, Codex, Copilot, Qwen) reach the internal
|
|
5
|
+
* tool bridge over HTTP at `http://localhost:<port>/mcp`. That endpoint is
|
|
6
|
+
* auth-protected (`getAuthMode() === 'required'` is the DEFAULT), but the
|
|
7
|
+
* engines run as detached SDKs/subprocesses with no user identity to present —
|
|
8
|
+
* so without a credential their handshake is rejected with 401 and the whole
|
|
9
|
+
* `clopen-mcp` bridge silently disappears (the model reports "no MCP at all").
|
|
10
|
+
*
|
|
11
|
+
* To fix this we mint ONE process-scoped secret at startup. The config builders
|
|
12
|
+
* attach it as `Authorization: Bearer <token>` on every bridge URL, and
|
|
13
|
+
* `remote-server.ts` accepts it as a first-class credential regardless of auth
|
|
14
|
+
* mode. The token only ever lives in memory and is only ever sent to loopback,
|
|
15
|
+
* so it never touches disk or the network.
|
|
16
|
+
*
|
|
17
|
+
* Claude is unaffected: it runs internal servers in-process and never hits the
|
|
18
|
+
* HTTP bridge.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const PREFIX = 'clp_mcp_';
|
|
22
|
+
|
|
23
|
+
function randomHex(bytes: number): string {
|
|
24
|
+
const arr = new Uint8Array(bytes);
|
|
25
|
+
crypto.getRandomValues(arr);
|
|
26
|
+
return Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
let token: string | null = null;
|
|
30
|
+
|
|
31
|
+
/** The process-scoped MCP bridge token, generated lazily on first use. */
|
|
32
|
+
export function getMcpServiceToken(): string {
|
|
33
|
+
if (token === null) {
|
|
34
|
+
token = PREFIX + randomHex(24);
|
|
35
|
+
}
|
|
36
|
+
return token;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Constant-time check whether `candidate` is the current service token.
|
|
41
|
+
* Returns false before the token has been minted.
|
|
42
|
+
*/
|
|
43
|
+
export function isMcpServiceToken(candidate: string): boolean {
|
|
44
|
+
if (token === null) return false;
|
|
45
|
+
if (candidate.length !== token.length) return false;
|
|
46
|
+
let diff = 0;
|
|
47
|
+
for (let i = 0; i < candidate.length; i++) {
|
|
48
|
+
diff |= candidate.charCodeAt(i) ^ token.charCodeAt(i);
|
|
49
|
+
}
|
|
50
|
+
return diff === 0;
|
|
51
|
+
}
|
package/backend/ws/git/remote.ts
CHANGED
|
@@ -200,12 +200,13 @@ export const remoteHandler = createRouter()
|
|
|
200
200
|
.http('git:stash-save', {
|
|
201
201
|
data: t.Object({
|
|
202
202
|
projectId: t.String(),
|
|
203
|
-
message: t.Optional(t.String())
|
|
203
|
+
message: t.Optional(t.String()),
|
|
204
|
+
staged: t.Optional(t.Boolean())
|
|
204
205
|
}),
|
|
205
206
|
response: t.Object({ ok: t.Boolean() })
|
|
206
207
|
}, async ({ data, conn }) => {
|
|
207
208
|
const project = requireProjectAccess(conn, data.projectId);
|
|
208
|
-
await gitService.stashSave(project.path, data.message);
|
|
209
|
+
await gitService.stashSave(project.path, data.message, data.staged);
|
|
209
210
|
return { ok: true };
|
|
210
211
|
})
|
|
211
212
|
|
package/backend/ws/mcp/crud.ts
CHANGED
|
@@ -14,11 +14,30 @@
|
|
|
14
14
|
import { t } from 'elysia';
|
|
15
15
|
import { createRouter } from '$shared/utils/ws-server';
|
|
16
16
|
import { debug } from '$shared/utils/logger';
|
|
17
|
-
import { mcpServerQueries, type McpServerRow, type McpTransport } from '$backend/database/queries';
|
|
18
|
-
import {
|
|
17
|
+
import { mcpServerQueries, type McpConfigField, type McpServerRow, type McpTransport } from '$backend/database/queries';
|
|
18
|
+
import {
|
|
19
|
+
slugifyRegistryName,
|
|
20
|
+
externalNamespace,
|
|
21
|
+
refreshInternalEnabledCache,
|
|
22
|
+
probeServer,
|
|
23
|
+
resolveServerRow,
|
|
24
|
+
startAuthorization,
|
|
25
|
+
completeAuthorization,
|
|
26
|
+
getValidAccessToken
|
|
27
|
+
} from '$backend/mcp';
|
|
19
28
|
|
|
20
29
|
const TRANSPORT_SCHEMA = t.Union([t.Literal('stdio'), t.Literal('http'), t.Literal('sse')]);
|
|
21
30
|
|
|
31
|
+
// UI field metadata captured from the catalog at install time. Engines never
|
|
32
|
+
// read this — it only lets "Configure" render the same labelled fields as install.
|
|
33
|
+
const CONFIG_FIELD_SCHEMA = t.Object({
|
|
34
|
+
name: t.String(),
|
|
35
|
+
kind: t.Union([t.Literal('env'), t.Literal('header')]),
|
|
36
|
+
description: t.Optional(t.String()),
|
|
37
|
+
isRequired: t.Boolean(),
|
|
38
|
+
isSecret: t.Boolean()
|
|
39
|
+
});
|
|
40
|
+
|
|
22
41
|
const INSTALLED_SERVER_SCHEMA = t.Object({
|
|
23
42
|
id: t.Number(),
|
|
24
43
|
slug: t.String(),
|
|
@@ -30,8 +49,12 @@ const INSTALLED_SERVER_SCHEMA = t.Object({
|
|
|
30
49
|
transport: TRANSPORT_SCHEMA,
|
|
31
50
|
command: t.Union([t.String(), t.Null()]),
|
|
32
51
|
args: t.Array(t.String()),
|
|
33
|
-
|
|
34
|
-
|
|
52
|
+
// Full values are returned (not redacted): the whole MCP surface is
|
|
53
|
+
// admin-only (see auth/permissions.ts), and the Settings UI shows values so
|
|
54
|
+
// admins can review and edit what each engine receives.
|
|
55
|
+
env: t.Record(t.String(), t.String()),
|
|
56
|
+
headers: t.Record(t.String(), t.String()),
|
|
57
|
+
configSchema: t.Array(CONFIG_FIELD_SCHEMA),
|
|
35
58
|
url: t.Union([t.String(), t.Null()]),
|
|
36
59
|
source: t.String(),
|
|
37
60
|
enabled: t.Boolean(),
|
|
@@ -40,11 +63,13 @@ const INSTALLED_SERVER_SCHEMA = t.Object({
|
|
|
40
63
|
|
|
41
64
|
function toDTO(row: McpServerRow) {
|
|
42
65
|
let args: string[] = [];
|
|
43
|
-
let
|
|
44
|
-
let
|
|
66
|
+
let env: Record<string, string> = {};
|
|
67
|
+
let headers: Record<string, string> = {};
|
|
68
|
+
let configSchema: McpConfigField[] = [];
|
|
45
69
|
try { args = JSON.parse(row.args); } catch { /* ignore */ }
|
|
46
|
-
try {
|
|
47
|
-
try {
|
|
70
|
+
try { env = JSON.parse(row.env); } catch { /* ignore */ }
|
|
71
|
+
try { headers = JSON.parse(row.headers); } catch { /* ignore */ }
|
|
72
|
+
try { configSchema = JSON.parse(row.config_schema); } catch { /* ignore */ }
|
|
48
73
|
return {
|
|
49
74
|
id: row.id,
|
|
50
75
|
slug: row.slug,
|
|
@@ -56,8 +81,9 @@ function toDTO(row: McpServerRow) {
|
|
|
56
81
|
transport: row.transport,
|
|
57
82
|
command: row.command,
|
|
58
83
|
args,
|
|
59
|
-
|
|
60
|
-
|
|
84
|
+
env,
|
|
85
|
+
headers,
|
|
86
|
+
configSchema,
|
|
61
87
|
url: row.url,
|
|
62
88
|
source: row.source,
|
|
63
89
|
enabled: row.is_enabled === 1,
|
|
@@ -65,6 +91,31 @@ function toDTO(row: McpServerRow) {
|
|
|
65
91
|
};
|
|
66
92
|
}
|
|
67
93
|
|
|
94
|
+
/**
|
|
95
|
+
* Reject an install/configure that omits a credential the catalog marked
|
|
96
|
+
* `isRequired`. Without this, a remote server whose auth header (e.g. an API
|
|
97
|
+
* key or `Authorization` bearer) is left blank installs "successfully" and then
|
|
98
|
+
* silently fails at connect time on every engine — the exact failure mode that
|
|
99
|
+
* left `ai-trendsmcp-google-trends` undetectable. OAuth-only servers declare no
|
|
100
|
+
* required field, so they pass here and are handled by the engine auth flow.
|
|
101
|
+
*/
|
|
102
|
+
function assertRequiredConfig(
|
|
103
|
+
configSchema: McpConfigField[],
|
|
104
|
+
env: Record<string, string>,
|
|
105
|
+
headers: Record<string, string>
|
|
106
|
+
): void {
|
|
107
|
+
const missing = configSchema
|
|
108
|
+
.filter(field => field.isRequired)
|
|
109
|
+
.filter(field => {
|
|
110
|
+
const source = field.kind === 'header' ? headers : env;
|
|
111
|
+
return (source[field.name] ?? '').trim() === '';
|
|
112
|
+
})
|
|
113
|
+
.map(field => field.name);
|
|
114
|
+
if (missing.length > 0) {
|
|
115
|
+
throw new Error(`Missing required configuration: ${missing.join(', ')}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
68
119
|
/** Derive a slug that doesn't collide with an already-installed server. */
|
|
69
120
|
function uniqueSlug(base: string): string {
|
|
70
121
|
const root = slugifyRegistryName(base);
|
|
@@ -97,6 +148,7 @@ export const mcpCrudHandler = createRouter()
|
|
|
97
148
|
url: t.Optional(t.String()),
|
|
98
149
|
env: t.Optional(t.Record(t.String(), t.String())),
|
|
99
150
|
headers: t.Optional(t.Record(t.String(), t.String())),
|
|
151
|
+
configSchema: t.Optional(t.Array(CONFIG_FIELD_SCHEMA)),
|
|
100
152
|
source: t.Optional(t.Union([t.Literal('registry'), t.Literal('custom')]))
|
|
101
153
|
}),
|
|
102
154
|
response: t.Object({ server: INSTALLED_SERVER_SCHEMA })
|
|
@@ -109,6 +161,7 @@ export const mcpCrudHandler = createRouter()
|
|
|
109
161
|
if ((data.transport === 'http' || data.transport === 'sse') && !data.url) {
|
|
110
162
|
throw new Error('A remote MCP server requires a URL');
|
|
111
163
|
}
|
|
164
|
+
assertRequiredConfig(data.configSchema ?? [], data.env ?? {}, data.headers ?? {});
|
|
112
165
|
|
|
113
166
|
const slug = uniqueSlug(data.slug || data.name);
|
|
114
167
|
const row = mcpServerQueries.insert({
|
|
@@ -123,6 +176,7 @@ export const mcpCrudHandler = createRouter()
|
|
|
123
176
|
env: data.env ?? {},
|
|
124
177
|
url: data.url ?? null,
|
|
125
178
|
headers: data.headers ?? {},
|
|
179
|
+
configSchema: data.configSchema ?? [],
|
|
126
180
|
source: data.source ?? 'registry'
|
|
127
181
|
});
|
|
128
182
|
debug.log('mcp', `📥 Installed external MCP server: ${slug}`);
|
|
@@ -156,10 +210,64 @@ export const mcpCrudHandler = createRouter()
|
|
|
156
210
|
// Drop blank values so we never store empty env/header entries.
|
|
157
211
|
const clean = (obj?: Record<string, string>) =>
|
|
158
212
|
Object.fromEntries(Object.entries(obj ?? {}).filter(([, v]) => v.trim() !== ''));
|
|
159
|
-
|
|
213
|
+
const env = clean(data.env);
|
|
214
|
+
const headers = clean(data.headers);
|
|
215
|
+
let configSchema: McpConfigField[] = [];
|
|
216
|
+
try { configSchema = JSON.parse(existing.config_schema); } catch { /* ignore */ }
|
|
217
|
+
assertRequiredConfig(configSchema, env, headers);
|
|
218
|
+
mcpServerQueries.updateConfig(data.id, env, headers);
|
|
160
219
|
debug.log('mcp', `🔧 Updated config for external MCP server: ${existing.slug}`);
|
|
161
220
|
return { server: toDTO(mcpServerQueries.getById(data.id)!) };
|
|
162
221
|
})
|
|
222
|
+
.http('mcp:status', {
|
|
223
|
+
data: t.Object({ id: t.Number() }),
|
|
224
|
+
response: t.Object({
|
|
225
|
+
status: t.Object({
|
|
226
|
+
state: t.Union([
|
|
227
|
+
t.Literal('ok'),
|
|
228
|
+
t.Literal('needs_auth'),
|
|
229
|
+
t.Literal('needs_config'),
|
|
230
|
+
t.Literal('unreachable'),
|
|
231
|
+
t.Literal('error'),
|
|
232
|
+
t.Literal('local')
|
|
233
|
+
]),
|
|
234
|
+
toolCount: t.Optional(t.Number()),
|
|
235
|
+
message: t.Optional(t.String())
|
|
236
|
+
})
|
|
237
|
+
})
|
|
238
|
+
}, async ({ data }) => {
|
|
239
|
+
debug.log('path', `mcp:status ${data.id}`);
|
|
240
|
+
const existing = mcpServerQueries.getById(data.id);
|
|
241
|
+
if (!existing) throw new Error('MCP server not found');
|
|
242
|
+
if (existing.source === 'internal') return { status: { state: 'local' as const } };
|
|
243
|
+
// Refresh a near-expiry OAuth token first so the probe (which reads the
|
|
244
|
+
// stored bearer) reflects the truly-authenticated state.
|
|
245
|
+
if (existing.oauth) await getValidAccessToken(existing.id);
|
|
246
|
+
const status = await probeServer(resolveServerRow(mcpServerQueries.getById(data.id)!));
|
|
247
|
+
return { status };
|
|
248
|
+
})
|
|
249
|
+
.http('mcp:oauth-start', {
|
|
250
|
+
data: t.Object({ id: t.Number() }),
|
|
251
|
+
response: t.Object({ authorizationUrl: t.String() })
|
|
252
|
+
}, async ({ data }) => {
|
|
253
|
+
debug.log('path', `mcp:oauth-start ${data.id}`);
|
|
254
|
+
const existing = mcpServerQueries.getById(data.id);
|
|
255
|
+
if (!existing) throw new Error('MCP server not found');
|
|
256
|
+
if (existing.transport === 'stdio' || !existing.url) throw new Error('Only remote MCP servers use OAuth sign-in');
|
|
257
|
+
// Clopen drives the whole OAuth flow; the resulting token is injected into
|
|
258
|
+
// every engine, so this single sign-in works for Codex/Claude/all engines.
|
|
259
|
+
return startAuthorization(existing.id, existing.url);
|
|
260
|
+
})
|
|
261
|
+
.http('mcp:oauth-complete', {
|
|
262
|
+
// Manual fallback: the user pastes the full redirected URL (or its
|
|
263
|
+
// code+state) when the loopback callback could not be reached.
|
|
264
|
+
data: t.Object({ state: t.String(), code: t.String() }),
|
|
265
|
+
response: t.Object({ success: t.Boolean() })
|
|
266
|
+
}, async ({ data }) => {
|
|
267
|
+
debug.log('path', 'mcp:oauth-complete');
|
|
268
|
+
await completeAuthorization(data.state, data.code);
|
|
269
|
+
return { success: true };
|
|
270
|
+
})
|
|
163
271
|
.http('mcp:uninstall', {
|
|
164
272
|
data: t.Object({ id: t.Number() }),
|
|
165
273
|
response: t.Object({ success: t.Boolean() })
|