@myrialabs/clopen 0.4.4 → 0.4.6
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 +15 -1
- 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/stream.ts +5 -0
- package/backend/engine/adapters/codex/credential.ts +120 -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/git/git-service.ts +40 -0
- 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/parse.test.ts +190 -0
- package/backend/mcp/external/parse.ts +293 -0
- package/backend/mcp/external/proxy.ts +202 -0
- package/backend/mcp/index.ts +6 -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/snapshot/gitignore.ts +230 -7
- package/backend/snapshot/helpers.ts +34 -10
- package/backend/ws/files/read.ts +10 -1
- package/backend/ws/git/branch-name.ts +20 -4
- package/backend/ws/git/branch.ts +66 -11
- package/backend/ws/git/commit-message.ts +18 -3
- package/backend/ws/git/commit.ts +50 -16
- package/backend/ws/git/conflict.ts +47 -5
- package/backend/ws/git/diff.ts +38 -4
- package/backend/ws/git/log.ts +22 -2
- package/backend/ws/git/remote.ts +82 -33
- package/backend/ws/git/staging.ts +39 -9
- package/backend/ws/git/status.ts +52 -0
- package/backend/ws/index.ts +5 -1
- package/backend/ws/mcp/crud.ts +30 -1
- 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/snapshot/timeline.ts +1 -1
- package/dist/assets/main-BkMrek4_.css +1 -0
- package/dist/assets/{main-AqTMkV9D.js → main-TYNK6Orl.js} +332 -295
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/git.ts +20 -0
- package/shared/utils/logger.ts +1 -0
- package/dist/assets/main-DJf71Zum.css +0 -1
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { parseMcpConfig } from './parse';
|
|
3
|
+
|
|
4
|
+
describe('parseMcpConfig', () => {
|
|
5
|
+
test('Claude Desktop / Cursor mcpServers stdio shape', () => {
|
|
6
|
+
const { servers, errors } = parseMcpConfig(JSON.stringify({
|
|
7
|
+
mcpServers: {
|
|
8
|
+
notion: {
|
|
9
|
+
command: 'npx',
|
|
10
|
+
args: ['-y', '@notionhq/notion-mcp-server'],
|
|
11
|
+
env: { NOTION_TOKEN: 'secret_abc123' }
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
}));
|
|
15
|
+
expect(errors).toEqual([]);
|
|
16
|
+
expect(servers).toHaveLength(1);
|
|
17
|
+
const s = servers[0];
|
|
18
|
+
expect(s.name).toBe('notion');
|
|
19
|
+
expect(s.transport).toBe('stdio');
|
|
20
|
+
expect(s.command).toBe('npx');
|
|
21
|
+
expect(s.args).toEqual(['-y', '@notionhq/notion-mcp-server']);
|
|
22
|
+
expect(s.fields).toEqual([
|
|
23
|
+
{ name: 'NOTION_TOKEN', kind: 'env', value: 'secret_abc123', isPlaceholder: false }
|
|
24
|
+
]);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test('Cursor remote mcpServers infers http from url', () => {
|
|
28
|
+
const { servers } = parseMcpConfig(JSON.stringify({
|
|
29
|
+
mcpServers: { linear: { url: 'https://mcp.linear.app/mcp' } }
|
|
30
|
+
}));
|
|
31
|
+
expect(servers[0].transport).toBe('http');
|
|
32
|
+
expect(servers[0].url).toBe('https://mcp.linear.app/mcp');
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test('url ending in /sse is inferred as sse', () => {
|
|
36
|
+
const { servers } = parseMcpConfig(JSON.stringify({
|
|
37
|
+
mcpServers: { x: { url: 'https://example.com/sse' } }
|
|
38
|
+
}));
|
|
39
|
+
expect(servers[0].transport).toBe('sse');
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test('VS Code servers block with explicit type and ${input:} placeholder', () => {
|
|
43
|
+
const { servers } = parseMcpConfig(JSON.stringify({
|
|
44
|
+
servers: {
|
|
45
|
+
github: {
|
|
46
|
+
type: 'http',
|
|
47
|
+
url: 'https://api.githubcopilot.com/mcp/',
|
|
48
|
+
headers: { Authorization: 'Bearer ${input:github_token}' }
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
inputs: [{ id: 'github_token', type: 'promptString' }]
|
|
52
|
+
}));
|
|
53
|
+
expect(servers).toHaveLength(1);
|
|
54
|
+
const s = servers[0];
|
|
55
|
+
expect(s.transport).toBe('http');
|
|
56
|
+
const field = s.fields.find(f => f.name === 'Authorization');
|
|
57
|
+
expect(field?.kind).toBe('header');
|
|
58
|
+
expect(field?.isPlaceholder).toBe(true);
|
|
59
|
+
expect(field?.value).toBe('');
|
|
60
|
+
expect(s.warnings.some(w => w.includes('${input:'))).toBe(true);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('OpenCode mcp block: command array, environment key, type local', () => {
|
|
64
|
+
const { servers } = parseMcpConfig(JSON.stringify({
|
|
65
|
+
mcp: {
|
|
66
|
+
'my-server': {
|
|
67
|
+
type: 'local',
|
|
68
|
+
command: ['npx', '-y', 'my-mcp', 'serve'],
|
|
69
|
+
environment: { API_KEY: 'live-key' },
|
|
70
|
+
enabled: true
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}));
|
|
74
|
+
const s = servers[0];
|
|
75
|
+
expect(s.transport).toBe('stdio');
|
|
76
|
+
expect(s.command).toBe('npx');
|
|
77
|
+
expect(s.args).toEqual(['-y', 'my-mcp', 'serve']);
|
|
78
|
+
expect(s.fields).toEqual([
|
|
79
|
+
{ name: 'API_KEY', kind: 'env', value: 'live-key', isPlaceholder: false }
|
|
80
|
+
]);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test('OpenCode remote type maps to http (switchable)', () => {
|
|
84
|
+
const { servers } = parseMcpConfig(JSON.stringify({
|
|
85
|
+
mcp: { remote: { type: 'remote', url: 'https://example.com/mcp', headers: { 'X-Key': 'v' } } }
|
|
86
|
+
}));
|
|
87
|
+
expect(servers[0].transport).toBe('http');
|
|
88
|
+
expect(servers[0].fields[0]).toEqual({ name: 'X-Key', kind: 'header', value: 'v', isPlaceholder: false });
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test('single unwrapped server object', () => {
|
|
92
|
+
const { servers } = parseMcpConfig(JSON.stringify({
|
|
93
|
+
command: 'uvx',
|
|
94
|
+
args: ['mcp-server-git']
|
|
95
|
+
}));
|
|
96
|
+
expect(servers).toHaveLength(1);
|
|
97
|
+
expect(servers[0].command).toBe('uvx');
|
|
98
|
+
expect(servers[0].transport).toBe('stdio');
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
test('bare name→config map with no wrapper', () => {
|
|
102
|
+
const { servers } = parseMcpConfig(JSON.stringify({
|
|
103
|
+
fs: { command: 'npx', args: ['-y', 'fs-mcp'] },
|
|
104
|
+
git: { command: 'uvx', args: ['git-mcp'] }
|
|
105
|
+
}));
|
|
106
|
+
expect(servers.map(s => s.name).sort()).toEqual(['fs', 'git']);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
test('multiple servers under mcpServers', () => {
|
|
110
|
+
const { servers } = parseMcpConfig(JSON.stringify({
|
|
111
|
+
mcpServers: {
|
|
112
|
+
a: { command: 'npx', args: ['a'] },
|
|
113
|
+
b: { url: 'https://b.example/mcp' }
|
|
114
|
+
}
|
|
115
|
+
}));
|
|
116
|
+
expect(servers).toHaveLength(2);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test('placeholder detection for common stand-ins', () => {
|
|
120
|
+
const { servers } = parseMcpConfig(JSON.stringify({
|
|
121
|
+
mcpServers: {
|
|
122
|
+
x: {
|
|
123
|
+
command: 'npx',
|
|
124
|
+
env: {
|
|
125
|
+
A: '<your-token>',
|
|
126
|
+
B: 'YOUR_API_KEY',
|
|
127
|
+
C: 'TOKEN_HERE',
|
|
128
|
+
D: '',
|
|
129
|
+
E: 'real-value'
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}));
|
|
134
|
+
const byName = Object.fromEntries(servers[0].fields.map(f => [f.name, f]));
|
|
135
|
+
expect(byName.A.isPlaceholder).toBe(true);
|
|
136
|
+
expect(byName.B.isPlaceholder).toBe(true);
|
|
137
|
+
expect(byName.C.isPlaceholder).toBe(true);
|
|
138
|
+
expect(byName.D.isPlaceholder).toBe(true);
|
|
139
|
+
expect(byName.E.isPlaceholder).toBe(false);
|
|
140
|
+
expect(byName.E.value).toBe('real-value');
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
test('serverUrl alias is recognised as a remote url', () => {
|
|
144
|
+
const { servers } = parseMcpConfig(JSON.stringify({
|
|
145
|
+
mcpServers: { ws: { serverUrl: 'https://ws.example/mcp' } }
|
|
146
|
+
}));
|
|
147
|
+
expect(servers[0].url).toBe('https://ws.example/mcp');
|
|
148
|
+
expect(servers[0].transport).toBe('http');
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test('JSONC: comments and trailing commas are tolerated', () => {
|
|
152
|
+
const jsonc = `{
|
|
153
|
+
// my servers
|
|
154
|
+
"mcpServers": {
|
|
155
|
+
"git": {
|
|
156
|
+
"command": "uvx",
|
|
157
|
+
"args": ["mcp-server-git"], /* git tools */
|
|
158
|
+
},
|
|
159
|
+
}
|
|
160
|
+
}`;
|
|
161
|
+
const { servers, errors } = parseMcpConfig(jsonc);
|
|
162
|
+
expect(errors).toEqual([]);
|
|
163
|
+
expect(servers[0].command).toBe('uvx');
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
test('invalid JSON returns an error, no servers', () => {
|
|
167
|
+
const { servers, errors } = parseMcpConfig('{ not json');
|
|
168
|
+
expect(servers).toHaveLength(0);
|
|
169
|
+
expect(errors[0]).toContain('Invalid JSON');
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
test('empty input returns a friendly error', () => {
|
|
173
|
+
const { servers, errors } = parseMcpConfig(' ');
|
|
174
|
+
expect(servers).toHaveLength(0);
|
|
175
|
+
expect(errors).toHaveLength(1);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
test('object with no server-shaped entries reports nothing found', () => {
|
|
179
|
+
const { servers, errors } = parseMcpConfig(JSON.stringify({ foo: 'bar', count: 3 }));
|
|
180
|
+
expect(servers).toHaveLength(0);
|
|
181
|
+
expect(errors[0]).toContain('No MCP server found');
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
test('slug is derived and never starts with reserved internal prefix', () => {
|
|
185
|
+
const { servers } = parseMcpConfig(JSON.stringify({
|
|
186
|
+
mcpServers: { 'Clopen Tools': { command: 'npx' } }
|
|
187
|
+
}));
|
|
188
|
+
expect(servers[0].slug.startsWith('clopen')).toBe(false);
|
|
189
|
+
});
|
|
190
|
+
});
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Manual MCP config parser.
|
|
3
|
+
*
|
|
4
|
+
* Users install MCP servers from product docs (Notion, Linear, Stitch, …) that
|
|
5
|
+
* publish a JSON snippet for ONE specific host — Claude Desktop, Cursor, VS
|
|
6
|
+
* Code, Windsurf, OpenCode — never for Clopen. There is no cross-tool standard,
|
|
7
|
+
* so this normaliser is deliberately tolerant: it accepts every common dialect
|
|
8
|
+
* and flattens each server into the shape Clopen's `mcp:install` stores. The UI
|
|
9
|
+
* shows the result for review before anything is persisted, so a best-effort
|
|
10
|
+
* guess (with `warnings`) beats rejecting an unfamiliar shape.
|
|
11
|
+
*
|
|
12
|
+
* Dialects handled:
|
|
13
|
+
* - `mcpServers` map — Claude Desktop / Cursor / Windsurf / Antigravity
|
|
14
|
+
* - `servers` map — VS Code (`type` field; `${input:…}` placeholders)
|
|
15
|
+
* - `mcp` map — OpenCode (`type: local|remote`, `command` array,
|
|
16
|
+
* `environment` instead of `env`)
|
|
17
|
+
* - a bare `name → config` map with no wrapper
|
|
18
|
+
* - a single server config object with no wrapper
|
|
19
|
+
*
|
|
20
|
+
* The input may be JSONC (comments + trailing commas), which VS Code emits.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { slugifyRegistryName } from '../shared/constants';
|
|
24
|
+
import type { McpTransport } from '$backend/database/queries';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* One env/header input flattened from a parsed server. `value` is the literal
|
|
28
|
+
* the snippet carried; `isPlaceholder` marks the obvious "fill me in" tokens
|
|
29
|
+
* (`<your-token>`, `${input:…}`, `YOUR_API_KEY`, blank) so the UI can require
|
|
30
|
+
* them before install instead of persisting a dud credential.
|
|
31
|
+
*/
|
|
32
|
+
export interface ParsedField {
|
|
33
|
+
name: string;
|
|
34
|
+
kind: 'env' | 'header';
|
|
35
|
+
value: string;
|
|
36
|
+
isPlaceholder: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** A single server normalised from pasted JSON, ready for review + install. */
|
|
40
|
+
export interface ParsedMcpServer {
|
|
41
|
+
/** Suggested display name (the map key, or derived for an unwrapped object). */
|
|
42
|
+
name: string;
|
|
43
|
+
/** Slug derived from the name; the backend re-slugifies and de-dupes on install. */
|
|
44
|
+
slug: string;
|
|
45
|
+
transport: McpTransport;
|
|
46
|
+
command?: string;
|
|
47
|
+
args: string[];
|
|
48
|
+
url?: string;
|
|
49
|
+
fields: ParsedField[];
|
|
50
|
+
/** Non-fatal notes surfaced in the preview (guessed transport, missing command, …). */
|
|
51
|
+
warnings: string[];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface ParseResult {
|
|
55
|
+
servers: ParsedMcpServer[];
|
|
56
|
+
/** Fatal problems (invalid JSON, nothing server-shaped) — empty on success. */
|
|
57
|
+
errors: string[];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// ---------------------------------------------------------------------------
|
|
61
|
+
// JSONC tolerance
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Strip `//` and block comments from a JSONC string without touching comment-
|
|
66
|
+
* like sequences inside string literals. Used as a fallback when strict
|
|
67
|
+
* `JSON.parse` fails — VS Code's `mcp.json` is JSONC.
|
|
68
|
+
*/
|
|
69
|
+
function stripJsonComments(input: string): string {
|
|
70
|
+
let out = '';
|
|
71
|
+
let inStr = false;
|
|
72
|
+
let strCh = '';
|
|
73
|
+
let inLine = false;
|
|
74
|
+
let inBlock = false;
|
|
75
|
+
for (let i = 0; i < input.length; i++) {
|
|
76
|
+
const c = input[i];
|
|
77
|
+
const n = input[i + 1];
|
|
78
|
+
if (inLine) {
|
|
79
|
+
if (c === '\n') { inLine = false; out += c; }
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (inBlock) {
|
|
83
|
+
if (c === '*' && n === '/') { inBlock = false; i++; }
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
if (inStr) {
|
|
87
|
+
out += c;
|
|
88
|
+
if (c === '\\') { out += input[i + 1] ?? ''; i++; continue; }
|
|
89
|
+
if (c === strCh) inStr = false;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (c === '"' || c === "'") { inStr = true; strCh = c; out += c; continue; }
|
|
93
|
+
if (c === '/' && n === '/') { inLine = true; i++; continue; }
|
|
94
|
+
if (c === '/' && n === '*') { inBlock = true; i++; continue; }
|
|
95
|
+
out += c;
|
|
96
|
+
}
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Parse JSON, retrying with comments + trailing commas stripped (JSONC). */
|
|
101
|
+
function relaxedParse(raw: string): unknown {
|
|
102
|
+
try {
|
|
103
|
+
return JSON.parse(raw);
|
|
104
|
+
} catch {
|
|
105
|
+
const cleaned = stripJsonComments(raw).replace(/,(\s*[}\]])/g, '$1');
|
|
106
|
+
return JSON.parse(cleaned);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ---------------------------------------------------------------------------
|
|
111
|
+
// Field helpers
|
|
112
|
+
// ---------------------------------------------------------------------------
|
|
113
|
+
|
|
114
|
+
function isPlainObject(v: unknown): v is Record<string, unknown> {
|
|
115
|
+
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function strOrUndef(v: unknown): string | undefined {
|
|
119
|
+
return typeof v === 'string' && v.trim() !== '' ? v : undefined;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Coerce an unknown into a `Record<string,string>`, dropping non-string values. */
|
|
123
|
+
function recordOfStrings(v: unknown): Record<string, string> {
|
|
124
|
+
if (!isPlainObject(v)) return {};
|
|
125
|
+
const out: Record<string, string> = {};
|
|
126
|
+
for (const [k, val] of Object.entries(v)) {
|
|
127
|
+
if (typeof val === 'string') out[k] = val;
|
|
128
|
+
else if (typeof val === 'number' || typeof val === 'boolean') out[k] = String(val);
|
|
129
|
+
}
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* True for values that are clearly stand-ins the user must replace — so the UI
|
|
135
|
+
* marks them required instead of installing a server that fails at connect time.
|
|
136
|
+
*/
|
|
137
|
+
function isPlaceholder(value: string): boolean {
|
|
138
|
+
const s = value.trim();
|
|
139
|
+
if (!s) return true;
|
|
140
|
+
if (/^<.*>$/.test(s)) return true; // <your-token>
|
|
141
|
+
if (/\$\{.*\}/.test(s)) return true; // ${input:api-key}, ${API_KEY}
|
|
142
|
+
if (/^(your|my)[_-]/i.test(s)) return true; // your_api_key
|
|
143
|
+
if (/_here$/i.test(s)) return true; // TOKEN_HERE
|
|
144
|
+
if (/^(x{3,}|changeme|replace[_-]?me|insert[_-].*|example|placeholder|todo|none)$/i.test(s)) return true;
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function fieldsFrom(map: Record<string, string>, kind: 'env' | 'header'): ParsedField[] {
|
|
149
|
+
return Object.entries(map).map(([name, value]) => ({
|
|
150
|
+
name,
|
|
151
|
+
kind,
|
|
152
|
+
value: isPlaceholder(value) ? '' : value,
|
|
153
|
+
isPlaceholder: isPlaceholder(value)
|
|
154
|
+
}));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ---------------------------------------------------------------------------
|
|
158
|
+
// Normalisation
|
|
159
|
+
// ---------------------------------------------------------------------------
|
|
160
|
+
|
|
161
|
+
/** Map an explicit `type` token (across dialects) to a Clopen transport. */
|
|
162
|
+
function transportFromType(typeRaw: string): McpTransport | undefined {
|
|
163
|
+
switch (typeRaw) {
|
|
164
|
+
case 'stdio':
|
|
165
|
+
case 'local':
|
|
166
|
+
return 'stdio';
|
|
167
|
+
case 'sse':
|
|
168
|
+
return 'sse';
|
|
169
|
+
case 'http':
|
|
170
|
+
case 'https':
|
|
171
|
+
case 'remote':
|
|
172
|
+
case 'streamable-http':
|
|
173
|
+
case 'streamable_http':
|
|
174
|
+
case 'streamablehttp':
|
|
175
|
+
return 'http';
|
|
176
|
+
default:
|
|
177
|
+
return undefined;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Normalise one raw server config object into a `ParsedMcpServer`, or null. */
|
|
182
|
+
function normalizeServer(name: string, raw: unknown): ParsedMcpServer | null {
|
|
183
|
+
if (!isPlainObject(raw)) return null;
|
|
184
|
+
const warnings: string[] = [];
|
|
185
|
+
|
|
186
|
+
// command: string (most dialects) or array (OpenCode: ["npx","-y","pkg"]).
|
|
187
|
+
let command: string | undefined;
|
|
188
|
+
let args: string[] = [];
|
|
189
|
+
const rawCommand = raw.command;
|
|
190
|
+
if (Array.isArray(rawCommand)) {
|
|
191
|
+
const parts = rawCommand.filter((x): x is string => typeof x === 'string');
|
|
192
|
+
command = parts[0];
|
|
193
|
+
args = parts.slice(1);
|
|
194
|
+
} else if (typeof rawCommand === 'string') {
|
|
195
|
+
command = rawCommand;
|
|
196
|
+
if (Array.isArray(raw.args)) args = raw.args.filter((x): x is string => typeof x === 'string');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const url = strOrUndef(raw.url) ?? strOrUndef(raw.serverUrl) ?? strOrUndef(raw.httpUrl);
|
|
200
|
+
const env = { ...recordOfStrings(raw.env), ...recordOfStrings(raw.environment) };
|
|
201
|
+
const headers = recordOfStrings(raw.headers);
|
|
202
|
+
|
|
203
|
+
// Transport: explicit `type` wins; otherwise infer from what's present.
|
|
204
|
+
const typeRaw = typeof raw.type === 'string' ? raw.type.toLowerCase() : undefined;
|
|
205
|
+
let transport = typeRaw ? transportFromType(typeRaw) : undefined;
|
|
206
|
+
const transportExplicit = transport !== undefined;
|
|
207
|
+
if (!transport) {
|
|
208
|
+
if (command) transport = 'stdio';
|
|
209
|
+
else if (url) transport = /\/sse(\/|$)/.test(url) ? 'sse' : 'http';
|
|
210
|
+
}
|
|
211
|
+
if (!transport) {
|
|
212
|
+
warnings.push('Could not determine transport — defaulting to local (stdio).');
|
|
213
|
+
transport = 'stdio';
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// Per the agreed default, an ambiguous remote is treated as http; flag it so
|
|
217
|
+
// the user can switch to sse in the preview if the server needs it.
|
|
218
|
+
if (!transportExplicit && transport === 'http' && url) {
|
|
219
|
+
warnings.push('Assumed remote (http). Switch to sse if this server uses Server-Sent Events.');
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
if (transport === 'stdio' && !command) {
|
|
223
|
+
warnings.push('No command found for a local server — set one before installing.');
|
|
224
|
+
}
|
|
225
|
+
if (transport !== 'stdio' && !url) {
|
|
226
|
+
warnings.push('No URL found for a remote server — set one before installing.');
|
|
227
|
+
}
|
|
228
|
+
if (Object.values({ ...env, ...headers }).some(v => /\$\{input:/.test(v))) {
|
|
229
|
+
warnings.push('Contains ${input:…} placeholders — fill them in below.');
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const fields = [...fieldsFrom(env, 'env'), ...fieldsFrom(headers, 'header')];
|
|
233
|
+
const cleanName = name.trim() || 'server';
|
|
234
|
+
return {
|
|
235
|
+
name: cleanName,
|
|
236
|
+
slug: slugifyRegistryName(cleanName),
|
|
237
|
+
transport,
|
|
238
|
+
command,
|
|
239
|
+
args,
|
|
240
|
+
url,
|
|
241
|
+
fields,
|
|
242
|
+
warnings
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** True when an object looks like a single server config rather than a map of them. */
|
|
247
|
+
function looksLikeServerConfig(obj: Record<string, unknown>): boolean {
|
|
248
|
+
return 'command' in obj || 'url' in obj || 'serverUrl' in obj || 'httpUrl' in obj || 'type' in obj;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Locate the `name → config` map inside a parsed payload, unwrapping the known
|
|
253
|
+
* container keys and tolerating a bare map or a single unwrapped server object.
|
|
254
|
+
*/
|
|
255
|
+
function findServerMap(obj: Record<string, unknown>): Record<string, unknown> {
|
|
256
|
+
for (const key of ['mcpServers', 'servers', 'mcp'] as const) {
|
|
257
|
+
if (isPlainObject(obj[key])) return obj[key] as Record<string, unknown>;
|
|
258
|
+
}
|
|
259
|
+
// A single unwrapped server object (e.g. the inner block someone copied).
|
|
260
|
+
if (looksLikeServerConfig(obj)) return { server: obj };
|
|
261
|
+
// Otherwise assume the object IS the map (its values are server configs).
|
|
262
|
+
return obj;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Parse pasted MCP JSON (any common dialect) into normalised servers. Never
|
|
267
|
+
* throws — fatal problems are returned in `errors` for the UI to surface.
|
|
268
|
+
*/
|
|
269
|
+
export function parseMcpConfig(raw: string): ParseResult {
|
|
270
|
+
if (!raw.trim()) return { servers: [], errors: ['Paste an MCP server JSON config first.'] };
|
|
271
|
+
|
|
272
|
+
let parsed: unknown;
|
|
273
|
+
try {
|
|
274
|
+
parsed = relaxedParse(raw);
|
|
275
|
+
} catch (error) {
|
|
276
|
+
return { servers: [], errors: [`Invalid JSON: ${error instanceof Error ? error.message : 'could not parse'}`] };
|
|
277
|
+
}
|
|
278
|
+
if (!isPlainObject(parsed)) {
|
|
279
|
+
return { servers: [], errors: ['Expected a JSON object with one or more MCP servers.'] };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const map = findServerMap(parsed);
|
|
283
|
+
const servers: ParsedMcpServer[] = [];
|
|
284
|
+
for (const [name, rawCfg] of Object.entries(map)) {
|
|
285
|
+
const server = normalizeServer(name, rawCfg);
|
|
286
|
+
if (server) servers.push(server);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
if (servers.length === 0) {
|
|
290
|
+
return { servers: [], errors: ['No MCP server found. Expected a "mcpServers", "servers", or "mcp" block, or a single server config.'] };
|
|
291
|
+
}
|
|
292
|
+
return { servers, errors: [] };
|
|
293
|
+
}
|
|
@@ -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
|
+
}
|