@myrialabs/clopen 0.4.5 → 0.4.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backend/auth/permissions.ts +14 -1
- package/backend/auth/session-invalidation.test.ts +17 -21
- package/backend/auth/session-invalidation.ts +10 -11
- package/backend/database/migrations/044_create_skills_table.ts +29 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/index.ts +3 -1
- package/backend/database/queries/skill-queries.ts +105 -0
- package/backend/engine/adapters/claude/models.ts +46 -3
- package/backend/engine/adapters/claude/stream.ts +5 -0
- package/backend/engine/adapters/codex/credential.ts +114 -13
- package/backend/engine/adapters/codex/stream.ts +34 -8
- package/backend/engine/adapters/copilot/stream.ts +4 -0
- package/backend/engine/adapters/opencode/stream.ts +4 -0
- package/backend/engine/adapters/qwen/stream.ts +3 -0
- package/backend/engine/docs/lessons-learned.md +54 -50
- package/backend/files/file-archive.test.ts +86 -26
- package/backend/files/file-archive.ts +214 -134
- package/backend/index.ts +10 -1
- package/backend/mcp/README.md +77 -24
- package/backend/mcp/external/config.ts +82 -101
- package/backend/mcp/external/proxy.ts +202 -0
- package/backend/mcp/index.ts +4 -3
- package/backend/mcp/internal/remote-server.ts +103 -55
- package/backend/skills/index.ts +21 -0
- package/backend/skills/marketplace.ts +172 -0
- package/backend/skills/service.ts +245 -0
- package/backend/skills/spec.ts +214 -0
- package/backend/skills/store.ts +99 -0
- package/backend/skills/sync.ts +187 -0
- package/backend/terminal/index.ts +2 -5
- package/backend/terminal/ptykit.ts +64 -0
- package/backend/tunnel/tunnel-config.ts +1 -1
- package/backend/utils/ws.ts +14 -0
- package/backend/ws/files/write.ts +23 -7
- package/backend/ws/index.ts +5 -1
- package/backend/ws/projects/crud.ts +4 -4
- package/backend/ws/skills/catalog.ts +79 -0
- package/backend/ws/skills/crud.ts +123 -0
- package/backend/ws/skills/index.ts +15 -0
- package/backend/ws/system/operations.ts +23 -0
- package/backend/ws/terminal/index.ts +6 -33
- package/backend/ws/terminal/tunnel.ts +76 -0
- package/dist/assets/index-xrB3zcfA.js +1 -0
- package/dist/assets/main-BXS8bjJ6.css +1 -0
- package/dist/assets/{main-zXKH_C5O.js → main-LBI3a0n5.js} +304 -261
- package/dist/index.html +2 -2
- package/package.json +7 -11
- package/shared/constants/engines.ts +4 -4
- package/shared/utils/logger.ts +1 -0
- package/backend/terminal/helpers.ts +0 -14
- package/backend/terminal/pty-manager.ts +0 -4
- package/backend/terminal/pty-session-manager.ts +0 -349
- package/backend/terminal/stream-manager.ts +0 -300
- package/backend/ws/terminal/access.ts +0 -56
- package/backend/ws/terminal/persistence.ts +0 -145
- package/backend/ws/terminal/session.ts +0 -470
- package/backend/ws/terminal/stream.ts +0 -82
- package/dist/assets/main-gNUEJAC5.css +0 -1
|
@@ -1,42 +1,57 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* External MCP — per-engine config builders.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
4
|
+
* Every enabled external server is exposed to engines through Clopen's OWN
|
|
5
|
+
* Streamable-HTTP bridge at `/mcp/ext/<slug>` (see `./proxy.ts`), NOT by
|
|
6
|
+
* pointing the engine straight at the third-party stdio/HTTP server. Each
|
|
7
|
+
* server keeps its bare `<slug>` namespace (the `clopen` prefix is reserved
|
|
8
|
+
* for internal) — disjoint from the internal `clopen-mcp` bridge — so the two
|
|
9
|
+
* systems never collide.
|
|
9
10
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
11
|
+
* Routing through the bridge means every engine receives the IDENTICAL shape:
|
|
12
|
+
* a loopback remote URL plus the service-token header. The real upstream
|
|
13
|
+
* transport (stdio/http/sse) and its OAuth/API-key credential are handled once,
|
|
14
|
+
* inside the proxy — so a new engine adapter needs no per-transport branching,
|
|
15
|
+
* and engines are shielded from upstream servers whose tool schemas would
|
|
16
|
+
* otherwise crash their MCP client (see `./proxy.ts`).
|
|
17
|
+
*
|
|
18
|
+
* The facade (`backend/mcp/index.ts`) merges these with the internal config
|
|
19
|
+
* before handing them to an adapter.
|
|
13
20
|
*/
|
|
14
21
|
|
|
15
22
|
import type { McpServerConfig } from '@anthropic-ai/claude-agent-sdk';
|
|
16
|
-
import type {
|
|
17
|
-
import type {
|
|
23
|
+
import type { McpRemoteConfig } from '@opencode-ai/sdk';
|
|
24
|
+
import type { MCPHTTPServerConfig as CopilotMcpServerConfig } from '@github/copilot-sdk';
|
|
18
25
|
import type { CLIMcpServerConfig as QwenMcpServerConfig } from '@qwen-code/sdk';
|
|
19
26
|
import { debug } from '$shared/utils/logger';
|
|
20
27
|
import { mcpServerQueries } from '$backend/database/queries';
|
|
21
|
-
import { externalNamespace } from '../shared/constants';
|
|
28
|
+
import { externalNamespace, MCP_TOOL_CALL_TIMEOUT_MS } from '../shared/constants';
|
|
29
|
+
import { getMcpServiceToken } from '../internal/service-token';
|
|
30
|
+
import { SERVER_ENV } from '../../utils/env';
|
|
22
31
|
import type { McpServerRow } from '$backend/database/queries';
|
|
23
32
|
import type { ResolvedExternalServer } from './types';
|
|
24
33
|
|
|
25
|
-
/**
|
|
34
|
+
/**
|
|
35
|
+
* Codex `mcp_servers.<name>` config, flattened by the SDK to `--config` flags.
|
|
36
|
+
* Each external server is a Streamable-HTTP remote pointing at our bridge;
|
|
37
|
+
* `http_headers` carries the service-token bearer (Codex rejects an inline
|
|
38
|
+
* `bearer_token` for `streamable_http`).
|
|
39
|
+
*/
|
|
26
40
|
type CodexMcpServerConfig = {
|
|
27
|
-
|
|
28
|
-
args?: string[];
|
|
29
|
-
env?: Record<string, string>;
|
|
30
|
-
url?: string;
|
|
31
|
-
/**
|
|
32
|
-
* Streamable-HTTP auth headers. Codex rejects an inline `bearer_token` for
|
|
33
|
-
* streamable_http but accepts an `http_headers` table (the same field the
|
|
34
|
-
* internal `clopen-mcp` bridge uses), so the centrally-managed
|
|
35
|
-
* `Authorization: Bearer …` and any static API-key headers reach Codex.
|
|
36
|
-
*/
|
|
41
|
+
url: string;
|
|
37
42
|
http_headers?: Record<string, string>;
|
|
38
43
|
};
|
|
39
44
|
|
|
45
|
+
/** Loopback URL of the per-server external proxy bridge for `slug`. */
|
|
46
|
+
function bridgeUrl(slug: string): string {
|
|
47
|
+
return `http://localhost:${SERVER_ENV.PORT}/mcp/ext/${slug}`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The service-token bearer header every engine→bridge hop carries. */
|
|
51
|
+
function serviceAuthHeaders(): Record<string, string> {
|
|
52
|
+
return { Authorization: `Bearer ${getMcpServiceToken()}` };
|
|
53
|
+
}
|
|
54
|
+
|
|
40
55
|
function parseJson<T>(raw: string, fallback: T): T {
|
|
41
56
|
try {
|
|
42
57
|
return JSON.parse(raw) as T;
|
|
@@ -96,124 +111,90 @@ export function remoteNeedsOAuth(s: ResolvedExternalServer): boolean {
|
|
|
96
111
|
&& Object.keys(s.headers).length === 0;
|
|
97
112
|
}
|
|
98
113
|
|
|
99
|
-
/** Qwen OAuth fields for a credential-less remote (dynamic discovery). */
|
|
100
|
-
function remoteAuthQwen(s: ResolvedExternalServer): Partial<QwenMcpServerConfig> {
|
|
101
|
-
if (!remoteNeedsOAuth(s)) return {};
|
|
102
|
-
return { oauth: { enabled: true }, authProviderType: 'dynamic_discovery' };
|
|
103
|
-
}
|
|
104
|
-
|
|
105
114
|
// ---------------------------------------------------------------------------
|
|
106
115
|
// Per-engine builders
|
|
116
|
+
//
|
|
117
|
+
// Every external server, regardless of its real transport, is emitted as a
|
|
118
|
+
// Streamable-HTTP remote pointing at our `/mcp/ext/<slug>` proxy. The only
|
|
119
|
+
// per-engine difference is the SDK's config shape (field names) — the URL,
|
|
120
|
+
// namespace key, and service-token header are identical. The upstream
|
|
121
|
+
// transport + credential live inside the proxy (see ./proxy.ts).
|
|
107
122
|
// ---------------------------------------------------------------------------
|
|
108
123
|
|
|
109
|
-
/** Claude Agent SDK:
|
|
124
|
+
/** Claude Agent SDK: Streamable-HTTP remote keyed by namespace. */
|
|
110
125
|
export function getClaudeExternalMcpConfig(): Record<string, McpServerConfig> {
|
|
111
126
|
const out: Record<string, McpServerConfig> = {};
|
|
112
127
|
for (const s of getEnabledExternalServers()) {
|
|
113
|
-
|
|
114
|
-
out[s.namespace] = { type: 'stdio', command: s.command, args: s.args, env: s.env };
|
|
115
|
-
} else if ((s.transport === 'http' || s.transport === 'sse') && s.url) {
|
|
116
|
-
out[s.namespace] = {
|
|
117
|
-
type: s.transport,
|
|
118
|
-
url: s.url,
|
|
119
|
-
...(Object.keys(s.headers).length > 0 ? { headers: s.headers } : {})
|
|
120
|
-
};
|
|
121
|
-
}
|
|
128
|
+
out[s.namespace] = { type: 'http', url: bridgeUrl(s.slug), headers: serviceAuthHeaders() };
|
|
122
129
|
}
|
|
123
130
|
logBuilt('Claude', out);
|
|
124
131
|
return out;
|
|
125
132
|
}
|
|
126
133
|
|
|
127
|
-
/** Open Code: `
|
|
128
|
-
export function getOpenCodeExternalMcpConfig(): Record<string,
|
|
129
|
-
const out: Record<string,
|
|
134
|
+
/** Open Code: `McpRemoteConfig` pointing at the bridge proxy. */
|
|
135
|
+
export function getOpenCodeExternalMcpConfig(): Record<string, McpRemoteConfig> {
|
|
136
|
+
const out: Record<string, McpRemoteConfig> = {};
|
|
130
137
|
for (const s of getEnabledExternalServers()) {
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
} else if ((s.transport === 'http' || s.transport === 'sse') && s.url) {
|
|
139
|
-
// `oauth` is intentionally left unset: Open Code's default is OAuth
|
|
140
|
-
// auto-detection (set it to `false` only to opt out). Credential-less
|
|
141
|
-
// remotes therefore get the authorization handshake for free; the
|
|
142
|
-
// interactive sign-in is driven separately via the MCP auth flow.
|
|
143
|
-
out[s.namespace] = {
|
|
144
|
-
type: 'remote',
|
|
145
|
-
url: s.url,
|
|
146
|
-
enabled: true,
|
|
147
|
-
...(Object.keys(s.headers).length > 0 ? { headers: s.headers } : {})
|
|
148
|
-
};
|
|
149
|
-
}
|
|
138
|
+
out[s.namespace] = {
|
|
139
|
+
type: 'remote',
|
|
140
|
+
url: bridgeUrl(s.slug),
|
|
141
|
+
enabled: true,
|
|
142
|
+
timeout: MCP_TOOL_CALL_TIMEOUT_MS,
|
|
143
|
+
headers: serviceAuthHeaders()
|
|
144
|
+
};
|
|
150
145
|
}
|
|
151
146
|
logBuilt('Open Code', out);
|
|
152
147
|
return out;
|
|
153
148
|
}
|
|
154
149
|
|
|
155
150
|
/**
|
|
156
|
-
* Codex: `mcp_servers.<name
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
*
|
|
151
|
+
* Codex: `mcp_servers.<name>.url` pointing at the bridge proxy.
|
|
152
|
+
*
|
|
153
|
+
* Note: Codex still requires per-tool `approval_mode` to auto-approve in
|
|
154
|
+
* non-interactive `codex exec`, and external tool names aren't known when this
|
|
155
|
+
* synchronous builder runs — so external MCP tool calls may be cancelled there.
|
|
156
|
+
* The server is registered so interactive/known-tool flows work; this limit is
|
|
157
|
+
* unchanged by the proxy.
|
|
161
158
|
*/
|
|
162
159
|
export function getCodexExternalMcpConfig(): Record<string, CodexMcpServerConfig> {
|
|
163
160
|
const out: Record<string, CodexMcpServerConfig> = {};
|
|
164
161
|
for (const s of getEnabledExternalServers()) {
|
|
165
|
-
|
|
166
|
-
out[s.namespace] = {
|
|
167
|
-
command: s.command,
|
|
168
|
-
args: s.args,
|
|
169
|
-
...(Object.keys(s.env).length > 0 ? { env: s.env } : {})
|
|
170
|
-
};
|
|
171
|
-
} else if ((s.transport === 'http' || s.transport === 'sse') && s.url) {
|
|
172
|
-
// `http_headers` carries the injected OAuth bearer (and any static API
|
|
173
|
-
// key), matching the internal bridge — so Codex authenticates too.
|
|
174
|
-
out[s.namespace] = {
|
|
175
|
-
url: s.url,
|
|
176
|
-
...(Object.keys(s.headers).length > 0 ? { http_headers: s.headers } : {})
|
|
177
|
-
};
|
|
178
|
-
}
|
|
162
|
+
out[s.namespace] = { url: bridgeUrl(s.slug), http_headers: serviceAuthHeaders() };
|
|
179
163
|
}
|
|
180
164
|
logBuilt('Codex', out);
|
|
181
165
|
return out;
|
|
182
166
|
}
|
|
183
167
|
|
|
184
|
-
/** Copilot: `
|
|
168
|
+
/** Copilot: `MCPHTTPServerConfig` pointing at the bridge proxy. */
|
|
185
169
|
export function getCopilotExternalMcpConfig(): Record<string, CopilotMcpServerConfig> {
|
|
186
170
|
const out: Record<string, CopilotMcpServerConfig> = {};
|
|
187
171
|
for (const s of getEnabledExternalServers()) {
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
};
|
|
200
|
-
}
|
|
172
|
+
// `tools: ['*']` makes the Copilot runtime expose ALL of the proxy's
|
|
173
|
+
// tools. Leaving it unset relies on the SDK's documented "undefined =
|
|
174
|
+
// all" default, which the bundled CLI does not honour for dynamically
|
|
175
|
+
// discovered servers — the tools never reach the model.
|
|
176
|
+
out[s.namespace] = {
|
|
177
|
+
type: 'http',
|
|
178
|
+
url: bridgeUrl(s.slug),
|
|
179
|
+
tools: ['*'],
|
|
180
|
+
timeout: MCP_TOOL_CALL_TIMEOUT_MS,
|
|
181
|
+
headers: serviceAuthHeaders()
|
|
182
|
+
};
|
|
201
183
|
}
|
|
202
184
|
logBuilt('Copilot', out);
|
|
203
185
|
return out;
|
|
204
186
|
}
|
|
205
187
|
|
|
206
|
-
/** Qwen Code: `CLIMcpServerConfig`
|
|
188
|
+
/** Qwen Code: `CLIMcpServerConfig` Streamable-HTTP (`httpUrl`) at the bridge proxy. */
|
|
207
189
|
export function getQwenExternalMcpConfig(): Record<string, QwenMcpServerConfig> {
|
|
208
190
|
const out: Record<string, QwenMcpServerConfig> = {};
|
|
209
191
|
for (const s of getEnabledExternalServers()) {
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
}
|
|
192
|
+
out[s.namespace] = {
|
|
193
|
+
httpUrl: bridgeUrl(s.slug),
|
|
194
|
+
timeout: MCP_TOOL_CALL_TIMEOUT_MS,
|
|
195
|
+
trust: true,
|
|
196
|
+
headers: serviceAuthHeaders()
|
|
197
|
+
};
|
|
217
198
|
}
|
|
218
199
|
logBuilt('Qwen', out);
|
|
219
200
|
return out;
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* External MCP — in-process proxy through the `/mcp/ext/<slug>` bridge.
|
|
3
|
+
*
|
|
4
|
+
* Instead of pointing each engine straight at a third-party MCP server (stdio
|
|
5
|
+
* subprocess or remote URL), Clopen connects to that server ITSELF as an MCP
|
|
6
|
+
* client and re-exposes its tools through a per-server endpoint on the same
|
|
7
|
+
* Streamable-HTTP bridge the internal `clopen-mcp` tools already use. The
|
|
8
|
+
* engine then talks only to Clopen (loopback + service token).
|
|
9
|
+
*
|
|
10
|
+
* Why proxy at all? Because Clopen owns the upstream client, it can:
|
|
11
|
+
* 1. Read `tools/list` with a RAW JSON-RPC request — bypassing the MCP SDK's
|
|
12
|
+
* `Client.listTools()` wrapper, which eagerly compiles an Ajv validator
|
|
13
|
+
* for every tool's `outputSchema`. A single unresolvable `$ref` (e.g.
|
|
14
|
+
* stitch's `#/$defs/ScreenInstance`) makes that wrapper throw, and the
|
|
15
|
+
* engine CLIs' `discoverTools` swallow the error and surface ZERO tools —
|
|
16
|
+
* so a "connected" server silently advertises nothing.
|
|
17
|
+
* 2. Sanitize each tool before re-exposing it: drop the crash-prone
|
|
18
|
+
* `outputSchema` and strip dangling `$ref`s from `inputSchema`.
|
|
19
|
+
* 3. Inject the centrally-managed OAuth bearer / static API key once, on the
|
|
20
|
+
* upstream hop — the engine→bridge hop only carries the service token.
|
|
21
|
+
*
|
|
22
|
+
* Net effect: external MCP servers behave identically on EVERY engine, and a
|
|
23
|
+
* server with invalid tool schemas degrades to "valid tools still work"
|
|
24
|
+
* instead of "whole server disappears".
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
28
|
+
import { StdioClientTransport, getDefaultEnvironment } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
29
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
30
|
+
import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
|
|
31
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
32
|
+
import {
|
|
33
|
+
ListToolsRequestSchema,
|
|
34
|
+
CallToolRequestSchema,
|
|
35
|
+
ListToolsResultSchema,
|
|
36
|
+
CompatibilityCallToolResultSchema,
|
|
37
|
+
type Tool
|
|
38
|
+
} from '@modelcontextprotocol/sdk/types.js';
|
|
39
|
+
import { debug } from '$shared/utils/logger';
|
|
40
|
+
import { mcpServerQueries } from '$backend/database/queries';
|
|
41
|
+
import { resolveServerRow } from './config';
|
|
42
|
+
import type { ResolvedExternalServer } from './types';
|
|
43
|
+
|
|
44
|
+
/** Cap on how long we wait for an upstream server to complete its handshake. */
|
|
45
|
+
const UPSTREAM_CONNECT_TIMEOUT_MS = 30_000;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Open an MCP client connection to a single upstream external server (stdio
|
|
49
|
+
* subprocess or remote HTTP/SSE). OAuth/API-key headers come from
|
|
50
|
+
* `resolveServerRow`, which injects the Clopen-managed bearer.
|
|
51
|
+
*/
|
|
52
|
+
async function connectUpstream(s: ResolvedExternalServer): Promise<Client> {
|
|
53
|
+
const client = new Client({ name: 'clopen-proxy', version: '1.0.0' }, { capabilities: {} });
|
|
54
|
+
|
|
55
|
+
if (s.transport === 'stdio') {
|
|
56
|
+
if (!s.command) throw new Error(`External server "${s.slug}" is stdio but has no command`);
|
|
57
|
+
// Merge over the SDK's safe default env (PATH, HOME, …) so `npx`/`uvx`
|
|
58
|
+
// resolve — passing only `s.env` would strip the inherited PATH.
|
|
59
|
+
const transport = new StdioClientTransport({
|
|
60
|
+
command: s.command,
|
|
61
|
+
args: s.args,
|
|
62
|
+
env: { ...getDefaultEnvironment(), ...s.env },
|
|
63
|
+
stderr: 'ignore'
|
|
64
|
+
});
|
|
65
|
+
await client.connect(transport, { timeout: UPSTREAM_CONNECT_TIMEOUT_MS });
|
|
66
|
+
return client;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (!s.url) throw new Error(`External server "${s.slug}" is ${s.transport} but has no URL`);
|
|
70
|
+
const url = new URL(s.url);
|
|
71
|
+
const requestInit = Object.keys(s.headers).length > 0 ? { headers: s.headers } : undefined;
|
|
72
|
+
const transport = s.transport === 'sse'
|
|
73
|
+
? new SSEClientTransport(url, { requestInit })
|
|
74
|
+
: new StreamableHTTPClientTransport(url, { requestInit });
|
|
75
|
+
await client.connect(transport, { timeout: UPSTREAM_CONNECT_TIMEOUT_MS });
|
|
76
|
+
return client;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Strip every `$ref` that points at a `$defs`/`definitions` entry the schema
|
|
81
|
+
* doesn't actually declare. Such dangling refs are what make a downstream
|
|
82
|
+
* Ajv `compile()` throw `MissingRefError`; replacing the offending node with an
|
|
83
|
+
* empty (permissive) schema keeps the rest of the shape intact and validatable.
|
|
84
|
+
*
|
|
85
|
+
* Best-effort and shallow on cost: walks the tree once, mutating a deep clone.
|
|
86
|
+
*/
|
|
87
|
+
function repairSchema<T>(schema: T): T {
|
|
88
|
+
if (schema == null || typeof schema !== 'object') return schema;
|
|
89
|
+
const root = schema as Record<string, unknown>;
|
|
90
|
+
|
|
91
|
+
const defs = new Set<string>();
|
|
92
|
+
for (const key of ['$defs', 'definitions'] as const) {
|
|
93
|
+
const bucket = root[key];
|
|
94
|
+
if (bucket && typeof bucket === 'object') {
|
|
95
|
+
for (const name of Object.keys(bucket as Record<string, unknown>)) defs.add(`${key}/${name}`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const walk = (node: unknown): unknown => {
|
|
100
|
+
if (Array.isArray(node)) return node.map(walk);
|
|
101
|
+
if (node && typeof node === 'object') {
|
|
102
|
+
const obj = node as Record<string, unknown>;
|
|
103
|
+
const ref = obj.$ref;
|
|
104
|
+
if (typeof ref === 'string' && ref.startsWith('#/')) {
|
|
105
|
+
const target = ref.slice(2); // strip "#/"
|
|
106
|
+
if (!defs.has(target)) {
|
|
107
|
+
// Dangling local ref → drop it, leaving any sibling keywords.
|
|
108
|
+
const { $ref, ...rest } = obj;
|
|
109
|
+
void $ref;
|
|
110
|
+
return walk(rest);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
const out: Record<string, unknown> = {};
|
|
114
|
+
for (const [k, v] of Object.entries(obj)) out[k] = walk(v);
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
return node;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
return walk(root) as T;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Re-expose an upstream tool to engines: keep its identity + input schema,
|
|
125
|
+
* repair dangling `$ref`s, and DROP `outputSchema` entirely. `outputSchema` is
|
|
126
|
+
* the field whose unresolvable `$ref`s crash the engines' eager Ajv
|
|
127
|
+
* compilation, and non-Claude engines don't rely on it — dropping it is the
|
|
128
|
+
* safest way to make every server's tools usable.
|
|
129
|
+
*/
|
|
130
|
+
function sanitizeTool(t: Tool): Tool {
|
|
131
|
+
const { outputSchema: _drop, inputSchema, ...rest } = t;
|
|
132
|
+
void _drop;
|
|
133
|
+
return {
|
|
134
|
+
...rest,
|
|
135
|
+
inputSchema: repairSchema(inputSchema ?? { type: 'object' as const })
|
|
136
|
+
} as Tool;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Read every page of an upstream `tools/list` via RAW requests (no Ajv caching). */
|
|
140
|
+
async function listAllToolsRaw(client: Client): Promise<Tool[]> {
|
|
141
|
+
const tools: Tool[] = [];
|
|
142
|
+
let cursor: string | undefined;
|
|
143
|
+
do {
|
|
144
|
+
const res = await client.request(
|
|
145
|
+
{ method: 'tools/list', params: cursor ? { cursor } : {} },
|
|
146
|
+
ListToolsResultSchema
|
|
147
|
+
);
|
|
148
|
+
tools.push(...res.tools);
|
|
149
|
+
cursor = res.nextCursor;
|
|
150
|
+
} while (cursor);
|
|
151
|
+
return tools;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** A bound proxy server plus the cleanup that tears down its upstream client. */
|
|
155
|
+
export interface ExternalProxy {
|
|
156
|
+
server: Server;
|
|
157
|
+
close: () => Promise<void>;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Build a low-level MCP `Server` that proxies one external server identified by
|
|
162
|
+
* `slug`. `tools/list` returns the upstream's sanitized tools; `tools/call`
|
|
163
|
+
* forwards verbatim. Throws if the slug isn't an enabled external server or the
|
|
164
|
+
* upstream handshake fails (the caller surfaces this as a per-server failure,
|
|
165
|
+
* never taking down the whole bridge).
|
|
166
|
+
*/
|
|
167
|
+
export async function createExternalProxyServer(slug: string): Promise<ExternalProxy> {
|
|
168
|
+
const row = mcpServerQueries.getBySlug(slug);
|
|
169
|
+
if (!row || row.source === 'internal') throw new Error(`Unknown external MCP server: ${slug}`);
|
|
170
|
+
if (row.is_enabled !== 1) throw new Error(`External MCP server is disabled: ${slug}`);
|
|
171
|
+
|
|
172
|
+
const resolved = resolveServerRow(row);
|
|
173
|
+
const client = await connectUpstream(resolved);
|
|
174
|
+
|
|
175
|
+
const server = new Server(
|
|
176
|
+
{ name: `clopen-ext-${slug}`, version: '1.0.0' },
|
|
177
|
+
{ capabilities: { tools: {} } }
|
|
178
|
+
);
|
|
179
|
+
|
|
180
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
181
|
+
const tools = (await listAllToolsRaw(client)).map(sanitizeTool);
|
|
182
|
+
debug.log('mcp', `🔌 Proxy ${slug}: serving ${tools.length} tool(s)`);
|
|
183
|
+
return { tools };
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
187
|
+
// Forward verbatim. CompatibilityCallToolResultSchema tolerates both the
|
|
188
|
+
// modern and 2024-10-07 result shapes; we never cached an output
|
|
189
|
+
// validator (we bypass listTools), so no schema check runs here.
|
|
190
|
+
return await client.request(
|
|
191
|
+
{ method: 'tools/call', params: req.params },
|
|
192
|
+
CompatibilityCallToolResultSchema
|
|
193
|
+
);
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
const close = async () => {
|
|
197
|
+
try { await client.close(); }
|
|
198
|
+
catch (error) { debug.warn('mcp', `Proxy ${slug}: error closing upstream client:`, error); }
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
return { server, close };
|
|
202
|
+
}
|
package/backend/mcp/index.ts
CHANGED
|
@@ -10,7 +10,8 @@
|
|
|
10
10
|
* through the `/mcp` remote bridge (namespace `clopen-mcp`).
|
|
11
11
|
* - EXTERNAL (`./external`) — servers the user installs from the official
|
|
12
12
|
* MCP registry, stored in the `mcp_servers` table. Each occupies its own
|
|
13
|
-
* `<slug>` namespace and is
|
|
13
|
+
* `<slug>` namespace and is proxied through the `/mcp/ext/<slug>` bridge
|
|
14
|
+
* (`./external/proxy.ts`) — the engine talks to Clopen, not the upstream.
|
|
14
15
|
*
|
|
15
16
|
* Adapters call `getEnabledMcpServers()` / `getXxxMcpConfig()` /
|
|
16
17
|
* `resolveOpenCodeToolName()` here and receive the COMBINED view. The internal
|
|
@@ -57,8 +58,8 @@ export {
|
|
|
57
58
|
// Internal server implementations + registries
|
|
58
59
|
export * from './internal/servers';
|
|
59
60
|
|
|
60
|
-
// Remote MCP HTTP bridge (serves internal tools to non-Claude engines)
|
|
61
|
-
export { handleMcpRequest, closeMcpServer } from './internal/remote-server';
|
|
61
|
+
// Remote MCP HTTP bridge (serves internal tools + external proxies to non-Claude engines)
|
|
62
|
+
export { handleMcpRequest, handleExternalMcpRequest, closeMcpServer } from './internal/remote-server';
|
|
62
63
|
|
|
63
64
|
// Project context service for MCP tool handlers
|
|
64
65
|
export { projectContextService } from './internal/project-context';
|