@myrialabs/clopen 0.3.22 → 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/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/index.ts +5 -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/{remote-server.test.ts → internal/remote-server.test.ts} +3 -3
- 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/ws/engine/index.ts +3 -1
- package/backend/ws/engine/restart.ts +54 -0
- 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/dist/assets/main-B7f2Gzb3.css +1 -0
- package/dist/assets/{main-Ba19ADkk.js → main-DYt1fDrp.js} +279 -273
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/stores/settings.ts +2 -0
- package/backend/mcp/servers/weather/get-temperature.ts +0 -56
- package/backend/mcp/servers/weather/index.ts +0 -31
- package/dist/assets/main-CwCZzMVm.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
- /package/backend/mcp/{remote-server.ts → internal/remote-server.ts} +0 -0
|
@@ -80,6 +80,7 @@ export const ADMIN_ONLY_ROUTES = new Set([
|
|
|
80
80
|
'engine:opencode-account-rename',
|
|
81
81
|
'engine:opencode-server-restart',
|
|
82
82
|
'engine:opencode-models-dev-fetch',
|
|
83
|
+
'engine:restart-all',
|
|
83
84
|
// Tunnel — remote/local management mutates global Cloudflare credentials,
|
|
84
85
|
// cloudflared auth, and ingress rules. Quick Tunnel is ephemeral and stays
|
|
85
86
|
// open. Read-only routes (status, *-list, ingress, auth-status) stay open so
|
|
@@ -97,7 +98,16 @@ export const ADMIN_ONLY_ROUTES = new Set([
|
|
|
97
98
|
'tunnel:local:ingress:add',
|
|
98
99
|
'tunnel:local:ingress:remove',
|
|
99
100
|
'tunnel:local:start',
|
|
100
|
-
'tunnel:local:stop'
|
|
101
|
+
'tunnel:local:stop',
|
|
102
|
+
// External MCP — installing/removing servers from the official registry is a
|
|
103
|
+
// global, system-wide operation (it applies to every engine and project), so
|
|
104
|
+
// the whole surface is admin-only, mirroring System Tools and Engines.
|
|
105
|
+
'mcp:catalog',
|
|
106
|
+
'mcp:list',
|
|
107
|
+
'mcp:install',
|
|
108
|
+
'mcp:toggle',
|
|
109
|
+
'mcp:update-config',
|
|
110
|
+
'mcp:uninstall'
|
|
101
111
|
]);
|
|
102
112
|
|
|
103
113
|
/**
|
|
@@ -35,7 +35,7 @@ import type { DatabaseMessage } from '$shared/types/database/schema';
|
|
|
35
35
|
import { getProjectEngine, initializeProjectEngine } from '../engine';
|
|
36
36
|
import { messageQueries, sessionQueries } from '../database/queries';
|
|
37
37
|
import { snapshotService } from '../snapshot/snapshot-service';
|
|
38
|
-
import { projectContextService } from '../mcp
|
|
38
|
+
import { projectContextService } from '../mcp';
|
|
39
39
|
import { browserMcpControl } from '../preview';
|
|
40
40
|
import { extractMessageText } from '../snapshot/helpers';
|
|
41
41
|
import { debug } from '$shared/utils/logger';
|
|
@@ -649,14 +649,25 @@ class StreamManager extends EventEmitter {
|
|
|
649
649
|
// ── System Init ────────────────────────────────────────
|
|
650
650
|
case 'system_init': {
|
|
651
651
|
const initEvent = output as SystemInitEvent;
|
|
652
|
-
|
|
652
|
+
// Suppress the toast for "soft" statuses: `pending` (still
|
|
653
|
+
// connecting) and `needs-auth` (server expects OAuth/credentials
|
|
654
|
+
// configured in Settings → MCP). These are not errors — a scary
|
|
655
|
+
// toast for them is confusing. (Status is the raw SDK string,
|
|
656
|
+
// wider than the EngineOutput union, hence the cast.)
|
|
657
|
+
const SOFT_STATUSES = new Set(['pending', 'needs-auth']);
|
|
658
|
+
const failedServers = initEvent.mcpServers.filter(
|
|
659
|
+
s => s.status !== 'connected' && !SOFT_STATUSES.has(s.status as string)
|
|
660
|
+
);
|
|
661
|
+
initEvent.mcpServers
|
|
662
|
+
.filter(s => SOFT_STATUSES.has(s.status as string))
|
|
663
|
+
.forEach(s => debug.log('mcp', `MCP server "${s.name}" not ready (${s.status}) — suppressing toast`));
|
|
653
664
|
failedServers.forEach(server => {
|
|
654
665
|
debug.warn('mcp', `MCP server connection failed: ${server.name} (${server.status})`);
|
|
655
666
|
this.emitStreamEvent(streamState, 'notification', {
|
|
656
667
|
notification: {
|
|
657
668
|
type: 'warning',
|
|
658
669
|
title: 'MCP Server Connection Failed',
|
|
659
|
-
message: `Failed to connect to
|
|
670
|
+
message: `Failed to connect to MCP server "${server.name}".`,
|
|
660
671
|
},
|
|
661
672
|
timestamp: new Date().toISOString()
|
|
662
673
|
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { DatabaseConnection } from '$shared/types/database/connection';
|
|
2
|
+
import { debug } from '$shared/utils/logger';
|
|
3
|
+
|
|
4
|
+
export const description = 'Create mcp_servers table for external (user-installed) MCP servers';
|
|
5
|
+
|
|
6
|
+
export const up = (db: DatabaseConnection): void => {
|
|
7
|
+
debug.log('migration', 'Creating mcp_servers table...');
|
|
8
|
+
db.exec(`
|
|
9
|
+
CREATE TABLE IF NOT EXISTS mcp_servers (
|
|
10
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
11
|
+
slug TEXT NOT NULL UNIQUE,
|
|
12
|
+
name TEXT NOT NULL,
|
|
13
|
+
description TEXT,
|
|
14
|
+
registry_name TEXT,
|
|
15
|
+
version TEXT,
|
|
16
|
+
transport TEXT NOT NULL,
|
|
17
|
+
command TEXT,
|
|
18
|
+
args TEXT NOT NULL DEFAULT '[]',
|
|
19
|
+
env TEXT NOT NULL DEFAULT '{}',
|
|
20
|
+
url TEXT,
|
|
21
|
+
headers TEXT NOT NULL DEFAULT '{}',
|
|
22
|
+
source TEXT NOT NULL DEFAULT 'registry',
|
|
23
|
+
is_enabled INTEGER NOT NULL DEFAULT 1,
|
|
24
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
25
|
+
)
|
|
26
|
+
`);
|
|
27
|
+
debug.log('migration', 'mcp_servers table created');
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export const down = (db: DatabaseConnection): void => {
|
|
31
|
+
debug.log('migration', 'Dropping mcp_servers table...');
|
|
32
|
+
db.exec('DROP TABLE IF EXISTS mcp_servers');
|
|
33
|
+
debug.log('migration', 'mcp_servers table dropped');
|
|
34
|
+
};
|
|
@@ -38,6 +38,7 @@ import * as migration036 from './036_create_auth_audit_log';
|
|
|
38
38
|
import * as migration037 from './037_repair_auth_audit_log_schema';
|
|
39
39
|
import * as migration038 from './038_add_workspace_state_to_user_projects';
|
|
40
40
|
import * as migration039 from './039_create_file_audit_log';
|
|
41
|
+
import * as migration040 from './040_create_mcp_servers_table';
|
|
41
42
|
|
|
42
43
|
// Export all migrations in order
|
|
43
44
|
export const migrations = [
|
|
@@ -274,6 +275,12 @@ export const migrations = [
|
|
|
274
275
|
description: migration039.description,
|
|
275
276
|
up: migration039.up,
|
|
276
277
|
down: migration039.down
|
|
278
|
+
},
|
|
279
|
+
{
|
|
280
|
+
id: '040',
|
|
281
|
+
description: migration040.description,
|
|
282
|
+
up: migration040.up,
|
|
283
|
+
down: migration040.down
|
|
277
284
|
}
|
|
278
285
|
];
|
|
279
286
|
|
|
@@ -11,4 +11,6 @@ export { authQueries } from './auth-queries';
|
|
|
11
11
|
export { dbClientConnectionQueries } from './db-client-connection-queries';
|
|
12
12
|
export { dbClientQueryHistoryQueries } from './db-client-query-history-queries';
|
|
13
13
|
export { auditLogQueries } from './audit-log-queries';
|
|
14
|
-
export { fileAuditLogQueries } from './file-audit-log-queries';
|
|
14
|
+
export { fileAuditLogQueries } from './file-audit-log-queries';
|
|
15
|
+
export { mcpServerQueries } from './mcp-server-queries';
|
|
16
|
+
export type { McpServerRow, McpServerInput, McpTransport, McpSource } from './mcp-server-queries';
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* External MCP Server Queries
|
|
3
|
+
*
|
|
4
|
+
* CRUD for user-installed (external) MCP servers — the servers managed from
|
|
5
|
+
* Settings → MCP, sourced from the official MCP registry. This is distinct
|
|
6
|
+
* from the INTERNAL custom-tool servers in `backend/mcp/internal/servers/`,
|
|
7
|
+
* which are defined in code and not stored in the DB.
|
|
8
|
+
*
|
|
9
|
+
* Conventions:
|
|
10
|
+
* - `slug` : unique machine id, used to derive the `<slug>` MCP
|
|
11
|
+
* namespace. Only `[a-z0-9-]`.
|
|
12
|
+
* - `transport`: 'stdio' | 'http' | 'sse'.
|
|
13
|
+
* - `args`/`env`/`headers` are stored as JSON strings.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { getDatabase } from '../index';
|
|
17
|
+
|
|
18
|
+
export type McpTransport = 'stdio' | 'http' | 'sse';
|
|
19
|
+
export type McpSource = 'registry' | 'custom' | 'internal';
|
|
20
|
+
|
|
21
|
+
/** Raw DB row. */
|
|
22
|
+
export interface McpServerRow {
|
|
23
|
+
id: number;
|
|
24
|
+
slug: string;
|
|
25
|
+
name: string;
|
|
26
|
+
description: string | null;
|
|
27
|
+
registry_name: string | null;
|
|
28
|
+
version: string | null;
|
|
29
|
+
transport: McpTransport;
|
|
30
|
+
command: string | null;
|
|
31
|
+
args: string;
|
|
32
|
+
env: string;
|
|
33
|
+
url: string | null;
|
|
34
|
+
headers: string;
|
|
35
|
+
source: McpSource;
|
|
36
|
+
is_enabled: number;
|
|
37
|
+
created_at: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface McpServerInput {
|
|
41
|
+
slug: string;
|
|
42
|
+
name: string;
|
|
43
|
+
description?: string | null;
|
|
44
|
+
registryName?: string | null;
|
|
45
|
+
version?: string | null;
|
|
46
|
+
transport: McpTransport;
|
|
47
|
+
command?: string | null;
|
|
48
|
+
args?: string[];
|
|
49
|
+
env?: Record<string, string>;
|
|
50
|
+
url?: string | null;
|
|
51
|
+
headers?: Record<string, string>;
|
|
52
|
+
source?: McpSource;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const mcpServerQueries = {
|
|
56
|
+
getAll(): McpServerRow[] {
|
|
57
|
+
const db = getDatabase();
|
|
58
|
+
return db.prepare(`SELECT * FROM mcp_servers ORDER BY created_at ASC`).all() as McpServerRow[];
|
|
59
|
+
},
|
|
60
|
+
|
|
61
|
+
getEnabled(): McpServerRow[] {
|
|
62
|
+
const db = getDatabase();
|
|
63
|
+
return db.prepare(`SELECT * FROM mcp_servers WHERE is_enabled = 1 ORDER BY created_at ASC`).all() as McpServerRow[];
|
|
64
|
+
},
|
|
65
|
+
|
|
66
|
+
getById(id: number): McpServerRow | null {
|
|
67
|
+
const db = getDatabase();
|
|
68
|
+
return db.prepare(`SELECT * FROM mcp_servers WHERE id = ?`).get(id) as McpServerRow | null;
|
|
69
|
+
},
|
|
70
|
+
|
|
71
|
+
getBySlug(slug: string): McpServerRow | null {
|
|
72
|
+
const db = getDatabase();
|
|
73
|
+
return db.prepare(`SELECT * FROM mcp_servers WHERE slug = ?`).get(slug) as McpServerRow | null;
|
|
74
|
+
},
|
|
75
|
+
|
|
76
|
+
getBySource(source: McpSource): McpServerRow[] {
|
|
77
|
+
const db = getDatabase();
|
|
78
|
+
return db.prepare(`SELECT * FROM mcp_servers WHERE source = ? ORDER BY created_at ASC`).all(source) as McpServerRow[];
|
|
79
|
+
},
|
|
80
|
+
|
|
81
|
+
insert(input: McpServerInput): McpServerRow {
|
|
82
|
+
const db = getDatabase();
|
|
83
|
+
const result = db.prepare(
|
|
84
|
+
`INSERT INTO mcp_servers
|
|
85
|
+
(slug, name, description, registry_name, version, transport, command, args, env, url, headers, source)
|
|
86
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
|
87
|
+
).run(
|
|
88
|
+
input.slug,
|
|
89
|
+
input.name,
|
|
90
|
+
input.description ?? null,
|
|
91
|
+
input.registryName ?? null,
|
|
92
|
+
input.version ?? null,
|
|
93
|
+
input.transport,
|
|
94
|
+
input.command ?? null,
|
|
95
|
+
JSON.stringify(input.args ?? []),
|
|
96
|
+
JSON.stringify(input.env ?? {}),
|
|
97
|
+
input.url ?? null,
|
|
98
|
+
JSON.stringify(input.headers ?? {}),
|
|
99
|
+
input.source ?? 'registry'
|
|
100
|
+
) as { lastInsertRowid: number | bigint };
|
|
101
|
+
const id = Number(result.lastInsertRowid);
|
|
102
|
+
return this.getById(id)!;
|
|
103
|
+
},
|
|
104
|
+
|
|
105
|
+
setEnabled(id: number, enabled: boolean): void {
|
|
106
|
+
const db = getDatabase();
|
|
107
|
+
db.prepare(`UPDATE mcp_servers SET is_enabled = ? WHERE id = ?`).run(enabled ? 1 : 0, id);
|
|
108
|
+
},
|
|
109
|
+
|
|
110
|
+
/** Update the stored env (e.g. user-provided API keys) for a server. */
|
|
111
|
+
updateEnv(id: number, env: Record<string, string>): void {
|
|
112
|
+
const db = getDatabase();
|
|
113
|
+
db.prepare(`UPDATE mcp_servers SET env = ? WHERE id = ?`).run(JSON.stringify(env), id);
|
|
114
|
+
},
|
|
115
|
+
|
|
116
|
+
/** Update both env (stdio) and headers (remote auth) for a server. */
|
|
117
|
+
updateConfig(id: number, env: Record<string, string>, headers: Record<string, string>): void {
|
|
118
|
+
const db = getDatabase();
|
|
119
|
+
db.prepare(`UPDATE mcp_servers SET env = ?, headers = ? WHERE id = ?`).run(
|
|
120
|
+
JSON.stringify(env),
|
|
121
|
+
JSON.stringify(headers),
|
|
122
|
+
id
|
|
123
|
+
);
|
|
124
|
+
},
|
|
125
|
+
|
|
126
|
+
remove(id: number): void {
|
|
127
|
+
const db = getDatabase();
|
|
128
|
+
db.prepare(`DELETE FROM mcp_servers WHERE id = ?`).run(id);
|
|
129
|
+
},
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Insert or refresh an INTERNAL (code-defined) server row.
|
|
133
|
+
*
|
|
134
|
+
* Internal servers are defined in `backend/mcp/internal/servers/` — the DB
|
|
135
|
+
* row is only a mirror used for listing + the enable/disable toggle. On
|
|
136
|
+
* update we refresh the display metadata (title/description/version) but
|
|
137
|
+
* PRESERVE `is_enabled` so the user's toggle survives restarts. New rows
|
|
138
|
+
* default to enabled and `stdio` transport (they run in-process / via the
|
|
139
|
+
* `/mcp` bridge, surfaced to the user as "local (stdio)").
|
|
140
|
+
*/
|
|
141
|
+
upsertInternal(input: { slug: string; name: string; description: string | null; version: string }): McpServerRow {
|
|
142
|
+
const db = getDatabase();
|
|
143
|
+
const existing = this.getBySlug(input.slug);
|
|
144
|
+
if (existing) {
|
|
145
|
+
db.prepare(
|
|
146
|
+
`UPDATE mcp_servers SET name = ?, description = ?, version = ?, transport = 'stdio', source = 'internal' WHERE slug = ?`
|
|
147
|
+
).run(input.name, input.description, input.version, input.slug);
|
|
148
|
+
return this.getBySlug(input.slug)!;
|
|
149
|
+
}
|
|
150
|
+
db.prepare(
|
|
151
|
+
`INSERT INTO mcp_servers (slug, name, description, version, transport, source, is_enabled)
|
|
152
|
+
VALUES (?, ?, ?, ?, 'stdio', 'internal', 1)`
|
|
153
|
+
).run(input.slug, input.name, input.description, input.version);
|
|
154
|
+
return this.getBySlug(input.slug)!;
|
|
155
|
+
},
|
|
156
|
+
|
|
157
|
+
/** Remove internal rows whose code definition no longer exists (keeps the slugs in `keep`). */
|
|
158
|
+
pruneInternalExcept(keep: string[]): void {
|
|
159
|
+
const db = getDatabase();
|
|
160
|
+
const rows = this.getBySource('internal');
|
|
161
|
+
const keepSet = new Set(keep);
|
|
162
|
+
for (const row of rows) {
|
|
163
|
+
if (!keepSet.has(row.slug)) db.prepare(`DELETE FROM mcp_servers WHERE id = ?`).run(row.id);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
};
|
package/backend/engine/README.md
CHANGED
|
@@ -97,13 +97,13 @@ Three key rules that **every** layer upholds:
|
|
|
97
97
|
> Two design pitfalls have repeatedly tripped people adding new adapters.
|
|
98
98
|
> Before sketching architecture, double-check:
|
|
99
99
|
>
|
|
100
|
-
> 1. **MCP over HTTP already exists.** `backend/mcp/remote-server.ts` mounts
|
|
100
|
+
> 1. **MCP over HTTP already exists.** `backend/mcp/internal/remote-server.ts` mounts
|
|
101
101
|
> every `defineServer()`-registered MCP server as a Streamable HTTP
|
|
102
102
|
> endpoint at `http://localhost:<port>/mcp`. OpenCode consumes it via
|
|
103
103
|
> `getOpenCodeMcpConfig()`. Any engine whose CLI/SDK accepts a
|
|
104
104
|
> `streamable-http` MCP URL (Codex, future engines) reuses **the same
|
|
105
105
|
> URL** by adding a sibling `getXxxMcpConfig()` helper in
|
|
106
|
-
> `backend/mcp/config.ts`. Do **NOT** propose a "new MCP bridge",
|
|
106
|
+
> `backend/mcp/internal/config.ts`. Do **NOT** propose a "new MCP bridge",
|
|
107
107
|
> "per-engine MCP server", or "per-stream MCP path". See §9.12.
|
|
108
108
|
> 2. **Shared CLI dotfiles are swapped from DB, not isolated.** When a CLI
|
|
109
109
|
> stores its credentials in a known location (e.g. `~/.codex/auth.json`),
|
|
@@ -75,7 +75,7 @@ import type {
|
|
|
75
75
|
ThreadStartedEvent,
|
|
76
76
|
TurnCompletedEvent,
|
|
77
77
|
} from '@openai/codex-sdk';
|
|
78
|
-
import { resolveOpenCodeToolName } from '../../../mcp
|
|
78
|
+
import { resolveOpenCodeToolName } from '../../../mcp';
|
|
79
79
|
import { readLastTokenUsageFromRollout } from './usage-rollout';
|
|
80
80
|
import { readApplyPatchesFromRollout, findMatchingPatch } from './patch-rollout';
|
|
81
81
|
|
|
@@ -26,7 +26,7 @@ import { extractJson } from '../../structured-helpers';
|
|
|
26
26
|
import { engineQueries } from '$backend/database/queries/engine-queries';
|
|
27
27
|
import { resolveOsPath } from '$backend/utils/paths';
|
|
28
28
|
import { resolveBinary } from '$backend/utils/cli';
|
|
29
|
-
import { getCodexMcpConfig } from '../../../mcp
|
|
29
|
+
import { getCodexMcpConfig } from '../../../mcp';
|
|
30
30
|
import { CODEX_MODELS } from './models';
|
|
31
31
|
import { debug } from '$shared/utils/logger';
|
|
32
32
|
import { handleStreamError, buildTurnError } from './error-handler';
|
|
@@ -49,7 +49,7 @@ import type {
|
|
|
49
49
|
} from '$shared/types/unified';
|
|
50
50
|
import { toCanonicalToolName } from '$shared/types/unified';
|
|
51
51
|
import type { SessionEvent } from '@github/copilot-sdk';
|
|
52
|
-
import { resolveOpenCodeToolName } from '../../../mcp
|
|
52
|
+
import { resolveOpenCodeToolName } from '../../../mcp';
|
|
53
53
|
|
|
54
54
|
// Derive data payload types from the SessionEvent discriminated union so we
|
|
55
55
|
// don't depend on internal type re-exports that aren't part of the SDK's
|
|
@@ -20,7 +20,7 @@ import { buildJsonPrompt, extractJson } from '../../structured-helpers';
|
|
|
20
20
|
import { engineQueries } from '$backend/database/queries/engine-queries';
|
|
21
21
|
import { resolveOsPath } from '$backend/utils/paths';
|
|
22
22
|
import { debug } from '$shared/utils/logger';
|
|
23
|
-
import { getCopilotMcpConfig } from '../../../mcp
|
|
23
|
+
import { getCopilotMcpConfig } from '../../../mcp';
|
|
24
24
|
import { handleStreamError, buildSessionError } from './error-handler';
|
|
25
25
|
import { fetchCopilotModels } from './models';
|
|
26
26
|
|
|
@@ -51,7 +51,7 @@ import type {
|
|
|
51
51
|
AskUserQuestion,
|
|
52
52
|
} from '$shared/types/unified';
|
|
53
53
|
import { toCanonicalToolName } from '$shared/types/unified';
|
|
54
|
-
import { resolveOpenCodeToolName } from '../../../mcp
|
|
54
|
+
import { resolveOpenCodeToolName } from '../../../mcp';
|
|
55
55
|
|
|
56
56
|
// ============================================================
|
|
57
57
|
// Qwen-specific tool-result content markers
|
|
@@ -45,7 +45,7 @@ import { getEngineEnv } from './environment';
|
|
|
45
45
|
import { handleStreamError } from './error-handler';
|
|
46
46
|
import { createSdkMessageConverter, toSdkUserMessage, type SdkMessageConverter } from './message-converter';
|
|
47
47
|
import { fetchQwenModels } from './models';
|
|
48
|
-
import { getQwenMcpConfig } from '../../../mcp
|
|
48
|
+
import { getQwenMcpConfig } from '../../../mcp';
|
|
49
49
|
import { forkQwenSessionState, sessionStateExists } from './session-fork';
|
|
50
50
|
|
|
51
51
|
interface PendingAskUserQuestion {
|
|
@@ -122,8 +122,8 @@ calling `getEnabledMcpServers(options.mcpContext)`.
|
|
|
122
122
|
- ❌ Use `console.*` — use `debug` from `$shared/utils/logger` with
|
|
123
123
|
category `'engine'`, `'chat'`, or `'mcp'`.
|
|
124
124
|
- ❌ **Build a new MCP HTTP server for the adapter.** Use the existing
|
|
125
|
-
`backend/mcp/remote-server.ts` and add a `getXxxMcpConfig()` helper in
|
|
126
|
-
`backend/mcp/config.ts` returning the URL in the engine's expected
|
|
125
|
+
`backend/mcp/internal/remote-server.ts` and add a `getXxxMcpConfig()` helper in
|
|
126
|
+
`backend/mcp/internal/config.ts` returning the URL in the engine's expected
|
|
127
127
|
shape. New MCP servers are added via `defineServer()` — never via a
|
|
128
128
|
parallel HTTP listener.
|
|
129
129
|
- ❌ **Create per-account isolated home directories** to multiplex two
|
|
@@ -352,7 +352,7 @@ async dispose(): Promise<void> {
|
|
|
352
352
|
|
|
353
353
|
### 9.12 Reuse the existing MCP HTTP infrastructure — never build a new bridge
|
|
354
354
|
|
|
355
|
-
`backend/mcp/remote-server.ts` already mounts every server registered via
|
|
355
|
+
`backend/mcp/internal/remote-server.ts` already mounts every server registered via
|
|
356
356
|
`defineServer()` as a **Streamable HTTP MCP** endpoint at
|
|
357
357
|
`http://localhost:<port>/mcp`. OpenCode consumes it via
|
|
358
358
|
`getOpenCodeMcpConfig()`. Tool handlers run **in-process** in the Clopen
|
|
@@ -383,9 +383,9 @@ When you add an engine whose CLI/SDK accepts a streamable-http MCP URL
|
|
|
383
383
|
- In the adapter, name the local variable holding the helper's return
|
|
384
384
|
value **`mcpConfig`**, not `mcpServers`. The latter shadows both the
|
|
385
385
|
SDK's config field name AND the registry exported from
|
|
386
|
-
`backend/mcp/config.ts`, and reads as a bug at the call site.
|
|
386
|
+
`backend/mcp/internal/config.ts`, and reads as a bug at the call site.
|
|
387
387
|
|
|
388
|
-
2. Use `resolveOpenCodeToolName()` (in `backend/mcp/config.ts`) on
|
|
388
|
+
2. Use `resolveOpenCodeToolName()` (in `backend/mcp/internal/config.ts`) on
|
|
389
389
|
incoming tool names; it strips the `clopen-mcp_` / `clopen-mcp-`
|
|
390
390
|
prefix and reverse-maps to `mcp__<server>__<tool>`. The same helper
|
|
391
391
|
works for any engine that uses the same naming convention.
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
| Fork session (native vs. on-disk workaround) | `claude/stream.ts` (`forkSession: true`), `opencode/stream.ts` (`client.session.fork`), `copilot/stream.ts` (`client.rpc.sessions.fork`), `codex/session-fork.ts` + `qwen/session-fork.ts` (copy disk state) |
|
|
17
17
|
| Sub-agent (`Task`/`Agent`) routing | `claude/message-converter.ts` (`parent_tool_use_id`), `opencode/message-converter.ts::convertSubtaskToolUseOnly`, `copilot/message-converter.ts::resolveParentToolUseId` + `agentParentMap` (see §9.15) |
|
|
18
18
|
| AskUserQuestion event + HTTP fallback | `opencode/stream.ts::resolveUserAnswer`, `claude/stream.ts::canUseTool` |
|
|
19
|
-
| MCP servers exposed over HTTP (single source) | `backend/mcp/remote-server.ts`, `backend/mcp/config.ts::getOpenCodeMcpConfig` (and future `getXxxMcpConfig`) |
|
|
19
|
+
| MCP servers exposed over HTTP (single source) | `backend/mcp/internal/remote-server.ts`, `backend/mcp/internal/config.ts::getOpenCodeMcpConfig` (and future `getXxxMcpConfig`) |
|
|
20
20
|
| Auth-blob swap into shared CLI dotfile | Pattern only (no implementation yet); see §3.3 callout + §9.13 |
|
|
21
21
|
| Restart-Server pattern (long-lived engines) | `backend/ws/engine/opencode/providers.ts::engine:opencode-server-restart`, `frontend/components/chat/input/components/EngineModelPicker.svelte::restartOCServer`, `AIEnginesSettings.svelte::handleRestartServer`/`forceRestartServer` |
|
|
22
22
|
| `generateStructured` (no tools, JSON) | `claude/stream.ts::generateStructured` (native `outputFormat`), `codex/stream.ts::generateStructured` (native `outputSchema`), `opencode/stream.ts::generateStructured` + `copilot/stream.ts::generateStructured` + `qwen/stream.ts::generateStructured` (prompt-engineered via `backend/engine/structured-helpers.ts`). See §9.16 for the strict-schema + part-fallback gotchas. |
|
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,7 +40,7 @@ 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';
|
|
@@ -163,6 +164,9 @@ async function startServer() {
|
|
|
163
164
|
try {
|
|
164
165
|
await initializeDatabase();
|
|
165
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();
|
|
166
170
|
// Start expired session cleanup now that the database is ready
|
|
167
171
|
sessionCleanupScheduler.start();
|
|
168
172
|
uploadTempCleanup.start();
|
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
|
|