cladogram 0.5.5-beta.7 → 0.5.5-beta.9

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.
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Clado 斜杠命令体系(Slash Commands, `/xxx`):
3
+ * - 内置 4 条高频命令(/arch、/test、/diff、/dispatch),统一收编原先写死的工作流入口;
4
+ * - 支持工作区(.clado/commands/<name>.md)、全局(~/.clado/commands/<name>.md)与插件(<pluginDir>/commands/<name>.md)自定义命令;
5
+ * - 支持 YAML Frontmatter(description / skill / workflow / persona)与 `{{args}}` 参数插值。
6
+ */
7
+
8
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+ import YAML from 'yaml';
11
+ import { userTemplatePaths } from '../skill/templates.js';
12
+
13
+ const CMD_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/;
14
+
15
+ export const BUILTIN_COMMANDS = Object.freeze([
16
+ Object.freeze({
17
+ name: 'arch',
18
+ description: '读取源码并在画布中梳理系统架构与调用链',
19
+ workflow: 'design',
20
+ persona: 'architect',
21
+ prompt: '请先用代码探针核对真实源码结构,再用画布工具梳理或更新架构设计与调用链:{{args}}',
22
+ scope: 'builtin',
23
+ }),
24
+ Object.freeze({
25
+ name: 'test',
26
+ description: '基于当前画布或源码生成脑图测试用例',
27
+ workflow: 'qa',
28
+ persona: 'qa',
29
+ prompt: '请阅读当前画布与相关源码,按 test-cases 模板生成覆盖正常流、边界与异常流的脑图测试用例:{{args}}',
30
+ scope: 'builtin',
31
+ }),
32
+ Object.freeze({
33
+ name: 'diff',
34
+ description: '读取本地 Git Diff,对照画布设计逐项验收与归档',
35
+ workflow: 'audit',
36
+ persona: 'auditor',
37
+ prompt: '请调用 probe_git_diff 读取本地真实代码变更,对照画布契约逐项验收并指出遗漏或偏离项:{{args}}',
38
+ scope: 'builtin',
39
+ }),
40
+ Object.freeze({
41
+ name: 'dispatch',
42
+ description: '打包当前架构规格并派发给外部 ACP 执行器落地编码',
43
+ workflow: 'dispatch',
44
+ persona: 'coder',
45
+ prompt: '{{args}}',
46
+ scope: 'builtin',
47
+ }),
48
+ ]);
49
+
50
+ function globalCommandsDir() {
51
+ return join(userTemplatePaths().state, 'commands');
52
+ }
53
+
54
+ function workspaceCommandsDir(workspace) {
55
+ return workspace ? join(workspace, '.clado', 'commands') : '';
56
+ }
57
+
58
+ export function parseCommandMarkdown(raw, fallbackName = '') {
59
+ const text = String(raw || '').replace(/\r\n/g, '\n');
60
+ let meta = {};
61
+ let body = text.trim();
62
+
63
+ const fm = text.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
64
+ if (fm) {
65
+ try {
66
+ const parsed = YAML.parse(fm[1]);
67
+ if (parsed && typeof parsed === 'object') meta = parsed;
68
+ } catch {}
69
+ body = fm[2].trim();
70
+ }
71
+
72
+ return {
73
+ name: typeof meta.name === 'string' && CMD_RE.test(meta.name.trim()) ? meta.name.trim() : fallbackName,
74
+ description: typeof meta.description === 'string' && meta.description.trim()
75
+ ? meta.description.trim()
76
+ : (body.split('\n')[0] || '自定义斜杠命令').slice(0, 100),
77
+ skill: typeof meta.skill === 'string' ? meta.skill.trim() : '',
78
+ workflow: typeof meta.workflow === 'string' ? meta.workflow.trim() : '',
79
+ persona: typeof meta.persona === 'string' ? meta.persona.trim() : '',
80
+ prompt: body,
81
+ };
82
+ }
83
+
84
+ export function serializeCommandMarkdown({ description = '', skill = '', workflow = '', persona = '', prompt = '' }) {
85
+ const fm = {};
86
+ if (description) fm.description = String(description).trim();
87
+ if (skill) fm.skill = String(skill).trim();
88
+ if (workflow) fm.workflow = String(workflow).trim();
89
+ if (persona) fm.persona = String(persona).trim();
90
+ const header = Object.keys(fm).length ? `---\n${YAML.stringify(fm).trim()}\n---\n\n` : '';
91
+ return `${header}${String(prompt || '').trim()}\n`;
92
+ }
93
+
94
+ function scanCommandsInDir(dir, scope, pluginId = '') {
95
+ if (!dir || !existsSync(dir)) return [];
96
+ const items = [];
97
+ let entries = [];
98
+ try {
99
+ entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
100
+ } catch {
101
+ return [];
102
+ }
103
+ for (const entry of entries) {
104
+ if (entry.name.startsWith('.') || !/\.md$/i.test(entry.name)) continue;
105
+ const slug = entry.name.replace(/\.md$/i, '');
106
+ if (!CMD_RE.test(slug)) continue;
107
+ const full = join(dir, entry.name);
108
+ try {
109
+ const st = lstatSync(full);
110
+ if (!st.isFile() || st.isSymbolicLink()) continue;
111
+ const parsed = parseCommandMarkdown(readFileSync(full, 'utf8'), slug);
112
+ items.push({
113
+ ...parsed,
114
+ name: parsed.name || slug,
115
+ scope,
116
+ ...(pluginId ? { pluginId } : {}),
117
+ });
118
+ } catch {}
119
+ }
120
+ return items;
121
+ }
122
+
123
+ export function listCommands(workspace, { pluginDirs = [] } = {}) {
124
+ const merged = new Map();
125
+ for (const cmd of BUILTIN_COMMANDS) merged.set(cmd.name, { ...cmd });
126
+
127
+ for (const p of pluginDirs || []) {
128
+ if (!p?.dir) continue;
129
+ for (const cmd of scanCommandsInDir(join(p.dir, 'commands'), 'plugin', p.id || '')) {
130
+ merged.set(cmd.name, cmd);
131
+ }
132
+ }
133
+ for (const cmd of scanCommandsInDir(globalCommandsDir(), 'global')) {
134
+ merged.set(cmd.name, cmd);
135
+ }
136
+ for (const cmd of scanCommandsInDir(workspaceCommandsDir(workspace), 'workspace')) {
137
+ merged.set(cmd.name, cmd);
138
+ }
139
+
140
+ return [...merged.values()];
141
+ }
142
+
143
+ export function saveCommand(workspace, { name, description = '', prompt = '', skill = '', workflow = '', persona = '', scope = 'workspace' } = {}) {
144
+ const cleanName = String(name || '')
145
+ .trim()
146
+ .replace(/^\/+/, '')
147
+ .toLowerCase();
148
+ if (!CMD_RE.test(cleanName)) {
149
+ throw new Error('命令名仅支持英文字母、数字、连字符或下划线(如 review、api-spec)。');
150
+ }
151
+ const cleanPrompt = String(prompt || '').trim();
152
+ if (!cleanPrompt) throw new Error('命令提示词模板不能为空。');
153
+
154
+ const baseDir = scope === 'global' || !workspace ? globalCommandsDir() : workspaceCommandsDir(workspace);
155
+ mkdirSync(baseDir, { recursive: true, mode: 0o700 });
156
+ const filePath = join(baseDir, `${cleanName}.md`);
157
+ writeFileSync(filePath, serializeCommandMarkdown({ description, skill, workflow, persona, prompt: cleanPrompt }), 'utf8');
158
+ return {
159
+ name: cleanName,
160
+ description: String(description || cleanPrompt.slice(0, 80)).trim(),
161
+ skill: String(skill || '').trim(),
162
+ workflow: String(workflow || '').trim(),
163
+ persona: String(persona || '').trim(),
164
+ prompt: cleanPrompt,
165
+ scope: scope === 'global' || !workspace ? 'global' : 'workspace',
166
+ };
167
+ }
168
+
169
+ export function deleteCommand(workspace, { name, scope = 'workspace' } = {}) {
170
+ const cleanName = String(name || '').trim().replace(/^\/+/, '').toLowerCase();
171
+ if (!CMD_RE.test(cleanName)) return false;
172
+ const baseDir = scope === 'global' || !workspace ? globalCommandsDir() : workspaceCommandsDir(workspace);
173
+ const filePath = join(baseDir, `${cleanName}.md`);
174
+ if (!existsSync(filePath)) return false;
175
+ rmSync(filePath, { force: true });
176
+ return true;
177
+ }
178
+
179
+ export function expandSlashCommand(workspace, rawInput = '', { pluginDirs = [] } = {}) {
180
+ const text = String(rawInput || '').trim();
181
+ const m = text.match(/^\/([a-zA-Z0-9][a-zA-Z0-9_-]{0,47})(?:\s+([\s\S]*))?$/);
182
+ if (!m) return null;
183
+
184
+ const cmdName = m[1].toLowerCase();
185
+ const args = (m[2] || '').trim();
186
+ const cmd = listCommands(workspace, { pluginDirs }).find(c => c.name.toLowerCase() === cmdName);
187
+ if (!cmd) return null;
188
+
189
+ let expanded = cmd.prompt || '';
190
+ if (expanded.includes('{{args}}')) {
191
+ expanded = expanded.replace(/\{\{args\}\}/g, args || '(当前画布与项目上下文)');
192
+ } else if (args) {
193
+ expanded = expanded ? `${expanded}\n\n补充参数:${args}` : args;
194
+ }
195
+
196
+ return {
197
+ command: cmd,
198
+ args,
199
+ prompt: expanded.trim() || text,
200
+ workflow: cmd.workflow || '',
201
+ persona: cmd.persona || '',
202
+ skill: cmd.skill || '',
203
+ };
204
+ }
@@ -62,16 +62,29 @@ function sanitizeConfig(raw = {}) {
62
62
  };
