@myrialabs/clopen 0.4.3 → 0.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/backend/auth/permissions.ts +1 -0
- package/backend/database/migrations/043_relocate_engine_config_dirs.ts +71 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/mcp-server-queries.ts +14 -0
- package/backend/engine/README.md +12 -8
- package/backend/engine/adapters/claude/environment.ts +3 -3
- package/backend/engine/adapters/codex/credential.ts +12 -2
- package/backend/engine/adapters/codex/stream.ts +6 -0
- package/backend/engine/adapters/copilot/stream.ts +5 -1
- package/backend/engine/adapters/opencode/server.ts +36 -5
- package/backend/engine/adapters/qwen/environment.ts +7 -0
- package/backend/engine/adapters/qwen/session-fork.ts +13 -1
- package/backend/engine/docs/database.md +9 -6
- package/backend/engine/docs/lessons-learned.md +117 -16
- package/backend/git/git-service.ts +50 -1
- package/backend/mcp/external/parse.test.ts +190 -0
- package/backend/mcp/external/parse.ts +293 -0
- package/backend/mcp/external/probe.ts +55 -5
- package/backend/mcp/external/registry-client.ts +8 -1
- package/backend/mcp/index.ts +2 -0
- package/backend/snapshot/gitignore.ts +230 -7
- package/backend/snapshot/helpers.ts +34 -10
- package/backend/utils/paths.ts +16 -0
- package/backend/ws/engine/codex/accounts.ts +3 -0
- 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/mcp/crud.ts +42 -2
- package/backend/ws/snapshot/timeline.ts +1 -1
- package/dist/assets/main-gNUEJAC5.css +1 -0
- package/dist/assets/{main-D-AcjotJ.js → main-zXKH_C5O.js} +318 -290
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/git.ts +20 -0
- package/dist/assets/main-DJf71Zum.css +0 -1
|
@@ -35,6 +35,8 @@ import {
|
|
|
35
35
|
assertSafeGitRevish,
|
|
36
36
|
assertSafeGitShowRef
|
|
37
37
|
} from './git-spawn-validation';
|
|
38
|
+
import { findNestedRepoPaths, findSubmodulePaths } from '../snapshot/gitignore';
|
|
39
|
+
import path from 'node:path';
|
|
38
40
|
|
|
39
41
|
export class GitService {
|
|
40
42
|
/**
|
|
@@ -204,7 +206,16 @@ export class GitService {
|
|
|
204
206
|
|
|
205
207
|
async getDiffCommit(cwd: string, commitHash: string): Promise<GitFileDiff[]> {
|
|
206
208
|
assertSafeGitRevish(commitHash, 'commit hash');
|
|
207
|
-
|
|
209
|
+
// Root commits have no parent, so `<hash>^` can't resolve and `git diff`
|
|
210
|
+
// fails silently (empty stdout) — which previously surfaced as "No files
|
|
211
|
+
// changed". Detect the parentless case and diff against the empty tree via
|
|
212
|
+
// `diff-tree --root` so the initial commit's files show up as additions.
|
|
213
|
+
// Commits with a parent (including merges) keep the original behaviour.
|
|
214
|
+
const hasParent =
|
|
215
|
+
(await execGit(['rev-parse', '--verify', '--quiet', `${commitHash}^`], cwd)).exitCode === 0;
|
|
216
|
+
const result = hasParent
|
|
217
|
+
? await execGit(['diff', `${commitHash}^`, commitHash], cwd)
|
|
218
|
+
: await execGit(['diff-tree', '-p', '--root', '--no-commit-id', commitHash], cwd);
|
|
208
219
|
return parseDiff(result.stdout);
|
|
209
220
|
}
|
|
210
221
|
|
|
@@ -302,6 +313,44 @@ export class GitService {
|
|
|
302
313
|
}
|
|
303
314
|
}
|
|
304
315
|
|
|
316
|
+
// Discover nested git repos (submodules, gitignored embedded repos,
|
|
317
|
+
// worktrees) and aggregate their branch info so the Branches tab can
|
|
318
|
+
// render one collapsible group per sub-repo. Failures in a single
|
|
319
|
+
// nested repo must not break the outer result — we record the error
|
|
320
|
+
// on the entry and move on.
|
|
321
|
+
try {
|
|
322
|
+
const [nestedPaths, submodulePaths] = await Promise.all([
|
|
323
|
+
findNestedRepoPaths(cwd),
|
|
324
|
+
findSubmodulePaths(cwd)
|
|
325
|
+
]);
|
|
326
|
+
if (nestedPaths.length > 0) {
|
|
327
|
+
const nestedResults = await Promise.all(
|
|
328
|
+
nestedPaths.map(async (repoPath) => {
|
|
329
|
+
const relPath = path.relative(cwd, repoPath).replace(/\\/g, '/');
|
|
330
|
+
const isSubmodule = submodulePaths.has(relPath);
|
|
331
|
+
try {
|
|
332
|
+
const info = await this.getBranches(repoPath, selectedRemote);
|
|
333
|
+
return { path: repoPath, relPath, isSubmodule, info };
|
|
334
|
+
} catch (err) {
|
|
335
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
336
|
+
return {
|
|
337
|
+
path: repoPath,
|
|
338
|
+
relPath,
|
|
339
|
+
isSubmodule,
|
|
340
|
+
info: { current: '', local: [], remote: [], ahead: 0, behind: 0 },
|
|
341
|
+
error: message
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
})
|
|
345
|
+
);
|
|
346
|
+
// Stable order for the UI (sorted by relPath).
|
|
347
|
+
nestedResults.sort((a, b) => a.relPath.localeCompare(b.relPath));
|
|
348
|
+
branchInfo.nested = nestedResults;
|
|
349
|
+
}
|
|
350
|
+
} catch (err) {
|
|
351
|
+
debug.warn('git', `Failed to enumerate nested repos: ${err instanceof Error ? err.message : String(err)}`);
|
|
352
|
+
}
|
|
353
|
+
|
|
305
354
|
return branchInfo;
|
|
306
355
|
}
|
|
307
356
|
|
|
@@ -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
|
+
}
|
|
@@ -87,6 +87,31 @@ function classifyUnauthorized(res: Response): McpHealth {
|
|
|
87
87
|
return { state: 'needs_config', message: 'A credential (API key / token) is required' };
|
|
88
88
|
}
|
|
89
89
|
|
|
90
|
+
/** Cap on captured stderr so a chatty subprocess can't balloon memory. */
|
|
91
|
+
const STDERR_CAP = 4000;
|
|
92
|
+
|
|
93
|
+
/** Drain a subprocess's stderr into a bounded string (best-effort). */
|
|
94
|
+
async function drainStderr(stream: ReadableStream<Uint8Array>): Promise<string> {
|
|
95
|
+
const reader = stream.getReader();
|
|
96
|
+
const decoder = new TextDecoder();
|
|
97
|
+
let text = '';
|
|
98
|
+
try {
|
|
99
|
+
while (text.length < STDERR_CAP) {
|
|
100
|
+
const { done, value } = await reader.read();
|
|
101
|
+
if (done) break;
|
|
102
|
+
text += decoder.decode(value, { stream: true });
|
|
103
|
+
}
|
|
104
|
+
} catch { /* stream closed/cancelled */ } finally {
|
|
105
|
+
reader.cancel().catch(() => undefined);
|
|
106
|
+
}
|
|
107
|
+
return text;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Condense captured stderr into a short, single-line diagnostic. */
|
|
111
|
+
function stderrTail(text: string): string {
|
|
112
|
+
return text.replace(/\s+/g, ' ').trim().slice(0, 300);
|
|
113
|
+
}
|
|
114
|
+
|
|
90
115
|
/**
|
|
91
116
|
* Spawn a stdio server and run the same handshake over its stdin/stdout
|
|
92
117
|
* (newline-delimited JSON-RPC) so "local" servers report a real connection
|
|
@@ -100,13 +125,18 @@ async function probeStdio(s: ResolvedExternalServer): Promise<McpHealth> {
|
|
|
100
125
|
proc = Bun.spawn([s.command, ...s.args], {
|
|
101
126
|
stdin: 'pipe',
|
|
102
127
|
stdout: 'pipe',
|
|
103
|
-
stderr: '
|
|
128
|
+
stderr: 'pipe',
|
|
104
129
|
env: { ...process.env, ...s.env }
|
|
105
130
|
});
|
|
106
131
|
} catch (error) {
|
|
107
132
|
return { state: 'unreachable', message: error instanceof Error ? error.message : 'Failed to start command' };
|
|
108
133
|
}
|
|
109
134
|
|
|
135
|
+
// Capture stderr concurrently so a process that prints usage/errors and then
|
|
136
|
+
// exits (e.g. a CLI that needs a `mcp` subcommand to actually start the
|
|
137
|
+
// server) yields an actionable message instead of a misleading timeout.
|
|
138
|
+
const stderrPromise = drainStderr(proc.stderr as unknown as ReadableStream<Uint8Array>);
|
|
139
|
+
|
|
110
140
|
try {
|
|
111
141
|
const stdin = proc.stdin as unknown as { write(data: Uint8Array): number; flush?(): Promise<number> | number };
|
|
112
142
|
const stdout = proc.stdout as unknown as ReadableStream<Uint8Array>;
|
|
@@ -117,10 +147,30 @@ async function probeStdio(s: ResolvedExternalServer): Promise<McpHealth> {
|
|
|
117
147
|
await stdin.flush?.();
|
|
118
148
|
|
|
119
149
|
const rpc = await readStdoutForId(stdout, 2, STDIO_PROBE_TIMEOUT_MS);
|
|
120
|
-
if (
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
150
|
+
if (rpc) {
|
|
151
|
+
if (Array.isArray(rpc.result?.tools)) return { state: 'ok', toolCount: rpc.result.tools.length };
|
|
152
|
+
const detail = rpc.error?.message ?? 'Server did not return a tool list';
|
|
153
|
+
return AUTH_HINT.test(detail) ? { state: 'needs_config', message: detail } : { state: 'error', message: detail };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// No JSON-RPC reply. Distinguish a process that already exited (a real,
|
|
157
|
+
// reportable error — wrong command, missing subcommand, crash) from one
|
|
158
|
+
// that's still alive but silent (a genuine timeout).
|
|
159
|
+
const exitCode = await Promise.race([
|
|
160
|
+
proc.exited,
|
|
161
|
+
new Promise<number | null>(resolve => setTimeout(() => resolve(null), 250))
|
|
162
|
+
]);
|
|
163
|
+
if (exitCode !== null) {
|
|
164
|
+
const tail = stderrTail(await Promise.race([
|
|
165
|
+
stderrPromise,
|
|
166
|
+
new Promise<string>(resolve => setTimeout(() => resolve(''), 200))
|
|
167
|
+
]));
|
|
168
|
+
const detail = tail
|
|
169
|
+
? `Process exited (code ${exitCode}): ${tail}`
|
|
170
|
+
: `Process exited (code ${exitCode}) before responding`;
|
|
171
|
+
return AUTH_HINT.test(detail) ? { state: 'needs_config', message: detail } : { state: 'error', message: detail };
|
|
172
|
+
}
|
|
173
|
+
return { state: 'unreachable', message: `No response within ${STDIO_PROBE_TIMEOUT_MS / 1000}s` };
|
|
124
174
|
} catch (error) {
|
|
125
175
|
return { state: 'error', message: error instanceof Error ? error.message : 'Probe failed' };
|
|
126
176
|
} finally {
|
|
@@ -109,7 +109,14 @@ function resolveStdioPackage(pkg: RegistryPackage): { command: string; args: str
|
|
|
109
109
|
if (!command || !pkg.identifier) return null;
|
|
110
110
|
|
|
111
111
|
const args: string[] = [];
|
|
112
|
-
|
|
112
|
+
const runtimeArgs = pkg.runtimeArguments ?? [];
|
|
113
|
+
// `npx` prompts before fetching an uncached package; `-y` keeps the
|
|
114
|
+
// non-interactive spawn (health probe + engine) from stalling on that prompt.
|
|
115
|
+
// Skip if the registry already supplies a confirm flag.
|
|
116
|
+
if (/(^|\/)npx$/.test(command) && !runtimeArgs.some(a => a.name === '-y' || a.name === '--yes')) {
|
|
117
|
+
args.push('-y');
|
|
118
|
+
}
|
|
119
|
+
for (const a of runtimeArgs) args.push(...argTokens(a));
|
|
113
120
|
|
|
114
121
|
// Package identifier token (with version for npm-style registries).
|
|
115
122
|
const identifier = pkg.version && pkg.registryType === 'npm'
|
package/backend/mcp/index.ts
CHANGED
|
@@ -87,6 +87,8 @@ export {
|
|
|
87
87
|
loadOAuth
|
|
88
88
|
} from './external/oauth';
|
|
89
89
|
export type { CatalogServer, CatalogEnvVar, CatalogPage, ResolvedExternalServer } from './external/types';
|
|
90
|
+
export { parseMcpConfig } from './external/parse';
|
|
91
|
+
export type { ParsedMcpServer, ParsedField, ParseResult } from './external/parse';
|
|
90
92
|
|
|
91
93
|
// ---------------------------------------------------------------------------
|
|
92
94
|
// Merged config builders (internal `clopen-mcp` + external bare `<slug>`)
|