@saturn-universe/cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/dist/attach.d.ts +9 -0
- package/dist/attach.js +80 -0
- package/dist/auth-config.d.ts +31 -0
- package/dist/auth-config.js +285 -0
- package/dist/choice-menu.d.ts +13 -0
- package/dist/choice-menu.js +238 -0
- package/dist/cli-diagnostics.d.ts +23 -0
- package/dist/cli-diagnostics.js +42 -0
- package/dist/cli-help.d.ts +6 -0
- package/dist/cli-help.js +163 -0
- package/dist/client.d.ts +13 -0
- package/dist/client.js +90 -0
- package/dist/commands.d.ts +64 -0
- package/dist/commands.js +299 -0
- package/dist/compaction-command.d.ts +16 -0
- package/dist/compaction-command.js +16 -0
- package/dist/composer.d.ts +88 -0
- package/dist/composer.js +124 -0
- package/dist/config-cli.d.ts +1 -0
- package/dist/config-cli.js +47 -0
- package/dist/config-file.d.ts +1 -0
- package/dist/config-file.js +43 -0
- package/dist/config-lock.d.ts +5 -0
- package/dist/config-lock.js +45 -0
- package/dist/duration.d.ts +2 -0
- package/dist/duration.js +11 -0
- package/dist/export.d.ts +19 -0
- package/dist/export.js +66 -0
- package/dist/host-command.d.ts +40 -0
- package/dist/host-command.js +48 -0
- package/dist/host-launcher.d.ts +22 -0
- package/dist/host-launcher.js +300 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +400 -0
- package/dist/markdown.d.ts +1 -0
- package/dist/markdown.js +118 -0
- package/dist/mcp-cli.d.ts +44 -0
- package/dist/mcp-cli.js +647 -0
- package/dist/menu.d.ts +7 -0
- package/dist/menu.js +91 -0
- package/dist/project-mcp-config.d.ts +9 -0
- package/dist/project-mcp-config.js +98 -0
- package/dist/provider-discovery.d.ts +26 -0
- package/dist/provider-discovery.js +138 -0
- package/dist/provider-pricing.d.ts +3 -0
- package/dist/provider-pricing.js +130 -0
- package/dist/provider.d.ts +16 -0
- package/dist/provider.js +370 -0
- package/dist/reconcile-command.d.ts +36 -0
- package/dist/reconcile-command.js +64 -0
- package/dist/renderer.d.ts +204 -0
- package/dist/renderer.js +1134 -0
- package/dist/repl-host.d.ts +22 -0
- package/dist/repl-host.js +51 -0
- package/dist/repl-run-observer.d.ts +27 -0
- package/dist/repl-run-observer.js +86 -0
- package/dist/repl.d.ts +12 -0
- package/dist/repl.js +1834 -0
- package/dist/results.d.ts +23 -0
- package/dist/results.js +1 -0
- package/dist/sandbox-cli.d.ts +39 -0
- package/dist/sandbox-cli.js +324 -0
- package/dist/session-history.d.ts +17 -0
- package/dist/session-history.js +76 -0
- package/dist/settings-menu.d.ts +2 -0
- package/dist/settings-menu.js +111 -0
- package/dist/skill-cli.d.ts +25 -0
- package/dist/skill-cli.js +355 -0
- package/dist/slash-commands.d.ts +66 -0
- package/dist/slash-commands.js +1449 -0
- package/dist/terminal-input.d.ts +24 -0
- package/dist/terminal-input.js +111 -0
- package/dist/terminal-selection.d.ts +21 -0
- package/dist/terminal-selection.js +72 -0
- package/dist/terminal-text.d.ts +38 -0
- package/dist/terminal-text.js +238 -0
- package/dist/tui.d.ts +170 -0
- package/dist/tui.js +2559 -0
- package/dist/usage.d.ts +13 -0
- package/dist/usage.js +46 -0
- package/dist/user-config.d.ts +48 -0
- package/dist/user-config.js +188 -0
- package/package.json +18 -3
- package/README.md +0 -3
package/dist/mcp-cli.js
ADDED
|
@@ -0,0 +1,647 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import { parse } from 'smol-toml';
|
|
4
|
+
import { PROJECT_MCP_CONFIG_FILENAME, mcpEnvVarNamePattern, mcpHeaderNamePattern, mcpServerNamePattern, normalizeMcpServerEntry, normalizeWorkspaceTrustPath, projectMcpConfigPath, redactMcpServerForDisplay, userConfigPath, workspaceConfigPath, } from '@saturn-universe/protocol';
|
|
5
|
+
import { CliError, UsageError } from './cli-diagnostics.js';
|
|
6
|
+
import { topicHelp } from './cli-help.js';
|
|
7
|
+
import { sendHostCommand } from './host-command.js';
|
|
8
|
+
import { restartHost } from './host-launcher.js';
|
|
9
|
+
import { terminalPrompt } from './menu.js';
|
|
10
|
+
import { updateUserConfigToml } from './user-config.js';
|
|
11
|
+
import { inspectProjectMcpConfig, removeProjectMcpServer, updateProjectMcpServer, writeProjectMcpServer, } from './project-mcp-config.js';
|
|
12
|
+
const mcpHelp = topicHelp('mcp');
|
|
13
|
+
function isPlainObject(value) {
|
|
14
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
15
|
+
return false;
|
|
16
|
+
const proto = Object.getPrototypeOf(value);
|
|
17
|
+
return proto === null || proto === Object.prototype;
|
|
18
|
+
}
|
|
19
|
+
async function readOptionalTomlMcp(filePath) {
|
|
20
|
+
let text;
|
|
21
|
+
try {
|
|
22
|
+
text = await readFile(filePath, 'utf8');
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (error.code === 'ENOENT') {
|
|
26
|
+
return { servers: {}, trustedWorkspaces: [] };
|
|
27
|
+
}
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
let parsed;
|
|
31
|
+
try {
|
|
32
|
+
parsed = parse(text);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
throw new UsageError('无法读取 MCP 配置,请检查 config.toml 格式。');
|
|
36
|
+
}
|
|
37
|
+
const servers = {};
|
|
38
|
+
if (isPlainObject(parsed.mcp_servers)) {
|
|
39
|
+
for (const [id, entry] of Object.entries(parsed.mcp_servers)) {
|
|
40
|
+
if (!mcpServerNamePattern.test(id))
|
|
41
|
+
continue;
|
|
42
|
+
try {
|
|
43
|
+
servers[id] = normalizeMcpServerEntry(entry);
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
// Ignore invalid entries during inspection.
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const trustedWorkspaces = Array.isArray(parsed.trusted_mcp_workspaces)
|
|
51
|
+
? parsed.trusted_mcp_workspaces.filter((item) => typeof item === 'string')
|
|
52
|
+
: [];
|
|
53
|
+
return { servers, trustedWorkspaces };
|
|
54
|
+
}
|
|
55
|
+
function serializeMcpEntry(entry) {
|
|
56
|
+
return {
|
|
57
|
+
transport: entry.transport,
|
|
58
|
+
...(entry.transport === 'stdio'
|
|
59
|
+
? {
|
|
60
|
+
command: entry.command,
|
|
61
|
+
...(entry.args?.length ? { args: [...entry.args] } : {}),
|
|
62
|
+
...(entry.env && Object.keys(entry.env).length ? { env: { ...entry.env } } : {}),
|
|
63
|
+
}
|
|
64
|
+
: {
|
|
65
|
+
url: entry.url,
|
|
66
|
+
...(entry.headers && Object.keys(entry.headers).length ? { headers: { ...entry.headers } } : {}),
|
|
67
|
+
}),
|
|
68
|
+
...(entry.tools?.length ? { tools: [...entry.tools] } : {}),
|
|
69
|
+
...(entry.read_only_tools?.length ? { read_only_tools: [...entry.read_only_tools] } : {}),
|
|
70
|
+
...(entry.timeout_ms !== undefined ? { timeout_ms: entry.timeout_ms } : {}),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
export async function addMcpServerConfig(workdir, name, entry, scope = 'user', env = process.env) {
|
|
74
|
+
if (!mcpServerNamePattern.test(name)) {
|
|
75
|
+
throw new UsageError('服务名称须为 1–64 个字母、数字、连字符或下划线。');
|
|
76
|
+
}
|
|
77
|
+
if (scope === 'project') {
|
|
78
|
+
const filePath = await writeProjectMcpServer(workdir, name, serializeMcpEntry(entry));
|
|
79
|
+
return { name, scope, path: filePath };
|
|
80
|
+
}
|
|
81
|
+
const result = await updateUserConfigToml((config) => {
|
|
82
|
+
const existing = isPlainObject(config.mcp_servers) ? { ...config.mcp_servers } : {};
|
|
83
|
+
existing[name] = serializeMcpEntry(entry);
|
|
84
|
+
config.mcp_servers = existing;
|
|
85
|
+
}, { env, workdir });
|
|
86
|
+
return { name, scope: 'user', path: result.configPath };
|
|
87
|
+
}
|
|
88
|
+
export async function removeMcpServerConfig(workdir, name, scope, env = process.env) {
|
|
89
|
+
if (!mcpServerNamePattern.test(name)) {
|
|
90
|
+
throw new Error(`Invalid MCP server name "${name}".`);
|
|
91
|
+
}
|
|
92
|
+
if (scope === 'project' || !scope) {
|
|
93
|
+
const removedPath = await removeProjectMcpServer(workdir, name);
|
|
94
|
+
if (removedPath)
|
|
95
|
+
return { name, scope: 'project', path: removedPath };
|
|
96
|
+
if (scope === 'project') {
|
|
97
|
+
throw new Error(`MCP server "${name}" not found in ${projectMcpConfigPath(workdir)}.`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
let removedUser = false;
|
|
101
|
+
const result = await updateUserConfigToml((config) => {
|
|
102
|
+
if (!isPlainObject(config.mcp_servers) || !Object.hasOwn(config.mcp_servers, name))
|
|
103
|
+
return;
|
|
104
|
+
const next = { ...config.mcp_servers };
|
|
105
|
+
delete next[name];
|
|
106
|
+
removedUser = true;
|
|
107
|
+
if (Object.keys(next).length > 0) {
|
|
108
|
+
config.mcp_servers = next;
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
delete config.mcp_servers;
|
|
112
|
+
}
|
|
113
|
+
}, { env, workdir });
|
|
114
|
+
if (!removedUser) {
|
|
115
|
+
throw new Error(`MCP server "${name}" not found.`);
|
|
116
|
+
}
|
|
117
|
+
return { name, scope: 'user', path: result.configPath };
|
|
118
|
+
}
|
|
119
|
+
export async function setWorkspaceMcpTrust(workdir, trusted, env = process.env) {
|
|
120
|
+
const normalized = normalizeWorkspaceTrustPath(workdir);
|
|
121
|
+
const result = await updateUserConfigToml((config) => {
|
|
122
|
+
const existing = Array.isArray(config.trusted_mcp_workspaces)
|
|
123
|
+
? config.trusted_mcp_workspaces.filter((item) => typeof item === 'string')
|
|
124
|
+
: [];
|
|
125
|
+
const filtered = existing.filter((item) => normalizeWorkspaceTrustPath(item) !== normalized);
|
|
126
|
+
if (trusted) {
|
|
127
|
+
filtered.push(normalized);
|
|
128
|
+
}
|
|
129
|
+
if (filtered.length > 0) {
|
|
130
|
+
config.trusted_mcp_workspaces = filtered;
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
delete config.trusted_mcp_workspaces;
|
|
134
|
+
}
|
|
135
|
+
}, { env, workdir });
|
|
136
|
+
return { workspace: normalized, trusted, configPath: result.configPath };
|
|
137
|
+
}
|
|
138
|
+
export async function listMcpServersInfo(workdir, liveStatus, env = process.env) {
|
|
139
|
+
const userPath = userConfigPath(env);
|
|
140
|
+
const workspacePath = workspaceConfigPath(workdir);
|
|
141
|
+
const [userToml, workspaceToml, projectMcp] = await Promise.all([
|
|
142
|
+
readOptionalTomlMcp(userPath),
|
|
143
|
+
readOptionalTomlMcp(workspacePath),
|
|
144
|
+
inspectProjectMcpConfig(workdir),
|
|
145
|
+
]);
|
|
146
|
+
const trustedSet = new Set(userToml.trustedWorkspaces.map((item) => normalizeWorkspaceTrustPath(item)));
|
|
147
|
+
const workspaceTrusted = trustedSet.has(normalizeWorkspaceTrustPath(workdir));
|
|
148
|
+
const liveById = new Map((liveStatus?.mcpServers ?? []).map((item) => [item.id, item]));
|
|
149
|
+
const records = [];
|
|
150
|
+
const seen = new Set();
|
|
151
|
+
const pushRecord = (id, scope, source, config, trusted, fallbackStatus) => {
|
|
152
|
+
if (seen.has(id))
|
|
153
|
+
return;
|
|
154
|
+
seen.add(id);
|
|
155
|
+
const live = liveById.get(id);
|
|
156
|
+
records.push({
|
|
157
|
+
id,
|
|
158
|
+
scope,
|
|
159
|
+
source,
|
|
160
|
+
config: redactMcpServerForDisplay(config),
|
|
161
|
+
trusted,
|
|
162
|
+
status: live?.discovery ?? fallbackStatus,
|
|
163
|
+
...(live?.discovery === 'ready' ? { toolCount: live.toolCount } : {}),
|
|
164
|
+
...(live?.error ? { error: live.error } : {}),
|
|
165
|
+
});
|
|
166
|
+
};
|
|
167
|
+
for (const [id, cfg] of Object.entries(workspaceToml.servers)) {
|
|
168
|
+
pushRecord(id, 'workspace', workspacePath, cfg, false, 'trust_required');
|
|
169
|
+
}
|
|
170
|
+
for (const [id, cfg] of Object.entries(userToml.servers)) {
|
|
171
|
+
pushRecord(id, 'user', userPath, cfg, true, 'configured');
|
|
172
|
+
}
|
|
173
|
+
for (const [id, cfg] of Object.entries(projectMcp.servers)) {
|
|
174
|
+
pushRecord(id, 'project', projectMcp.path, cfg, workspaceTrusted, workspaceTrusted ? 'configured' : 'pending_trust');
|
|
175
|
+
}
|
|
176
|
+
for (const live of liveById.values()) {
|
|
177
|
+
if (live.id === PROJECT_MCP_CONFIG_FILENAME || seen.has(live.id))
|
|
178
|
+
continue;
|
|
179
|
+
records.push({
|
|
180
|
+
id: live.id,
|
|
181
|
+
scope: live.scope === 'project' ? 'project' : live.scope === 'workspace' ? 'workspace' : 'user',
|
|
182
|
+
source: live.scope ?? 'host',
|
|
183
|
+
config: live.transport === 'http'
|
|
184
|
+
? { transport: 'http', url: '(host)' }
|
|
185
|
+
: { transport: 'stdio', command: '(host)' },
|
|
186
|
+
trusted: live.discovery !== 'pending_trust' && live.discovery !== 'trust_required',
|
|
187
|
+
status: live.discovery,
|
|
188
|
+
...(live.discovery === 'ready' ? { toolCount: live.toolCount } : {}),
|
|
189
|
+
...(live.error ? { error: live.error } : {}),
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
records.sort((a, b) => a.id.localeCompare(b.id));
|
|
193
|
+
const liveJsonError = liveById.get(PROJECT_MCP_CONFIG_FILENAME)?.error;
|
|
194
|
+
const mcpJsonError = projectMcp.parseError ?? liveJsonError;
|
|
195
|
+
return {
|
|
196
|
+
servers: records,
|
|
197
|
+
workspaceTrusted,
|
|
198
|
+
...(mcpJsonError ? { mcpJsonError } : {}),
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
export function formatMcpServerStatus(srv) {
|
|
202
|
+
const tools = srv.status === 'ready' && srv.toolCount !== undefined ? ` · ${srv.toolCount} tools` : '';
|
|
203
|
+
const error = srv.error ? ` · ${srv.error}` : '';
|
|
204
|
+
return `[${srv.scope}] ${srv.id} (${srv.config.transport}) · ${srv.status}${tools}${error}`;
|
|
205
|
+
}
|
|
206
|
+
export async function promptMcpSecret(label) {
|
|
207
|
+
if (!process.stdin.isTTY || !process.stderr.isTTY)
|
|
208
|
+
throw new UsageError('MCP 授权需要交互式终端。');
|
|
209
|
+
const prompt = terminalPrompt(process.stdin, process.stderr);
|
|
210
|
+
try {
|
|
211
|
+
return await prompt.question(label, true);
|
|
212
|
+
}
|
|
213
|
+
finally {
|
|
214
|
+
prompt.close();
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
export async function authenticateMcpServer(workdir, args, options) {
|
|
218
|
+
let parsed;
|
|
219
|
+
try {
|
|
220
|
+
parsed = parseArgs({
|
|
221
|
+
args: [...args],
|
|
222
|
+
allowPositionals: true,
|
|
223
|
+
strict: true,
|
|
224
|
+
options: { header: { type: 'string' }, json: { type: 'boolean' } },
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
throw new UsageError('用法:mcp auth <name> [--header NAME]');
|
|
229
|
+
}
|
|
230
|
+
const [name] = parsed.positionals;
|
|
231
|
+
const header = parsed.values.header ?? 'Authorization';
|
|
232
|
+
if (!name || !mcpServerNamePattern.test(name) || parsed.positionals.length !== 1)
|
|
233
|
+
throw new UsageError('用法:mcp auth <name> [--header NAME]');
|
|
234
|
+
if (header.length > 128 ||
|
|
235
|
+
!mcpHeaderNamePattern.test(header) ||
|
|
236
|
+
/^(?:mcp-|accept$|content-type$|content-length$|host$|connection$|transfer-encoding$|proxy-)/i.test(header))
|
|
237
|
+
throw new UsageError('请指定有效的 MCP 认证 Header 名称。');
|
|
238
|
+
const env = options.env ?? process.env;
|
|
239
|
+
const [user, workspace, project] = await Promise.all([
|
|
240
|
+
readOptionalTomlMcp(userConfigPath(env)),
|
|
241
|
+
readOptionalTomlMcp(workspaceConfigPath(workdir)),
|
|
242
|
+
inspectProjectMcpConfig(workdir),
|
|
243
|
+
]);
|
|
244
|
+
const live = options.before?.mcpServers?.find((srv) => srv.id === name);
|
|
245
|
+
if (live?.scope === 'explicit' || Object.hasOwn(workspace.servers, name))
|
|
246
|
+
throw new UsageError('此 MCP 服务由其他配置覆盖。请使用用户 config.toml 或项目 .mcp.json 中的服务。');
|
|
247
|
+
const fromUser = Object.hasOwn(user.servers, name);
|
|
248
|
+
const current = fromUser
|
|
249
|
+
? user.servers[name]
|
|
250
|
+
: Object.hasOwn(project.servers, name)
|
|
251
|
+
? project.servers[name]
|
|
252
|
+
: undefined;
|
|
253
|
+
if (!current || current.transport !== 'http')
|
|
254
|
+
throw new UsageError('请指定已在用户 config.toml 或项目 .mcp.json 中配置的 HTTP MCP 服务。');
|
|
255
|
+
const bearer = parsed.values.header === undefined;
|
|
256
|
+
const label = bearer ? 'Bearer Token' : header;
|
|
257
|
+
const input = await options.prompt(`${name} [${fromUser ? 'user' : 'project'}] ${label}: `);
|
|
258
|
+
if (input === null)
|
|
259
|
+
return null;
|
|
260
|
+
const valid = bearer
|
|
261
|
+
? /^[A-Za-z0-9._~+/-]+=*$/.test(input)
|
|
262
|
+
: /^[!-~](?:[ -~]*[!-~])?$/.test(input) && !input.includes('${');
|
|
263
|
+
if (!valid || input.length > 4096)
|
|
264
|
+
throw new UsageError('请输入有效的单行 MCP 凭据。');
|
|
265
|
+
const value = bearer ? `Bearer ${input}` : input;
|
|
266
|
+
const update = (raw) => {
|
|
267
|
+
if (!isPlainObject(raw))
|
|
268
|
+
throw new UsageError('MCP 配置在录入期间已变更,请重新执行授权。');
|
|
269
|
+
const latest = mcpEntry(raw);
|
|
270
|
+
if (latest.transport !== 'http' || latest.url !== current.url)
|
|
271
|
+
throw new UsageError('MCP 服务地址在录入期间已变更,请重新执行授权。');
|
|
272
|
+
const headers = Object.fromEntries(Object.entries(latest.headers ?? {}).filter(([key]) => key.toLowerCase() !== header.toLowerCase()));
|
|
273
|
+
return { ...raw, headers: { ...headers, [header]: value } };
|
|
274
|
+
};
|
|
275
|
+
if (fromUser) {
|
|
276
|
+
await updateUserConfigToml((config) => {
|
|
277
|
+
const servers = config.mcp_servers;
|
|
278
|
+
if (!isPlainObject(servers) || !Object.hasOwn(servers, name))
|
|
279
|
+
throw new UsageError('MCP 配置在录入期间已变更,请重新执行授权。');
|
|
280
|
+
config.mcp_servers = { ...servers, [name]: update(servers[name]) };
|
|
281
|
+
}, { env, workdir });
|
|
282
|
+
}
|
|
283
|
+
else {
|
|
284
|
+
await updateProjectMcpServer(workdir, name, update);
|
|
285
|
+
}
|
|
286
|
+
const info = await listMcpServersInfo(workdir, await options.restart(), env);
|
|
287
|
+
const server = info.servers.find((srv) => srv.id === name);
|
|
288
|
+
if (!server)
|
|
289
|
+
throw new Error('已保存凭据,刷新后未找到对应的 MCP 服务。');
|
|
290
|
+
return { server, json: parsed.values.json === true };
|
|
291
|
+
}
|
|
292
|
+
async function queryRunningHostStatus(workdir) {
|
|
293
|
+
return sendHostCommand(workdir, { type: 'host.status' }, { commandId: 'cli-mcp-status', timeoutMs: 1200 }).catch(() => undefined);
|
|
294
|
+
}
|
|
295
|
+
function parseAddArgs(args) {
|
|
296
|
+
let scope = 'user';
|
|
297
|
+
let transport;
|
|
298
|
+
const envMap = {};
|
|
299
|
+
const headerMap = {};
|
|
300
|
+
let json = false;
|
|
301
|
+
let name;
|
|
302
|
+
let target;
|
|
303
|
+
const targetArgs = [];
|
|
304
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
305
|
+
const arg = args[i];
|
|
306
|
+
if (arg === '--') {
|
|
307
|
+
const rest = args.slice(i + 1);
|
|
308
|
+
if (!name) {
|
|
309
|
+
if (rest.length < 2)
|
|
310
|
+
throw new CliError('USAGE');
|
|
311
|
+
name = rest[0];
|
|
312
|
+
target = rest[1];
|
|
313
|
+
targetArgs.push(...rest.slice(2));
|
|
314
|
+
}
|
|
315
|
+
else {
|
|
316
|
+
if (!rest.length)
|
|
317
|
+
throw new CliError('USAGE');
|
|
318
|
+
target = rest[0];
|
|
319
|
+
targetArgs.push(...rest.slice(1));
|
|
320
|
+
}
|
|
321
|
+
break;
|
|
322
|
+
}
|
|
323
|
+
if (arg === '--json') {
|
|
324
|
+
json = true;
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
if (arg === '--scope' || arg.startsWith('--scope=')) {
|
|
328
|
+
const val = arg === '--scope' ? args[++i] : arg.slice('--scope='.length);
|
|
329
|
+
if (val !== 'user' && val !== 'project')
|
|
330
|
+
throw new CliError('USAGE');
|
|
331
|
+
scope = val;
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
if (arg === '--transport' || arg.startsWith('--transport=')) {
|
|
335
|
+
const val = arg === '--transport' ? args[++i] : arg.slice('--transport='.length);
|
|
336
|
+
const norm = val?.toLowerCase();
|
|
337
|
+
if (norm === 'stdio')
|
|
338
|
+
transport = 'stdio';
|
|
339
|
+
else if (norm === 'http' || norm === 'streamable-http')
|
|
340
|
+
transport = 'http';
|
|
341
|
+
else
|
|
342
|
+
throw new CliError('USAGE');
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
if (arg === '--env' || arg === '-e' || arg.startsWith('--env=')) {
|
|
346
|
+
const raw = arg === '--env' || arg === '-e' ? args[++i] : arg.slice('--env='.length);
|
|
347
|
+
if (!raw)
|
|
348
|
+
throw new CliError('USAGE');
|
|
349
|
+
const eq = raw.indexOf('=');
|
|
350
|
+
if (eq <= 0)
|
|
351
|
+
throw new Error(`Invalid --env "${raw}". Expected KEY=VALUE.`);
|
|
352
|
+
const key = raw.slice(0, eq).trim();
|
|
353
|
+
const val = raw.slice(eq + 1);
|
|
354
|
+
if (!mcpEnvVarNamePattern.test(key))
|
|
355
|
+
throw new Error(`Invalid environment variable name "${key}".`);
|
|
356
|
+
envMap[key] = val;
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
if (arg === '--header' || arg === '-H' || arg.startsWith('--header=')) {
|
|
360
|
+
const raw = arg === '--header' || arg === '-H' ? args[++i] : arg.slice('--header='.length);
|
|
361
|
+
if (!raw)
|
|
362
|
+
throw new CliError('USAGE');
|
|
363
|
+
const colon = raw.indexOf(':');
|
|
364
|
+
if (colon <= 0)
|
|
365
|
+
throw new Error(`Invalid --header "${raw}". Expected "Key: Value".`);
|
|
366
|
+
const key = raw.slice(0, colon).trim();
|
|
367
|
+
const val = raw.slice(colon + 1).trim();
|
|
368
|
+
if (!mcpHeaderNamePattern.test(key))
|
|
369
|
+
throw new Error(`Invalid HTTP header name "${key}".`);
|
|
370
|
+
headerMap[key] = val;
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
if (arg.startsWith('-')) {
|
|
374
|
+
throw new CliError('USAGE');
|
|
375
|
+
}
|
|
376
|
+
if (!name) {
|
|
377
|
+
name = arg;
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
target = arg;
|
|
381
|
+
targetArgs.push(...args.slice(i + 1));
|
|
382
|
+
break;
|
|
383
|
+
}
|
|
384
|
+
if (!name || !target)
|
|
385
|
+
throw new CliError('USAGE');
|
|
386
|
+
return {
|
|
387
|
+
name,
|
|
388
|
+
scope,
|
|
389
|
+
...(transport ? { transport } : {}),
|
|
390
|
+
envMap,
|
|
391
|
+
headerMap,
|
|
392
|
+
target,
|
|
393
|
+
targetArgs,
|
|
394
|
+
json,
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
function mcpEntry(raw) {
|
|
398
|
+
try {
|
|
399
|
+
return normalizeMcpServerEntry(raw);
|
|
400
|
+
}
|
|
401
|
+
catch {
|
|
402
|
+
throw new UsageError('MCP 服务配置无效。请检查 transport/type、HTTP(S) url 或 stdio command 及其选项。');
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
function parseMcpImport(name, json) {
|
|
406
|
+
let raw;
|
|
407
|
+
try {
|
|
408
|
+
raw = JSON.parse(json);
|
|
409
|
+
}
|
|
410
|
+
catch {
|
|
411
|
+
throw new UsageError('JSON 格式有误。请检查括号、逗号和引号。');
|
|
412
|
+
}
|
|
413
|
+
if (isPlainObject(raw) && Object.hasOwn(raw, 'mcpServers')) {
|
|
414
|
+
if (!isPlainObject(raw.mcpServers))
|
|
415
|
+
throw new UsageError('mcpServers 必须是包含服务名称的 JSON 对象。');
|
|
416
|
+
if (!Object.hasOwn(raw.mcpServers, name))
|
|
417
|
+
throw new UsageError('mcpServers 中没有与输入名称匹配的服务。');
|
|
418
|
+
return mcpEntry(raw.mcpServers[name]);
|
|
419
|
+
}
|
|
420
|
+
return mcpEntry(raw);
|
|
421
|
+
}
|
|
422
|
+
export async function runMcpCommand(args, workdir, env = process.env) {
|
|
423
|
+
const sub = args[0]?.toLowerCase() ?? 'list';
|
|
424
|
+
if (!sub || sub === 'help' || sub === '--help' || sub === '-h') {
|
|
425
|
+
process.stdout.write(mcpHelp + '\n');
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
if (sub === 'auth') {
|
|
429
|
+
const before = await queryRunningHostStatus(workdir);
|
|
430
|
+
if (before) {
|
|
431
|
+
const sessions = await sendHostCommand(workdir, { type: 'session.list' });
|
|
432
|
+
if (sessions.some(({ latestRunStatus }) => latestRunStatus && ['created', 'running', 'paused', 'cancelling'].includes(latestRunStatus)))
|
|
433
|
+
throw new UsageError('当前有正在执行的任务,请等待完成后再变更 MCP 设置。');
|
|
434
|
+
}
|
|
435
|
+
if (before?.configSource === 'explicit')
|
|
436
|
+
throw new UsageError('请在使用自定义配置启动的 Saturn 工作台中运行 /mcp auth,以保留启动选项。');
|
|
437
|
+
const result = await authenticateMcpServer(workdir, args.slice(1), {
|
|
438
|
+
prompt: promptMcpSecret,
|
|
439
|
+
...(before ? { before } : {}),
|
|
440
|
+
env,
|
|
441
|
+
restart: async () => (await restartHost(workdir, undefined, {
|
|
442
|
+
detach: true,
|
|
443
|
+
...(before?.activeMode.ref ? { mode: before.activeMode.ref } : {}),
|
|
444
|
+
...(before?.selectedProfile ? { profile: before.selectedProfile } : {}),
|
|
445
|
+
})).status,
|
|
446
|
+
});
|
|
447
|
+
if (!result)
|
|
448
|
+
return;
|
|
449
|
+
const { server, json } = result;
|
|
450
|
+
process.stdout.write((json ? JSON.stringify({ ok: true, server }) : formatMcpServerStatus(server)) + '\n');
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
if (sub === 'add') {
|
|
454
|
+
const parsed = parseAddArgs(args.slice(1));
|
|
455
|
+
const resolvedTransport = parsed.transport ?? (/^https?:\/\//i.test(parsed.target) ? 'http' : 'stdio');
|
|
456
|
+
if (resolvedTransport === 'stdio' && Object.keys(parsed.headerMap).length > 0) {
|
|
457
|
+
throw new UsageError('--header 仅适用于 HTTP MCP 服务。');
|
|
458
|
+
}
|
|
459
|
+
if (resolvedTransport === 'http' &&
|
|
460
|
+
(Object.keys(parsed.envMap).length > 0 || parsed.targetArgs.length > 0)) {
|
|
461
|
+
throw new UsageError('--env 和命令参数仅适用于 stdio MCP 服务。');
|
|
462
|
+
}
|
|
463
|
+
const entry = mcpEntry(resolvedTransport === 'http'
|
|
464
|
+
? {
|
|
465
|
+
transport: 'http',
|
|
466
|
+
url: parsed.target,
|
|
467
|
+
...(Object.keys(parsed.headerMap).length ? { headers: parsed.headerMap } : {}),
|
|
468
|
+
}
|
|
469
|
+
: {
|
|
470
|
+
transport: 'stdio',
|
|
471
|
+
command: parsed.target,
|
|
472
|
+
...(parsed.targetArgs.length ? { args: parsed.targetArgs } : {}),
|
|
473
|
+
...(Object.keys(parsed.envMap).length ? { env: parsed.envMap } : {}),
|
|
474
|
+
});
|
|
475
|
+
const saved = await addMcpServerConfig(workdir, parsed.name, entry, parsed.scope, env);
|
|
476
|
+
if (parsed.json) {
|
|
477
|
+
process.stdout.write(JSON.stringify({ ok: true, server: saved }) + '\n');
|
|
478
|
+
}
|
|
479
|
+
else {
|
|
480
|
+
process.stdout.write(`Added MCP server "${saved.name}" (${saved.scope}) to ${saved.path}\n`);
|
|
481
|
+
}
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
if (sub === 'add-json') {
|
|
485
|
+
let parsed;
|
|
486
|
+
try {
|
|
487
|
+
parsed = parseArgs({
|
|
488
|
+
args: args.slice(1),
|
|
489
|
+
allowPositionals: true,
|
|
490
|
+
strict: true,
|
|
491
|
+
options: {
|
|
492
|
+
scope: { type: 'string' },
|
|
493
|
+
json: { type: 'boolean' },
|
|
494
|
+
},
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
catch {
|
|
498
|
+
throw new CliError('USAGE');
|
|
499
|
+
}
|
|
500
|
+
const [name, rawJson] = parsed.positionals;
|
|
501
|
+
if (!name || rawJson === undefined || parsed.positionals.length > 2)
|
|
502
|
+
throw new CliError('USAGE');
|
|
503
|
+
const scope = parsed.values.scope === undefined ? 'user' : parsed.values.scope;
|
|
504
|
+
if (scope !== 'user' && scope !== 'project')
|
|
505
|
+
throw new CliError('USAGE');
|
|
506
|
+
const entry = parseMcpImport(name, rawJson);
|
|
507
|
+
const saved = await addMcpServerConfig(workdir, name, entry, scope, env);
|
|
508
|
+
if (parsed.values.json) {
|
|
509
|
+
process.stdout.write(JSON.stringify({ ok: true, server: saved }) + '\n');
|
|
510
|
+
}
|
|
511
|
+
else {
|
|
512
|
+
process.stdout.write(`Added MCP server "${saved.name}" (${saved.scope}) to ${saved.path}\n`);
|
|
513
|
+
}
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
if (sub === 'list') {
|
|
517
|
+
let parsed;
|
|
518
|
+
try {
|
|
519
|
+
parsed = parseArgs({
|
|
520
|
+
args: args.slice(1),
|
|
521
|
+
allowPositionals: false,
|
|
522
|
+
strict: true,
|
|
523
|
+
options: {
|
|
524
|
+
json: { type: 'boolean' },
|
|
525
|
+
},
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
catch {
|
|
529
|
+
throw new CliError('USAGE');
|
|
530
|
+
}
|
|
531
|
+
const liveStatus = await queryRunningHostStatus(workdir);
|
|
532
|
+
const info = await listMcpServersInfo(workdir, liveStatus, env);
|
|
533
|
+
if (parsed.values.json) {
|
|
534
|
+
process.stdout.write(JSON.stringify({ ok: true, ...info }) + '\n');
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
if (!info.servers.length && !info.mcpJsonError) {
|
|
538
|
+
process.stdout.write('当前还没有外部工具服务。运行 saturn mcp 可以添加。\n');
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
for (const srv of info.servers) {
|
|
542
|
+
const target = srv.config.transport === 'http'
|
|
543
|
+
? srv.config.url
|
|
544
|
+
: [srv.config.command, ...(srv.config.args ?? [])].join(' ');
|
|
545
|
+
const toolsText = srv.toolCount !== undefined ? ` · ${srv.toolCount} tools` : '';
|
|
546
|
+
const errText = srv.error ? ` · ${srv.error}` : '';
|
|
547
|
+
process.stdout.write(`[${srv.scope}] ${srv.id} (${srv.config.transport}) · ${srv.status}${toolsText} · ${target}${errText}\n`);
|
|
548
|
+
}
|
|
549
|
+
if (info.mcpJsonError) {
|
|
550
|
+
process.stdout.write(`[project] .mcp.json · error: ${info.mcpJsonError}\n`);
|
|
551
|
+
}
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
if (sub === 'get') {
|
|
555
|
+
let parsed;
|
|
556
|
+
try {
|
|
557
|
+
parsed = parseArgs({
|
|
558
|
+
args: args.slice(1),
|
|
559
|
+
allowPositionals: true,
|
|
560
|
+
strict: true,
|
|
561
|
+
options: {
|
|
562
|
+
json: { type: 'boolean' },
|
|
563
|
+
},
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
catch {
|
|
567
|
+
throw new CliError('USAGE');
|
|
568
|
+
}
|
|
569
|
+
const name = parsed.positionals[0];
|
|
570
|
+
if (!name || parsed.positionals.length > 1)
|
|
571
|
+
throw new CliError('USAGE');
|
|
572
|
+
const liveStatus = await queryRunningHostStatus(workdir);
|
|
573
|
+
const info = await listMcpServersInfo(workdir, liveStatus, env);
|
|
574
|
+
const found = info.servers.find((item) => item.id === name);
|
|
575
|
+
if (!found) {
|
|
576
|
+
throw new Error(`MCP server "${name}" not found.`);
|
|
577
|
+
}
|
|
578
|
+
if (parsed.values.json) {
|
|
579
|
+
process.stdout.write(JSON.stringify({ ok: true, server: found }) + '\n');
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
process.stdout.write([
|
|
583
|
+
`${found.id} [${found.scope}] (${found.config.transport})`,
|
|
584
|
+
` status: ${found.status}${found.toolCount !== undefined ? ` (${found.toolCount} tools)` : ''}`,
|
|
585
|
+
` source: ${found.source}`,
|
|
586
|
+
` config: ${JSON.stringify(found.config)}`,
|
|
587
|
+
...(found.error ? [` error: ${found.error}`] : []),
|
|
588
|
+
].join('\n') + '\n');
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
if (sub === 'remove' || sub === 'rm') {
|
|
592
|
+
let parsed;
|
|
593
|
+
try {
|
|
594
|
+
parsed = parseArgs({
|
|
595
|
+
args: args.slice(1),
|
|
596
|
+
allowPositionals: true,
|
|
597
|
+
strict: true,
|
|
598
|
+
options: {
|
|
599
|
+
scope: { type: 'string' },
|
|
600
|
+
json: { type: 'boolean' },
|
|
601
|
+
},
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
catch {
|
|
605
|
+
throw new CliError('USAGE');
|
|
606
|
+
}
|
|
607
|
+
const name = parsed.positionals[0];
|
|
608
|
+
if (!name || parsed.positionals.length > 1)
|
|
609
|
+
throw new CliError('USAGE');
|
|
610
|
+
const scope = parsed.values.scope;
|
|
611
|
+
if (scope !== undefined && scope !== 'user' && scope !== 'project')
|
|
612
|
+
throw new CliError('USAGE');
|
|
613
|
+
const removed = await removeMcpServerConfig(workdir, name, scope, env);
|
|
614
|
+
if (parsed.values.json) {
|
|
615
|
+
process.stdout.write(JSON.stringify({ ok: true, removed }) + '\n');
|
|
616
|
+
}
|
|
617
|
+
else {
|
|
618
|
+
process.stdout.write(`Removed MCP server "${removed.name}" (${removed.scope}) from ${removed.path}\n`);
|
|
619
|
+
}
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
if (sub === 'trust' || sub === 'untrust') {
|
|
623
|
+
let parsed;
|
|
624
|
+
try {
|
|
625
|
+
parsed = parseArgs({
|
|
626
|
+
args: args.slice(1),
|
|
627
|
+
allowPositionals: false,
|
|
628
|
+
strict: true,
|
|
629
|
+
options: {
|
|
630
|
+
json: { type: 'boolean' },
|
|
631
|
+
},
|
|
632
|
+
});
|
|
633
|
+
}
|
|
634
|
+
catch {
|
|
635
|
+
throw new CliError('USAGE');
|
|
636
|
+
}
|
|
637
|
+
const updated = await setWorkspaceMcpTrust(workdir, sub === 'trust', env);
|
|
638
|
+
if (parsed.values.json) {
|
|
639
|
+
process.stdout.write(JSON.stringify({ ok: true, ...updated }) + '\n');
|
|
640
|
+
}
|
|
641
|
+
else {
|
|
642
|
+
process.stdout.write(`${updated.trusted ? 'Trusted' : 'Untrusted'} workspace ${updated.workspace} in ${updated.configPath}\n`);
|
|
643
|
+
}
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
throw new CliError('USAGE');
|
|
647
|
+
}
|
package/dist/menu.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type ChoicePrompt } from './choice-menu.js';
|
|
2
|
+
export interface AuthPrompt extends ChoicePrompt {
|
|
3
|
+
close(): void;
|
|
4
|
+
}
|
|
5
|
+
export declare function terminalPrompt(input: NodeJS.ReadStream, output: NodeJS.WriteStream): AuthPrompt;
|
|
6
|
+
export declare function askChoice(prompt: AuthPrompt, print: (s: string) => void, title: string, labels: readonly string[]): Promise<number>;
|
|
7
|
+
export declare function pickAction(title: string, labels: readonly string[]): Promise<number>;
|