63
63
 
64
64
  const rawPersonas = raw.personas && typeof raw.personas === 'object' ? raw.personas : {};
65
+ const builtinIds = new Set(PERSONA_TEMPLATES.map(t => t.id));
65
66
  for (const tpl of PERSONA_TEMPLATES) {
66
67
  const item = rawPersonas[tpl.id] && typeof rawPersonas[tpl.id] === 'object' ? rawPersonas[tpl.id] : {};
67
68
  out.personas[tpl.id] = {
68
- name: tpl.name,
69
+ name: typeof item.name === 'string' && item.name.trim() ? item.name.trim().slice(0, 40) : tpl.name,
69
70
  pal: tpl.pal,
70
71
  summary: tpl.summary,
71
72
  prompt: typeof item.prompt === 'string' && item.prompt.trim() ? item.prompt.trim().slice(0, 4000) : tpl.prompt,
72
73
  initContext: typeof item.initContext === 'string' ? item.initContext.trim().slice(0, 2000) : tpl.initContext,
73
74
  };
74
75
  }
76
+ for (const [k, v] of Object.entries(rawPersonas)) {
77
+ if (builtinIds.has(k) || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,31}$/.test(k)) continue;
78
+ if (!v || typeof v !== 'object') continue;
79
+ out.personas[k] = {
80
+ name: typeof v.name === 'string' && v.name.trim() ? v.name.trim().slice(0, 40) : k,
81
+ pal: typeof v.pal === 'string' ? v.pal : 'violet',
82
+ summary: typeof v.summary === 'string' ? v.summary.slice(0, 80) : (typeof v.prompt === 'string' ? v.prompt.trim().slice(0, 48) : '自定义人设'),
83
+ prompt: typeof v.prompt === 'string' ? v.prompt.trim().slice(0, 4000) : '',
84
+ initContext: typeof v.initContext === 'string' ? v.initContext.trim().slice(0, 2000) : '',
85
+ custom: true,
86
+ };
87
+ }
75
88
  return out;
