@myrialabs/clopen 0.4.2 → 0.4.4
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/README.md +2 -0
- 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/043_relocate_engine_config_dirs.ts +71 -0
- package/backend/database/migrations/index.ts +21 -0
- package/backend/database/queries/index.ts +1 -1
- package/backend/database/queries/mcp-server-queries.ts +42 -2
- package/backend/engine/README.md +12 -8
- package/backend/engine/adapters/claude/environment.ts +3 -3
- package/backend/engine/adapters/codex/credential.ts +6 -2
- package/backend/engine/adapters/codex/stream.ts +6 -0
- package/backend/engine/adapters/copilot/stream.ts +5 -1
- package/backend/engine/adapters/opencode/server.ts +57 -21
- package/backend/engine/adapters/qwen/environment.ts +7 -0
- package/backend/engine/adapters/qwen/session-fork.ts +13 -1
- package/backend/engine/docs/adding-an-engine.md +8 -0
- package/backend/engine/docs/database.md +9 -6
- package/backend/engine/docs/lessons-learned.md +177 -16
- package/backend/git/git-service.ts +21 -2
- 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 +308 -0
- package/backend/mcp/external/registry-client.ts +8 -1
- 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/utils/paths.ts +16 -0
- package/backend/ws/engine/codex/accounts.ts +3 -0
- package/backend/ws/git/remote.ts +3 -2
- package/backend/ws/mcp/crud.ts +131 -12
- package/dist/assets/{main-qT_RedHf.js → main-AqTMkV9D.js} +272 -266
- 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
|
@@ -18,6 +18,7 @@ import { debug } from '$shared/utils/logger';
|
|
|
18
18
|
import { SERVER_ENV } from '../../utils/env';
|
|
19
19
|
import { validateMcpOutput } from './output-validator';
|
|
20
20
|
import { MCP_TOOL_CALL_TIMEOUT_MS } from '../shared/constants';
|
|
21
|
+
import { getMcpServiceToken } from './service-token';
|
|
21
22
|
|
|
22
23
|
/**
|
|
23
24
|
* User-defined MCP Servers Configuration
|
|
@@ -445,6 +446,7 @@ export function getOpenCodeMcpConfig(): Record<string, McpRemoteConfig> {
|
|
|
445
446
|
url: `http://localhost:${port}/mcp`,
|
|
446
447
|
enabled: true,
|
|
447
448
|
timeout: MCP_TOOL_CALL_TIMEOUT_MS,
|
|
449
|
+
headers: { Authorization: `Bearer ${getMcpServiceToken()}` },
|
|
448
450
|
},
|
|
449
451
|
};
|
|
450
452
|
}
|
|
@@ -462,6 +464,7 @@ export function getOpenCodeMcpConfig(): Record<string, McpRemoteConfig> {
|
|
|
462
464
|
*/
|
|
463
465
|
type CodexMcpServerConfig = {
|
|
464
466
|
url: string;
|
|
467
|
+
http_headers?: Record<string, string>;
|
|
465
468
|
tools?: Record<string, { approval_mode: 'auto' | 'prompt' | 'approve' }>;
|
|
466
469
|
};
|
|
467
470
|
|
|
@@ -507,6 +510,7 @@ export function getCodexMcpConfig(): Record<string, CodexMcpServerConfig> {
|
|
|
507
510
|
return {
|
|
508
511
|
'clopen-mcp': {
|
|
509
512
|
url: `http://localhost:${port}/mcp`,
|
|
513
|
+
http_headers: { Authorization: `Bearer ${getMcpServiceToken()}` },
|
|
510
514
|
tools,
|
|
511
515
|
},
|
|
512
516
|
};
|
|
@@ -559,6 +563,7 @@ export function getCopilotMcpConfig(): Record<string, MCPHTTPServerConfig> {
|
|
|
559
563
|
url: `http://localhost:${port}/mcp`,
|
|
560
564
|
tools,
|
|
561
565
|
timeout: MCP_TOOL_CALL_TIMEOUT_MS,
|
|
566
|
+
headers: { Authorization: `Bearer ${getMcpServiceToken()}` },
|
|
562
567
|
},
|
|
563
568
|
};
|
|
564
569
|
}
|
|
@@ -606,6 +611,7 @@ export function getQwenMcpConfig(): Record<string, QwenMcpServerConfig> {
|
|
|
606
611
|
includeTools,
|
|
607
612
|
timeout: MCP_TOOL_CALL_TIMEOUT_MS,
|
|
608
613
|
trust: true,
|
|
614
|
+
headers: { Authorization: `Bearer ${getMcpServiceToken()}` },
|
|
609
615
|
},
|
|
610
616
|
};
|
|
611
617
|
}
|
|
@@ -12,6 +12,7 @@ import { describe, expect, test, beforeAll, afterAll, beforeEach } from 'bun:tes
|
|
|
12
12
|
import { randomUUID } from 'node:crypto';
|
|
13
13
|
|
|
14
14
|
import { handleMcpRequest } from './remote-server';
|
|
15
|
+
import { getMcpServiceToken } from './service-token';
|
|
15
16
|
import { authQueries, settingsQueries } from '../../database/queries';
|
|
16
17
|
import { generatePAT, generateSessionToken, hashToken } from '../../auth/tokens';
|
|
17
18
|
import { initializeDatabase, closeDatabase, getDatabase } from '../../database';
|
|
@@ -130,6 +131,19 @@ describe('MCP Remote Server Authentication', () => {
|
|
|
130
131
|
expect(response.status).not.toBe(401);
|
|
131
132
|
});
|
|
132
133
|
|
|
134
|
+
test('accepts the internal service token even when auth is required', async () => {
|
|
135
|
+
// The non-Claude engines authenticate to the bridge with this loopback
|
|
136
|
+
// token, not a user session. Without it the whole clopen-mcp bridge 401s.
|
|
137
|
+
const response = await handleMcpRequest(mcpRequest(getMcpServiceToken()));
|
|
138
|
+
expect(response.status).not.toBe(401);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
test('does not mint a session for the service token', async () => {
|
|
142
|
+
const before = sessionCount(testUserId);
|
|
143
|
+
await handleMcpRequest(mcpRequest(getMcpServiceToken()));
|
|
144
|
+
expect(sessionCount(testUserId)).toBe(before);
|
|
145
|
+
});
|
|
146
|
+
|
|
133
147
|
test('skips authentication in no-auth mode', async () => {
|
|
134
148
|
setAuthMode('none');
|
|
135
149
|
const response = await handleMcpRequest(mcpRequest());
|
|
@@ -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/utils/paths.ts
CHANGED
|
@@ -10,6 +10,22 @@ export function getClopenDir(): string {
|
|
|
10
10
|
return join(homedir(), process.env.NODE_ENV === 'development' ? '.clopen-dev' : '.clopen');
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
/**
|
|
14
|
+
* Returns the isolated per-engine config/home directory under
|
|
15
|
+
* `{clopenDir}/engine/{engine}/user/`.
|
|
16
|
+
*
|
|
17
|
+
* Every engine's runtime state (credentials, sessions, logs) is redirected
|
|
18
|
+
* here via that engine's home/config env var (CLAUDE_CONFIG_DIR, CODEX_HOME,
|
|
19
|
+
* COPILOT_HOME, QWEN_RUNTIME_DIR, XDG_* for OpenCode) so Clopen never mixes
|
|
20
|
+
* its data with the user's own global CLI usage (~/.codex, ~/.copilot, …).
|
|
21
|
+
*
|
|
22
|
+
* Grouped under an `engine/` parent so all AI-engine state sits in one place,
|
|
23
|
+
* separate from Clopen's other data dirs (snapshots, etc.).
|
|
24
|
+
*/
|
|
25
|
+
export function getEngineUserConfigDir(engine: string): string {
|
|
26
|
+
return join(getClopenDir(), 'engine', engine, 'user');
|
|
27
|
+
}
|
|
28
|
+
|
|
13
29
|
/**
|
|
14
30
|
* Resolve a path to an OS-native absolute path.
|
|
15
31
|
* On Windows: resolves relative paths, prepends drive letter, converts to backslashes.
|
|
@@ -46,6 +46,7 @@ import {
|
|
|
46
46
|
applyAccountAuth,
|
|
47
47
|
readAuthJson,
|
|
48
48
|
serializeCodexCredential,
|
|
49
|
+
getCodexHomeDir,
|
|
49
50
|
} from '../../../engine/adapters/codex/credential';
|
|
50
51
|
import { resolveBinaryWithRefresh } from '../../../utils/cli';
|
|
51
52
|
import { getCleanSpawnEnv } from '../../../utils/env';
|
|
@@ -324,6 +325,8 @@ export const codexAccountsHandler = createRouter()
|
|
|
324
325
|
// server. (`BROWSER=false` is honoured by most OS open helpers.)
|
|
325
326
|
const ptyEnv = getCleanSpawnEnv();
|
|
326
327
|
ptyEnv['BROWSER'] = 'false';
|
|
328
|
+
// Write auth.json into Clopen's isolated Codex home, not ~/.codex.
|
|
329
|
+
ptyEnv['CODEX_HOME'] = getCodexHomeDir();
|
|
327
330
|
|
|
328
331
|
let pty: ReturnType<typeof spawn>;
|
|
329
332
|
try {
|
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}`);
|
|
@@ -145,7 +199,11 @@ export const mcpCrudHandler = createRouter()
|
|
|
145
199
|
data: t.Object({
|
|
146
200
|
id: t.Number(),
|
|
147
201
|
env: t.Optional(t.Record(t.String(), t.String())),
|
|
148
|
-
headers: t.Optional(t.Record(t.String(), t.String()))
|
|
202
|
+
headers: t.Optional(t.Record(t.String(), t.String())),
|
|
203
|
+
// stdio only: repair an incomplete registry command (e.g. a missing
|
|
204
|
+
// `mcp` subcommand). Ignored for remote servers.
|
|
205
|
+
command: t.Optional(t.String()),
|
|
206
|
+
args: t.Optional(t.Array(t.String()))
|
|
149
207
|
}),
|
|
150
208
|
response: t.Object({ server: INSTALLED_SERVER_SCHEMA })
|
|
151
209
|
}, async ({ data }) => {
|
|
@@ -156,10 +214,71 @@ export const mcpCrudHandler = createRouter()
|
|
|
156
214
|
// Drop blank values so we never store empty env/header entries.
|
|
157
215
|
const clean = (obj?: Record<string, string>) =>
|
|
158
216
|
Object.fromEntries(Object.entries(obj ?? {}).filter(([, v]) => v.trim() !== ''));
|
|
159
|
-
|
|
217
|
+
const env = clean(data.env);
|
|
218
|
+
const headers = clean(data.headers);
|
|
219
|
+
let configSchema: McpConfigField[] = [];
|
|
220
|
+
try { configSchema = JSON.parse(existing.config_schema); } catch { /* ignore */ }
|
|
221
|
+
assertRequiredConfig(configSchema, env, headers);
|
|
222
|
+
mcpServerQueries.updateConfig(data.id, env, headers);
|
|
223
|
+
// Persist an edited command/args for stdio servers (drop blank arg tokens).
|
|
224
|
+
if (existing.transport === 'stdio' && (data.command !== undefined || data.args !== undefined)) {
|
|
225
|
+
const command = (data.command ?? existing.command ?? '').trim();
|
|
226
|
+
if (!command) throw new Error('A stdio MCP server requires a command');
|
|
227
|
+
const args = (data.args ?? []).map(a => a.trim()).filter(a => a !== '');
|
|
228
|
+
mcpServerQueries.updateCommand(data.id, command, args);
|
|
229
|
+
}
|
|
160
230
|
debug.log('mcp', `🔧 Updated config for external MCP server: ${existing.slug}`);
|
|
161
231
|
return { server: toDTO(mcpServerQueries.getById(data.id)!) };
|
|
162
232
|
})
|
|
233
|
+
.http('mcp:status', {
|
|
234
|
+
data: t.Object({ id: t.Number() }),
|
|
235
|
+
response: t.Object({
|
|
236
|
+
status: t.Object({
|
|
237
|
+
state: t.Union([
|
|
238
|
+
t.Literal('ok'),
|
|
239
|
+
t.Literal('needs_auth'),
|
|
240
|
+
t.Literal('needs_config'),
|
|
241
|
+
t.Literal('unreachable'),
|
|
242
|
+
t.Literal('error'),
|
|
243
|
+
t.Literal('local')
|
|
244
|
+
]),
|
|
245
|
+
toolCount: t.Optional(t.Number()),
|
|
246
|
+
message: t.Optional(t.String())
|
|
247
|
+
})
|
|
248
|
+
})
|
|
249
|
+
}, async ({ data }) => {
|
|
250
|
+
debug.log('path', `mcp:status ${data.id}`);
|
|
251
|
+
const existing = mcpServerQueries.getById(data.id);
|
|
252
|
+
if (!existing) throw new Error('MCP server not found');
|
|
253
|
+
if (existing.source === 'internal') return { status: { state: 'local' as const } };
|
|
254
|
+
// Refresh a near-expiry OAuth token first so the probe (which reads the
|
|
255
|
+
// stored bearer) reflects the truly-authenticated state.
|
|
256
|
+
if (existing.oauth) await getValidAccessToken(existing.id);
|
|
257
|
+
const status = await probeServer(resolveServerRow(mcpServerQueries.getById(data.id)!));
|
|
258
|
+
return { status };
|
|
259
|
+
})
|
|
260
|
+
.http('mcp:oauth-start', {
|
|
261
|
+
data: t.Object({ id: t.Number() }),
|
|
262
|
+
response: t.Object({ authorizationUrl: t.String() })
|
|
263
|
+
}, async ({ data }) => {
|
|
264
|
+
debug.log('path', `mcp:oauth-start ${data.id}`);
|
|
265
|
+
const existing = mcpServerQueries.getById(data.id);
|
|
266
|
+
if (!existing) throw new Error('MCP server not found');
|
|
267
|
+
if (existing.transport === 'stdio' || !existing.url) throw new Error('Only remote MCP servers use OAuth sign-in');
|
|
268
|
+
// Clopen drives the whole OAuth flow; the resulting token is injected into
|
|
269
|
+
// every engine, so this single sign-in works for Codex/Claude/all engines.
|
|
270
|
+
return startAuthorization(existing.id, existing.url);
|
|
271
|
+
})
|
|
272
|
+
.http('mcp:oauth-complete', {
|
|
273
|
+
// Manual fallback: the user pastes the full redirected URL (or its
|
|
274
|
+
// code+state) when the loopback callback could not be reached.
|
|
275
|
+
data: t.Object({ state: t.String(), code: t.String() }),
|
|
276
|
+
response: t.Object({ success: t.Boolean() })
|
|
277
|
+
}, async ({ data }) => {
|
|
278
|
+
debug.log('path', 'mcp:oauth-complete');
|
|
279
|
+
await completeAuthorization(data.state, data.code);
|
|
280
|
+
return { success: true };
|
|
281
|
+
})
|
|
163
282
|
.http('mcp:uninstall', {
|
|
164
283
|
data: t.Object({ id: t.Number() }),
|
|
165
284
|
response: t.Object({ success: t.Boolean() })
|