76
89
  }
77
90
 
@@ -103,8 +116,10 @@ export function saveAgentDebugConfig(stateDir, patch = {}, { scope = 'global' }
103
116
  const nextPersonas = { ...current.personas };
104
117
  if (patch.personas && typeof patch.personas === 'object') {
105
118
  for (const [k, v] of Object.entries(patch.personas)) {
106
- if (nextPersonas[k] && v && typeof v === 'object') {
107
- nextPersonas[k] = { ...nextPersonas[k], ...v };
119
+ if (v === null) {
120
+ delete nextPersonas[k];
121
+ } else if (v && typeof v === 'object' && /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,31}$/.test(k)) {
122
+ nextPersonas[k] = { ...(nextPersonas[k] || {}), ...v };
108
123
  }
109
124
  }
110
125
  }
@@ -0,0 +1,308 @@
1
+ /**
2
+ * Clado 原生 Agent 外部 MCP Client 运行时与配置管理:
3
+ * - 支持全球配置(~/.clado/mcp.json)、工作区配置(.clado/mcp.json)与插件声明(pluginMcp)三层合并;
4
+ * - 兼容标准 mcpServers JSON 格式(Claude Code / Cursor 直接粘贴即用);
5
+ * - 支持 Stdio(本地命令)与 Streamable HTTP(远程/本机 HTTP MCP)双传输协议;
6
+ * - 提供连通性测试、工具发现缓存、与原生 Agent 工具调用桥接(mcp__<server>__<tool>)。
7
+ */
8
+
9
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
10
+ import { dirname, join } from 'node:path';
11
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
12
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
13
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
14
+ import { userTemplatePaths } from '../skill/templates.js';
15
+ import { VERSION } from '../util/version.js';
16
+
17
+ const NAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/;
18
+ const DEFAULT_TIMEOUT_MS = 12000;
19
+
20
+ function globalMcpPath() {
21
+ return join(userTemplatePaths().state, 'mcp.json');
22
+ }
23
+
24
+ function workspaceMcpPath(workspace) {
25
+ return workspace ? join(workspace, '.clado', 'mcp.json') : '';
26
+ }
27
+
28
+ function readMcpFile(filePath) {
29
+ if (!filePath || !existsSync(filePath)) return {};
30
+ try {
31
+ const raw = JSON.parse(readFileSync(filePath, 'utf8'));
32
+ if (!raw || typeof raw !== 'object') return {};
33
+ const servers = raw.mcpServers && typeof raw.mcpServers === 'object' ? raw.mcpServers : raw;
34
+ return servers && typeof servers === 'object' && !Array.isArray(servers) ? servers : {};
35
+ } catch {
36
+ return {};
37
+ }
38
+ }
39
+
40
+ function writeMcpFile(filePath, servers) {
41
+ const dir = dirname(filePath);
42
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
43
+ writeFileSync(filePath, JSON.stringify({ mcpServers: servers }, null, 2) + '\n', { mode: 0o600 });
44
+ }
45
+
46
+ export function normalizeServerConfig(raw = {}) {
47
+ if (!raw || typeof raw !== 'object') throw new Error('MCP 服务配置必须是 JSON 对象。');
48
+ const url = typeof raw.url === 'string' ? raw.url.trim() : '';
49
+ const command = typeof raw.command === 'string' ? raw.command.trim() : '';
50
+ const type = raw.type === 'http' || raw.type === 'streamable-http' || (!command && url) ? 'http' : 'stdio';
51
+ const enabled = raw.enabled !== false;
52
+
53
+ if (type === 'http') {
54
+ if (!/^https?:\/\//i.test(url)) throw new Error('HTTP MCP 服务需要有效的 http(s):// 地址。');
55
+ const headers = raw.headers && typeof raw.headers === 'object' && !Array.isArray(raw.headers)
56
+ ? Object.fromEntries(Object.entries(raw.headers).map(([k, v]) => [String(k), String(v)]))
57
+ : {};
58
+ return { type: 'http', url, headers, enabled };
59
+ }
60
+
61
+ if (!command) throw new Error('Stdio MCP 服务需要填写启动命令(command)。');
62
+ const args = Array.isArray(raw.args)
63
+ ? raw.args.map(a => String(a))
64
+ : (typeof raw.args === 'string' && raw.args.trim() ? raw.args.trim().split(/\s+/) : []);
65
+ const env = raw.env && typeof raw.env === 'object' && !Array.isArray(raw.env)
66
+ ? Object.fromEntries(Object.entries(raw.env).map(([k, v]) => [String(k), String(v)]))
67
+ : {};
68
+ const cwd = typeof raw.cwd === 'string' && raw.cwd.trim() ? raw.cwd.trim() : undefined;
69
+ return { type: 'stdio', command, args, env, ...(cwd ? { cwd } : {}), enabled };
70
+ }
71
+
72
+ function sanitizeServerForUi(name, cfg, scope, pluginId = '') {
73
+ const envKeys = cfg.env ? Object.keys(cfg.env) : [];
74
+ const headerKeys = cfg.headers ? Object.keys(cfg.headers) : [];
75
+ return {
76
+ name,
77
+ scope,
78
+ ...(pluginId ? { pluginId } : {}),
79
+ type: cfg.type || (cfg.url ? 'http' : 'stdio'),
80
+ enabled: cfg.enabled !== false,
81
+ command: cfg.command || '',
82
+ args: Array.isArray(cfg.args) ? cfg.args : [],
83
+ url: cfg.url || '',
84
+ envKeys,
85
+ headerKeys,
86
+ };
87
+ }
88
+
89
+ export function listMcpServers(workspace, { pluginMcp = [], includeSecrets = false } = {}) {
90
+ const merged = new Map();
91
+
92
+ for (const item of pluginMcp || []) {
93
+ if (!item?.name || !NAME_RE.test(item.name)) continue;
94
+ try {
95
+ const cfg = normalizeServerConfig(item);
96
+ merged.set(item.name, { name: item.name, scope: 'plugin', pluginId: item.pluginId || '', config: cfg });
97
+ } catch {}
98
+ }
99
+
100
+ const globalMap = readMcpFile(globalMcpPath());
101
+ for (const [name, raw] of Object.entries(globalMap)) {
102
+ if (!NAME_RE.test(name)) continue;
103
+ try {
104
+ merged.set(name, { name, scope: 'global', config: normalizeServerConfig(raw) });
105
+ } catch {}
106
+ }
107
+
108
+ const wsMap = readMcpFile(workspaceMcpPath(workspace));
109
+ for (const [name, raw] of Object.entries(wsMap)) {
110
+ if (!NAME_RE.test(name)) continue;
111
+ try {
112
+ merged.set(name, { name, scope: 'workspace', config: normalizeServerConfig(raw) });
113
+ } catch {}
114
+ }
115
+
116
+ return [...merged.values()].map(entry => (
117
+ includeSecrets
118
+ ? entry
119
+ : sanitizeServerForUi(entry.name, entry.config, entry.scope, entry.pluginId)
120
+ ));
121
+ }
122
+
123
+ export function saveMcpServer(workspace, { name, scope = 'workspace', config } = {}) {
124
+ const cleanName = String(name || '').trim();
125
+ if (!NAME_RE.test(cleanName)) {
126
+ throw new Error('MCP 服务名称仅支持字母、数字、下划线和连字符(1-48 字符)。');
127
+ }
128
+ const normalized = normalizeServerConfig(config);
129
+ const filePath = scope === 'global' || !workspace ? globalMcpPath() : workspaceMcpPath(workspace);
130
+ const current = readMcpFile(filePath);
131
+ current[cleanName] = normalized;
132
+ writeMcpFile(filePath, current);
133
+ return sanitizeServerForUi(cleanName, normalized, scope === 'global' || !workspace ? 'global' : 'workspace');
134
+ }
135
+
136
+ export function toggleMcpServer(workspace, { name, scope = 'workspace', enabled = true } = {}) {
137
+ const cleanName = String(name || '').trim();
138
+ const filePath = scope === 'global' || !workspace ? globalMcpPath() : workspaceMcpPath(workspace);
139
+ const current = readMcpFile(filePath);
140
+ if (!current[cleanName]) throw new Error(`未找到 MCP 服务:${cleanName}`);
141
+ current[cleanName] = { ...current[cleanName], enabled: Boolean(enabled) };
142
+ writeMcpFile(filePath, current);
143
+ return sanitizeServerForUi(cleanName, normalizeServerConfig(current[cleanName]), scope === 'global' || !workspace ? 'global' : 'workspace');
144
+ }
145
+
146
+ export function deleteMcpServer(workspace, { name, scope = 'workspace' } = {}) {
147
+ const cleanName = String(name || '').trim();
148
+ const filePath = scope === 'global' || !workspace ? globalMcpPath() : workspaceMcpPath(workspace);
149
+ const current = readMcpFile(filePath);
150
+ if (!current[cleanName]) return false;
151
+ delete current[cleanName];
152
+ writeMcpFile(filePath, current);
153
+ return true;
154
+ }
155
+
156
+ export function importMcpJson(workspace, { scope = 'workspace', jsonText = '' } = {}) {
157
+ let parsed;
158
+ try {
159
+ parsed = typeof jsonText === 'string' ? JSON.parse(jsonText) : jsonText;
160
+ } catch {
161
+ throw new Error('粘贴的内容不是合法 JSON。');
162
+ }
163
+ const map = parsed?.mcpServers && typeof parsed.mcpServers === 'object' ? parsed.mcpServers : parsed;
164
+ if (!map || typeof map !== 'object' || Array.isArray(map)) {
165
+ throw new Error('JSON 需要包含 mcpServers 对象或直接为服务名称映射。');
166
+ }
167
+ const entries = Object.entries(map);
168
+ if (!entries.length) throw new Error('JSON 中没有可导入的 MCP 服务。');
169
+
170
+ const filePath = scope === 'global' || !workspace ? globalMcpPath() : workspaceMcpPath(workspace);
171
+ const current = readMcpFile(filePath);
172
+ const imported = [];
173
+ for (const [name, raw] of entries) {
174
+ if (!NAME_RE.test(name)) throw new Error(`服务名称无效:${name}`);
175
+ current[name] = normalizeServerConfig(raw);
176
+ imported.push(name);
177
+ }
178
+ writeMcpFile(filePath, current);
179
+ return imported;
180
+ }
181
+
182
+ async function withMcpClient(serverConfig, workspace, fn, { timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
183
+ const client = new Client({ name: 'clado-native-agent', version: VERSION });
184
+ let transport;
185
+ if (serverConfig.type === 'http') {
186
+ transport = new StreamableHTTPClientTransport(new URL(serverConfig.url), {
187
+ requestInit: serverConfig.headers && Object.keys(serverConfig.headers).length
188
+ ? { headers: serverConfig.headers }
189
+ : undefined,
190
+ });
191
+ } else {
192
+ transport = new StdioClientTransport({
193
+ command: serverConfig.command,
194
+ args: serverConfig.args || [],
195
+ env: { ...process.env, ...(serverConfig.env || {}) },
196
+ cwd: serverConfig.cwd || workspace || process.cwd(),
197
+ stderr: 'pipe',
198
+ });
199
+ }
200
+
201
+ let timer;
202
+ const timeoutPromise = new Promise((_, reject) => {
203
+ timer = setTimeout(() => reject(new Error(`连接 MCP 服务超时(>${Math.round(timeoutMs / 1000)}s)`)), timeoutMs);
204
+ });
205
+
206
+ try {
207
+ await Promise.race([client.connect(transport), timeoutPromise]);
208
+ return await Promise.race([fn(client), timeoutPromise]);
209
+ } finally {
210
+ clearTimeout(timer);
211
+ await client.close().catch(() => {});
212
+ }
213
+ }
214
+
215
+ export async function testMcpServer(workspace, serverConfig, { timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
216
+ const started = Date.now();
217
+ try {
218
+ const normalized = normalizeServerConfig(serverConfig);
219
+ const tools = await withMcpClient(normalized, workspace, async client => {
220
+ const res = await client.listTools();
221
+ return Array.isArray(res?.tools) ? res.tools : [];
222
+ }, { timeoutMs });
223
+ return {
224
+ ok: true,
225
+ latencyMs: Date.now() - started,
226
+ toolCount: tools.length,
227
+ tools: tools.map(t => ({ name: t.name, description: t.description || '' })),
228
+ };
229
+ } catch (error) {
230
+ return {
231
+ ok: false,
232
+ latencyMs: Date.now() - started,
233
+ toolCount: 0,
234
+ tools: [],
235
+ error: error?.message || String(error),
236
+ };
237
+ }
238
+ }
239
+
240
+ export function encodeMcpToolName(serverName, toolName) {
241
+ const safeTool = String(toolName || '').replace(/[^a-zA-Z0-9_-]/g, '_');
242
+ return `mcp__${serverName}__${safeTool}`;
243
+ }
244
+
245
+ export async function discoverExternalMcpTools(workspace, { pluginMcp = [], timeoutMs = 6000 } = {}) {
246
+ const servers = listMcpServers(workspace, { pluginMcp, includeSecrets: true }).filter(s => s.config.enabled !== false);
247
+ if (!servers.length) return { definitions: [], registry: new Map(), errors: [] };
248
+
249
+ const definitions = [];
250
+ const registry = new Map();
251
+ const errors = [];
252
+
253
+ await Promise.all(servers.map(async entry => {
254
+ try {
255
+ const tools = await withMcpClient(entry.config, workspace, async client => {
256
+ const res = await client.listTools();
257
+ return Array.isArray(res?.tools) ? res.tools : [];
258
+ }, { timeoutMs });
259
+
260
+ for (const tool of tools) {
261
+ const fnName = encodeMcpToolName(entry.name, tool.name);
262
+ registry.set(fnName, {
263
+ serverName: entry.name,
264
+ toolName: tool.name,
265
+ config: entry.config,
266
+ });
267
+ definitions.push({
268
+ type: 'function',
269
+ function: {
270
+ name: fnName,
271
+ description: `[MCP:${entry.name}] ${tool.description || tool.name}`,
272
+ parameters: tool.inputSchema && typeof tool.inputSchema === 'object'
273
+ ? tool.inputSchema
274
+ : { type: 'object', properties: {} },
275
+ },
276
+ });
277
+ }
278
+ } catch (error) {
279
+ errors.push({ server: entry.name, error: error?.message || String(error) });
280
+ }
281
+ }));
282
+
283
+ return { definitions, registry, errors };
284
+ }
285
+
286
+ export async function callExternalMcpTool(entry, args = {}, workspace, { timeoutMs = 20000 } = {}) {
287
+ return withMcpClient(entry.config, workspace, async client => {
288
+ const result = await client.callTool({
289
+ name: entry.toolName,
290
+ arguments: args && typeof args === 'object' ? args : {},
291
+ });
292
+ const content = Array.isArray(result?.content) ? result.content : [];
293
+ const textParts = content
294
+ .map(part => {
295
+ if (part?.type === 'text') return part.text || '';
296
+ if (part?.type === 'resource' && part.resource?.text) return part.resource.text;
297
+ return JSON.stringify(part);
298
+ })
299
+ .filter(Boolean);
300
+ return {
301
+ ok: !result?.isError,
302
+ server: entry.serverName,
303
+ tool: entry.toolName,
304
+ text: textParts.join('\n') || (result?.structuredContent ? JSON.stringify(result.structuredContent) : ''),
305
+ ...(result?.structuredContent ? { structuredContent: result.structuredContent } : {}),
306
+ };
307
+ }, { timeoutMs });
308
+ }