pi-web-ui 0.103.3 → 0.104.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.
Files changed (38) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/server/agent-formatters.js +9 -1
  3. package/dist/server/agent-service-daemon.js +4 -3
  4. package/dist/server/agent-service.js +586 -44
  5. package/dist/server/compaction-markers.js +111 -3
  6. package/dist/server/delegate-mode.js +2 -0
  7. package/dist/server/dispatch-domain-handlers.js +25 -0
  8. package/dist/server/dsh/dsh-agent-service.js +265 -11
  9. package/dist/server/goal-review-gate.js +2 -0
  10. package/dist/server/index.js +1 -0
  11. package/dist/server/market-service.js +36 -9
  12. package/dist/server/mcp-agent-tool.js +164 -0
  13. package/dist/server/mcp-manager.js +182 -0
  14. package/dist/server/plan-mode.js +3 -0
  15. package/dist/server/plugin-api-catalog.js +24 -0
  16. package/dist/server/plugins.js +113 -0
  17. package/dist/server/preset-share.js +52 -1
  18. package/dist/server/remote-ssh-service.js +90 -25
  19. package/dist/server/sandbox-service.js +705 -0
  20. package/dist/server/sandbox-tool.js +365 -0
  21. package/dist/server/session-parser.js +48 -21
  22. package/dist/server/terminals.js +210 -10
  23. package/dist/server/tool-manager.js +24 -0
  24. package/dist/server/webui-context.js +6 -0
  25. package/dist/server/workspace-snapshot.js +51 -13
  26. package/package.json +1 -1
  27. package/plugin-sdk/index.d.ts +39 -0
  28. package/plugin-sdk/index.mjs +14 -0
  29. package/plugins/catalog.json +101 -2
  30. package/themes/zhujian-dark.css +711 -0
  31. package/themes/zhujian.css +760 -0
  32. package/web/dist/assets/{TerminalPanel-CAqMqC49.js → TerminalPanel-28naZdcs.js} +1 -1
  33. package/web/dist/assets/index-DbGGBf5I.js +680 -0
  34. package/web/dist/assets/index-RqIdFOsh.css +1 -0
  35. package/web/dist/index.html +2 -2
  36. package/web/dist/sw.js +1 -1
  37. package/web/dist/assets/index-CYQdZEbx.css +0 -1
  38. package/web/dist/assets/index-Dt7CQ_Z6.js +0 -680
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
10
  import { dirname, join } from "node:path";
11
+ import { validateFetchUrl } from "./preset-share.js";
11
12
  const DEFAULT_TIMEOUT_MS = 10_000;
12
13
  const CACHE_TTL_MS = 60 * 60 * 1000; // 1 小时缓存
13
14
  /** 获取 GitHub Token(优先使用配置的预设分享令牌或标准环境变量) */
@@ -59,7 +60,10 @@ function writeCache(cacheFile, data) {
59
60
  /** 从公开 API 或仓库拉取 MCP 服务器列表 */
60
61
  export async function fetchRemoteMcpMarket(opts) {
61
62
  const source = opts.source || "smithery";
62
- const cacheKey = `mcp-market-${source.replace(/[^a-zA-Z0-9_-]/g, "_")}-${opts.query || "all"}.json`;
63
+ // query 与 source 同样消毒进缓存 key:query 未消毒时 `q/../../x` 会经 join
64
+ // 归一化逃出 market-cache 目录(dataDir 内任意路径读写)
65
+ const sanitizeCacheKey = (s) => s.replace(/[^a-zA-Z0-9_-]/g, "_");
66
+ const cacheKey = `mcp-market-${sanitizeCacheKey(source)}-${sanitizeCacheKey(opts.query || "all")}.json`;
63
67
  const cacheFile = join(opts.dataDir, "market-cache", cacheKey);
64
68
  if (!opts.refresh) {
65
69
  const cached = readCache(cacheFile);
@@ -134,7 +138,13 @@ export async function fetchRemoteMcpMarket(opts) {
134
138
  return { ok: true, servers, source: "github", total: servers.length };
135
139
  }
136
140
  // 自定义 URL(支持返回 JSON 格式的 servers 列表)
137
- const customRes = await fetch(source, {
141
+ // SSRF 收口:与 preset-share 同一口径——自定义源也只允许 http/https 公网地址,
142
+ // 否则内网/回环地址可被当作市场源探测(preset_import_url 有校验,此处原本没有)
143
+ const validated = validateFetchUrl(source);
144
+ if (!validated.ok) {
145
+ throw new Error(validated.reason === "scheme" ? "自定义目录仅支持 http/https 地址" : "自定义目录不允许内网/回环地址");
146
+ }
147
+ const customRes = await fetch(validated.url, {
138
148
  headers: fetchHeaders(),
139
149
  signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
140
150
  });
@@ -173,13 +183,17 @@ export async function fetchRemoteSkillMarket(opts) {
173
183
  }
174
184
  try {
175
185
  // 1. 优先尝试读取 repo 下的 skills 目录;若不存在则尝试根目录
186
+ // skillPrefix 记录技能实际所在目录——SKILL.md 的 raw 地址必须按它拼,
187
+ // 否则根目录仓库的描述抓取全部 404(fetchRemoteSkillContent 同理双分支)
176
188
  let apiUrl = `https://api.github.com/repos/${repo}/contents/skills`;
189
+ let skillPrefix = "skills";
177
190
  let res = await fetch(apiUrl, {
178
191
  headers: fetchHeaders(),
179
192
  signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
180
193
  });
181
194
  if (res.status === 404) {
182
195
  apiUrl = `https://api.github.com/repos/${repo}/contents`;
196
+ skillPrefix = "";
183
197
  res = await fetch(apiUrl, {
184
198
  headers: fetchHeaders(),
185
199
  signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
@@ -191,17 +205,30 @@ export async function fetchRemoteSkillMarket(opts) {
191
205
  const items = (await res.json());
192
206
  const skillDirs = items.filter((item) => item.type === "dir" && !item.name.startsWith("."));
193
207
  // 2. 并发读取每个 skill 的 SKILL.md 提取描述(按 raw github 内容读取,避开 GitHub API rate limit)
208
+ // 默认分支 main/master 双尝试(仓库默认分支为 master 时 main 404)
209
+ const fetchSkillDoc = async (id) => {
210
+ const base = skillPrefix ? `${skillPrefix}/${id}/SKILL.md` : `${id}/SKILL.md`;
211
+ for (const branch of ["main", "master"]) {
212
+ try {
213
+ const rawRes = await fetch(`https://raw.githubusercontent.com/${repo}/${branch}/${base}`, {
214
+ headers: { "User-Agent": "pi-web-ui" },
215
+ signal: AbortSignal.timeout(5000),
216
+ });
217
+ if (rawRes.ok)
218
+ return await rawRes.text();
219
+ }
220
+ catch {
221
+ /* try next branch / fallback to default description */
222
+ }
223
+ }
224
+ return null;
225
+ };
194
226
  const skills = await Promise.all(skillDirs.map(async (dir) => {
195
227
  const id = dir.name;
196
- const rawUrl = `https://raw.githubusercontent.com/${repo}/main/skills/${id}/SKILL.md`;
197
228
  let description = `Agent skill ${id} from ${repo}`;
198
229
  try {
199
- const rawRes = await fetch(rawUrl, {
200
- headers: { "User-Agent": "pi-web-ui" },
201
- signal: AbortSignal.timeout(5000),
202
- });
203
- if (rawRes.ok) {
204
- const text = await rawRes.text();
230
+ const text = await fetchSkillDoc(id);
231
+ if (text) {
205
232
  const descMatch = text.match(/description:\s*(?:>|\|)?\s*([^\r\n]+)/);
206
233
  if (descMatch && descMatch[1].trim()) {
207
234
  description = descMatch[1].trim();
@@ -0,0 +1,164 @@
1
+ /**
2
+ * mcp-agent-tool.ts — Agent 工具 `mcp_manage`:让 AI 便捷地检查、安装、移除与重载 MCP 服务器。
3
+ *
4
+ * 约定:
5
+ * - 工具定义(description / promptSnippet / promptGuidelines)保持精简纯英文;
6
+ * - 单次调用返回文本走 pick(lang, zh, en, key);
7
+ * - 安装或移除后立即触发 McpBridge.reload() + 会话工具表热同步(syncPluginToolsIntoSession),
8
+ * 新挂载的远端工具在同一对话下一拍即可直接调用。
9
+ */
10
+ import { defineTool } from "@earendil-works/pi-coding-agent";
11
+ import { Type } from "typebox";
12
+ import { pick } from "./i18n.js";
13
+ import { MCP_MANAGE_TOOL_NAME } from "./tool-manager.js";
14
+ function formatServerLine(s) {
15
+ const target = s.url ? s.url : [s.command, ...(s.args ?? [])].filter(Boolean).join(" ");
16
+ const toolNames = (s.tools ?? []).map((t) => t.name).join(", ");
17
+ const toolSuffix = toolNames ? ` | tools: ${toolNames}` : "";
18
+ const errSuffix = s.error ? ` | error: ${s.error}` : "";
19
+ return `- ${s.name} [${s.scope}] (${s.status}${s.enabled === false ? ", disabled" : ""}): ${target}${toolSuffix}${errSuffix}`;
20
+ }
21
+ export function makeMcpManageTool(host, lang) {
22
+ const getLang = lang ?? (() => "en");
23
+ const reply = (text, details = {}) => ({
24
+ content: [{ type: "text", text }],
25
+ details,
26
+ });
27
+ return defineTool({
28
+ name: MCP_MANAGE_TOOL_NAME,
29
+ label: "Manage MCP servers",
30
+ description: "Inspect, verify, install, remove, or reload Model Context Protocol (MCP) servers in project (.pi/mcp.json) or global (~/.pi/agent/mcp.json) config and sync their tools into the active session.",
31
+ promptSnippet: "check whether an MCP server is installed or install/configure one",
32
+ promptGuidelines: [
33
+ "Run mcp_manage with action='check' before installing an MCP server to avoid duplicate entries.",
34
+ "Prefer package shorthand (e.g. package='@modelcontextprotocol/server-filesystem') for npm-based stdio MCP servers.",
35
+ ],
36
+ parameters: Type.Object({
37
+ action: Type.Union([
38
+ Type.Literal("list"),
39
+ Type.Literal("check"),
40
+ Type.Literal("install"),
41
+ Type.Literal("remove"),
42
+ Type.Literal("reload"),
43
+ ], {
44
+ description: "Operation to perform: list, check, install, remove, or reload.",
45
+ }),
46
+ query: Type.Optional(Type.String({
47
+ description: "check: server name, npm package name, command, or URL substring to look up.",
48
+ })),
49
+ name: Type.Optional(Type.String({
50
+ description: "install/remove: server identifier (letters, digits, underscore, hyphen). Auto-derived from package/url if omitted on install.",
51
+ })),
52
+ package: Type.Optional(Type.String({
53
+ description: "install: npm package name shorthand (e.g. '@modelcontextprotocol/server-memory'); expands to npx -y <package>.",
54
+ })),
55
+ command: Type.Optional(Type.String({
56
+ description: "install: executable for stdio MCP server (e.g. 'npx', 'uvx', 'node', 'python').",
57
+ })),
58
+ args: Type.Optional(Type.Array(Type.String(), {
59
+ description: "install: command arguments (appended after package when package is set).",
60
+ })),
61
+ env: Type.Optional(Type.Record(Type.String(), Type.String(), {
62
+ description: "install: environment variables passed to the stdio MCP server.",
63
+ })),
64
+ cwd: Type.Optional(Type.String({
65
+ description: "install: working directory for the stdio MCP server.",
66
+ })),
67
+ url: Type.Optional(Type.String({
68
+ description: "install: endpoint URL for http / streamable-http MCP server.",
69
+ })),
70
+ headers: Type.Optional(Type.Record(Type.String(), Type.String(), {
71
+ description: "install: HTTP headers for remote MCP server.",
72
+ })),
73
+ type: Type.Optional(Type.Union([Type.Literal("stdio"), Type.Literal("http"), Type.Literal("streamable-http")], {
74
+ description: "install: transport type (defaults to stdio, or streamable-http when url is given).",
75
+ })),
76
+ scope: Type.Optional(Type.Union([Type.Literal("project"), Type.Literal("global")], {
77
+ description: "install/remove: config scope ('project' = .pi/mcp.json, 'global' = ~/.pi/agent/mcp.json).",
78
+ })),
79
+ description: Type.Optional(Type.String({
80
+ description: "install: human-readable server note.",
81
+ })),
82
+ }),
83
+ execute: async (_id, params) => {
84
+ const L = getLang();
85
+ const action = params.action;
86
+ if (action === "list") {
87
+ const { servers, globalPath, projectPath } = host.listServers();
88
+ if (servers.length === 0) {
89
+ return reply(pick(L, `当前未配置任何 MCP 服务器。\n项目配置:${projectPath}\n全局配置:${globalPath}`, `No MCP servers configured.\nProject config: ${projectPath}\nGlobal config: ${globalPath}`, "mcp_manage.list.empty"), { count: 0 });
90
+ }
91
+ const lines = servers.map(formatServerLine).join("\n");
92
+ return reply(pick(L, `已配置的 MCP 服务器(${servers.length}):\n${lines}`, `Configured MCP servers (${servers.length}):\n${lines}`, "mcp_manage.list.ok", { count: servers.length }), { count: servers.length, servers: servers.map((s) => ({ name: s.name, scope: s.scope, status: s.status })) });
93
+ }
94
+ if (action === "check") {
95
+ const q = (params.query ?? params.name ?? params.package ?? "").trim();
96
+ if (!q) {
97
+ return reply(pick(L, "请提供 query(或 name / package)以检查对应的 MCP 服务器是否已安装。", "Provide query (or name / package) to check whether the MCP server is installed.", "mcp_manage.check.missing_query"), { installed: false });
98
+ }
99
+ const res = host.checkServer(q);
100
+ if (!res.installed || !res.server) {
101
+ return reply(pick(L, `未找到匹配「${q}」的 MCP 服务器(installed=false)。可使用 action="install" 安装。`, `No MCP server matching "${q}" is installed (installed=false). Use action="install" to install it.`, "mcp_manage.check.not_installed", { query: q }), { query: q, installed: false, running: false });
102
+ }
103
+ const lines = res.matches.map(formatServerLine).join("\n");
104
+ return reply(pick(L, `已找到匹配「${q}」的 MCP 服务器(installed=true, running=${res.running}):\n${lines}`, `Found MCP server matching "${q}" (installed=true, running=${res.running}):\n${lines}`, "mcp_manage.check.found", { query: q }), {
105
+ query: q,
106
+ installed: true,
107
+ running: res.running,
108
+ enabled: res.enabled,
109
+ name: res.server.name,
110
+ scope: res.server.scope,
111
+ status: res.server.status,
112
+ toolCount: res.tools.length,
113
+ });
114
+ }
115
+ if (action === "install") {
116
+ const res = await host.installServer({
117
+ name: params.name,
118
+ package: params.package,
119
+ command: params.command,
120
+ args: params.args,
121
+ env: params.env,
122
+ cwd: params.cwd,
123
+ url: params.url,
124
+ headers: params.headers,
125
+ type: params.type,
126
+ scope: params.scope,
127
+ description: params.description,
128
+ });
129
+ if (!res.ok) {
130
+ return reply(pick(L, `MCP 服务器安装失败:${res.error ?? "未知错误"}`, `Failed to install MCP server: ${res.error ?? "unknown error"}`, "mcp_manage.install.fail"), { ok: false, error: res.error });
131
+ }
132
+ const toolNames = (res.tools ?? []).map((t) => `${res.name}_${t.name}`);
133
+ const toolHint = toolNames.length > 0
134
+ ? pick(L, `\n已暴露工具(${toolNames.length}):${toolNames.join(", ")}`, `\nExposed tools (${toolNames.length}): ${toolNames.join(", ")}`, "mcp_manage.install.tools", { count: toolNames.length })
135
+ : res.error
136
+ ? `\n⚠️ ${res.error}`
137
+ : "";
138
+ return reply(pick(L, `已安装 MCP 服务器「${res.name}」(作用域:${res.scope},状态:${res.status})。${toolHint}`, `Installed MCP server "${res.name}" (scope: ${res.scope}, status: ${res.status}).${toolHint}`, "mcp_manage.install.ok", { name: res.name ?? "", scope: res.scope ?? "project", status: res.status ?? "stopped" }), {
139
+ ok: true,
140
+ name: res.name,
141
+ scope: res.scope,
142
+ status: res.status,
143
+ toolCount: toolNames.length,
144
+ ...(res.error ? { error: res.error } : {}),
145
+ });
146
+ }
147
+ if (action === "remove") {
148
+ const name = (params.name ?? params.query ?? "").trim();
149
+ if (!name) {
150
+ return reply(pick(L, "请提供要移除的 MCP 服务器名称(name)。", "Provide the MCP server name to remove.", "mcp_manage.remove.missing_name"), { ok: false });
151
+ }
152
+ const res = await host.removeServer(name, params.scope);
153
+ if (!res.ok) {
154
+ return reply(pick(L, `移除 MCP 服务器「${name}」失败:${res.error ?? "不存在"}`, `Failed to remove MCP server "${name}": ${res.error ?? "not found"}`, "mcp_manage.remove.fail", { name }), { ok: false, name, error: res.error });
155
+ }
156
+ return reply(pick(L, `已移除 MCP 服务器「${name}」并同步工具列表。`, `Removed MCP server "${name}" and synced tools.`, "mcp_manage.remove.ok", { name }), { ok: true, name });
157
+ }
158
+ // action === "reload"
159
+ const { servers } = await host.reloadServers();
160
+ const runningCount = servers.filter((s) => s.status === "running").length;
161
+ return reply(pick(L, `已重新加载全部 MCP 服务器(共 ${servers.length} 个,运行中 ${runningCount} 个)。`, `Reloaded all MCP servers (${servers.length} total, ${runningCount} running).`, "mcp_manage.reload.ok", { count: servers.length, running: runningCount }), { count: servers.length, running: runningCount });
162
+ },
163
+ });
164
+ }
@@ -213,3 +213,185 @@ export function toggleMcpServer(opts) {
213
213
  }
214
214
  return { ok: false, error: `服务器 ${name} 不存在` };
215
215
  }
216
+ /** 从 npm 包名、URL 或命令自动推导合法的 MCP 服务器名称 */
217
+ export function deriveMcpServerName(raw) {
218
+ let s = String(raw ?? "").trim();
219
+ if (!s)
220
+ return "";
221
+ // 如果是 URL,提取 hostname
222
+ if (/^https?:\/\//i.test(s)) {
223
+ try {
224
+ const u = new URL(s);
225
+ s = u.hostname;
226
+ }
227
+ catch {
228
+ /* ignore */
229
+ }
230
+ }
231
+ else {
232
+ // 去掉 npm 版本后缀(如 @scope/pkg@1.2.3 或 pkg@latest)
233
+ const atIdx = s.lastIndexOf("@");
234
+ if (atIdx > 0) {
235
+ s = s.slice(0, atIdx);
236
+ }
237
+ // 若为 @scope/pkg,取斜杠后半段;若后半段只是 "mcp" 或 "server"(如 @playwright/mcp),取 scope
238
+ if (s.startsWith("@") && s.includes("/")) {
239
+ const [scopePart, pkgPart] = s.slice(1).split("/", 2);
240
+ if (pkgPart && !/^(mcp|server|mcp-server)$/i.test(pkgPart)) {
241
+ s = pkgPart;
242
+ }
243
+ else if (scopePart) {
244
+ s = scopePart;
245
+ }
246
+ }
247
+ // 剥离常见前后缀(保留非空主体)
248
+ const stripped = s.replace(/^(mcp-server-|server-|mcp-)/i, "").replace(/(-mcp-server|-server|-mcp)$/i, "");
249
+ if (stripped.trim()) {
250
+ s = stripped.trim();
251
+ }
252
+ }
253
+ return s
254
+ .replace(/[^a-zA-Z0-9_-]+/g, "-")
255
+ .replace(/^-+|-+$/g, "")
256
+ .slice(0, 64);
257
+ }
258
+ /**
259
+ * 检查某个 MCP 服务器是否已安装(支持按服务器名称、npm 包名、命令或 URL 匹配)。
260
+ */
261
+ export function checkMcpServer(opts) {
262
+ const q = String(opts.query ?? "").trim();
263
+ if (!q) {
264
+ return { installed: false, running: false, enabled: false, server: null, matches: [], tools: [] };
265
+ }
266
+ const qLower = q.toLowerCase();
267
+ const derived = deriveMcpServerName(q).toLowerCase();
268
+ const { servers } = listAllMcpServers(opts);
269
+ // 按匹配度打分:精确名 > 忽略大小写名 > 推导短名相等 > package/args/url/command 包含
270
+ const scored = [];
271
+ for (const srv of servers) {
272
+ const nameLower = srv.name.toLowerCase();
273
+ const cmdLower = (srv.command ?? "").toLowerCase();
274
+ const argsLower = (srv.args ?? []).map((a) => String(a).toLowerCase());
275
+ const urlLower = (srv.url ?? "").toLowerCase();
276
+ let score = 0;
277
+ if (srv.name === q) {
278
+ score = 100;
279
+ }
280
+ else if (nameLower === qLower) {
281
+ score = 90;
282
+ }
283
+ else if (derived && nameLower === derived) {
284
+ score = 80;
285
+ }
286
+ else if (argsLower.some((a) => a === qLower || (derived && deriveMcpServerName(a).toLowerCase() === derived))) {
287
+ score = 75;
288
+ }
289
+ else if (nameLower.includes(qLower) ||
290
+ cmdLower.includes(qLower) ||
291
+ urlLower.includes(qLower) ||
292
+ argsLower.some((a) => a.includes(qLower))) {
293
+ score = 50;
294
+ }
295
+ if (score > 0) {
296
+ // 同分时项目级优先、running 优先
297
+ if (srv.scope === "project")
298
+ score += 2;
299
+ if (srv.status === "running")
300
+ score += 1;
301
+ scored.push({ server: srv, score });
302
+ }
303
+ }
304
+ scored.sort((a, b) => b.score - a.score);
305
+ const matches = scored.map((x) => x.server);
306
+ const primary = matches[0] ?? null;
307
+ return {
308
+ installed: matches.length > 0,
309
+ running: primary ? primary.status === "running" : false,
310
+ enabled: primary ? primary.enabled !== false : false,
311
+ server: primary,
312
+ matches,
313
+ tools: primary?.tools ?? [],
314
+ };
315
+ }
316
+ /**
317
+ * 便捷安装/配置一个 MCP 服务器并立即触发 McpBridge 热加载。
318
+ */
319
+ export async function installMcpServer(opts) {
320
+ const spec = opts.spec ?? {};
321
+ const pkg = typeof spec.package === "string" ? spec.package.trim() : "";
322
+ const rawCmd = typeof spec.command === "string" ? spec.command.trim() : "";
323
+ const rawUrl = typeof spec.url === "string" ? spec.url.trim() : "";
324
+ const extraArgs = Array.isArray(spec.args) ? spec.args.map(String) : [];
325
+ let command = rawCmd || undefined;
326
+ let args = extraArgs.length > 0 ? extraArgs : undefined;
327
+ if (pkg) {
328
+ command = command || "npx";
329
+ args = command === "npx" ? ["-y", pkg, ...extraArgs] : [pkg, ...extraArgs];
330
+ }
331
+ if (!command && !rawUrl) {
332
+ return {
333
+ ok: false,
334
+ error: "安装 MCP 服务器需提供 package(npm 包名)、command(启动命令)或 url(HTTP 地址)之一",
335
+ };
336
+ }
337
+ const rawName = (typeof spec.name === "string" && spec.name.trim()) ||
338
+ deriveMcpServerName(pkg || rawUrl || extraArgs[0] || command || "");
339
+ if (!rawName || !isValidMcpServerName(rawName)) {
340
+ return {
341
+ ok: false,
342
+ error: "无法推导出合法的服务器名称,请显式指定 name(仅允许英文字母、数字、下划线及中划线)",
343
+ };
344
+ }
345
+ const scope = spec.scope === "global" ? "global" : "project";
346
+ const uiServer = {
347
+ name: rawName,
348
+ scope,
349
+ command,
350
+ args,
351
+ cwd: typeof spec.cwd === "string" && spec.cwd.trim() ? spec.cwd.trim() : undefined,
352
+ env: spec.env && typeof spec.env === "object" ? spec.env : undefined,
353
+ url: rawUrl || undefined,
354
+ headers: spec.headers && typeof spec.headers === "object" ? spec.headers : undefined,
355
+ type: spec.type ?? (rawUrl ? "streamable-http" : "stdio"),
356
+ timeout: typeof spec.timeout === "number" ? spec.timeout : undefined,
357
+ enabled: spec.enabled !== false,
358
+ description: typeof spec.description === "string" && spec.description.trim() ? spec.description.trim() : undefined,
359
+ status: "stopped",
360
+ tools: [],
361
+ };
362
+ const saved = saveMcpServer({
363
+ agentDir: opts.agentDir,
364
+ cwd: opts.cwd,
365
+ dataDir: opts.dataDir,
366
+ server: uiServer,
367
+ });
368
+ if (!saved.ok) {
369
+ return { ok: false, error: saved.error };
370
+ }
371
+ if (opts.bridge) {
372
+ try {
373
+ await opts.bridge.reload();
374
+ }
375
+ catch {
376
+ /* bridge reload 内部已吞异常,兜底防御 */
377
+ }
378
+ }
379
+ const after = listAllMcpServers({
380
+ agentDir: opts.agentDir,
381
+ cwd: opts.cwd,
382
+ dataDir: opts.dataDir,
383
+ bridge: opts.bridge,
384
+ });
385
+ const updated = after.servers.find((s) => s.name === rawName && s.scope === scope) ??
386
+ after.servers.find((s) => s.name === rawName) ??
387
+ uiServer;
388
+ return {
389
+ ok: true,
390
+ name: rawName,
391
+ scope,
392
+ status: updated.status,
393
+ tools: updated.tools,
394
+ server: updated,
395
+ ...(updated.error ? { error: updated.error } : {}),
396
+ };
397
+ }
@@ -51,6 +51,9 @@ const BLOCKED_TOOLS = new Set([
51
51
  "eval",
52
52
  // QuickJS 沙箱代码执行(可嵌套调用写工具/命令,计划模式禁止任意代码执行)
53
53
  "codemode",
54
+ // MCP 服务器配置管理(install/remove 会修改 mcp.json 并拉起新子进程)
55
+ "mcp_manage",
56
+ "sandbox",
54
57
  // 形态变换(会重写整个文件树)
55
58
  "format",
56
59
  "prettier",
@@ -264,6 +264,30 @@ export const HOST_METHODS = [
264
264
  example: `host.events.on("notes:changed", () => {})`,
265
265
  },
266
266
  { name: "models.list", needs: "-", summary: "列出已配置鉴权的模型(provider/id)", example: `host.models.list()` },
267
+ {
268
+ name: "mcp.list",
269
+ needs: "-",
270
+ summary: "列出已配置的全局与项目级 MCP 服务器及运行态/工具列表",
271
+ example: `await host.mcp.list()`,
272
+ },
273
+ {
274
+ name: "mcp.check",
275
+ needs: "-",
276
+ summary: "按名称、npm 包名、命令或 URL 检查指定 MCP 是否已安装/运行中",
277
+ example: `await host.mcp.check("filesystem")`,
278
+ },
279
+ {
280
+ name: "mcp.install",
281
+ needs: "tools",
282
+ summary: "安装/配置 MCP 服务器(支持 package 快捷方式)并立即触发热加载",
283
+ example: `await host.mcp.install({ package: "@modelcontextprotocol/server-memory" })`,
284
+ },
285
+ {
286
+ name: "mcp.promptInstall",
287
+ needs: "chat",
288
+ summary: "向当前对话发送指令,让 AI 检查并安装指定的 MCP 服务器",
289
+ example: `await host.mcp.promptInstall("@modelcontextprotocol/server-filesystem")`,
290
+ },
267
291
  {
268
292
  name: "scm",
269
293
  needs: "-",
@@ -39,6 +39,7 @@ import { applyPostEdit, denialText, freezeParams, isBlockingDecision, normalizeP
39
39
  import { normalizeWorkspaceRoots } from "./client-state.js";
40
40
  import { compareVersions, ensureBackup } from "./plugin-updater.js";
41
41
  import { createProject, isInsideRoot, realPathOfNearest, } from "./plugin-project.js";
42
+ import { listAllMcpServers, checkMcpServer, installMcpServer, } from "./mcp-manager.js";
42
43
  import { createHash } from "node:crypto";
43
44
  import { execFile } from "node:child_process";
44
45
  import { promisify } from "node:util";
@@ -1580,6 +1581,8 @@ export class PluginManager {
1580
1581
  runAborter = undefined;
1581
1582
  /** 由 index.ts 接入 agent-service:模型列表(host.models.list 的底层)。无注入回 []。 */
1582
1583
  modelLister = undefined;
1584
+ /** 由 index.ts 接入 McpBridge:供 host.mcp 读取实时运行状态与热重载。 */
1585
+ mcpBridge = undefined;
1583
1586
  /** 插件能力动态授权表(host.requestPermission 的底层,见 server/plugin-permissions.ts)。 */
1584
1587
  permGrants;
1585
1588
  /** 由 index.ts 注入:向浏览器请求能力授权的用户确认({ok, remember})。
@@ -3757,6 +3760,116 @@ export class PluginManager {
3757
3760
  }
3758
3761
  },
3759
3762
  },
3763
+ mcp: {
3764
+ list: async () => {
3765
+ try {
3766
+ const res = listAllMcpServers({
3767
+ agentDir: self.mcpBridge?.getAgentDir(),
3768
+ cwd: self.cwdValue,
3769
+ dataDir: self.dataDir,
3770
+ bridge: self.mcpBridge,
3771
+ });
3772
+ return res.servers;
3773
+ }
3774
+ catch (err) {
3775
+ console.error(`[plugin:${info.id}] mcp.list failed:`, err);
3776
+ return [];
3777
+ }
3778
+ },
3779
+ check: async (query) => {
3780
+ try {
3781
+ return checkMcpServer({
3782
+ agentDir: self.mcpBridge?.getAgentDir(),
3783
+ cwd: self.cwdValue,
3784
+ dataDir: self.dataDir,
3785
+ bridge: self.mcpBridge,
3786
+ query: String(query ?? ""),
3787
+ });
3788
+ }
3789
+ catch (err) {
3790
+ console.error(`[plugin:${info.id}] mcp.check failed:`, err);
3791
+ return { installed: false, running: false, enabled: false, server: null, matches: [], tools: [] };
3792
+ }
3793
+ },
3794
+ install: async (spec) => {
3795
+ if (!can("tools")) {
3796
+ return { ok: false, error: '插件未声明能力 "tools"(manifest.permissions)——请求被拒' };
3797
+ }
3798
+ try {
3799
+ const res = await installMcpServer({
3800
+ agentDir: self.mcpBridge?.getAgentDir(),
3801
+ cwd: self.cwdValue,
3802
+ dataDir: self.dataDir,
3803
+ bridge: self.mcpBridge,
3804
+ spec: spec ?? {},
3805
+ });
3806
+ if (res.ok) {
3807
+ try {
3808
+ self.onAgentToolsChanged?.();
3809
+ }
3810
+ catch {
3811
+ /* ignore */
3812
+ }
3813
+ }
3814
+ return res;
3815
+ }
3816
+ catch (err) {
3817
+ return { ok: false, error: err.message };
3818
+ }
3819
+ },
3820
+ promptInstall: async (target, opts) => {
3821
+ if (!can("chat") && !can("tools")) {
3822
+ return { ok: false, error: '插件未声明能力 "chat" 或 "tools"(manifest.permissions)——请求被拒' };
3823
+ }
3824
+ const scope = opts?.scope === "global" ? "global" : "project";
3825
+ let desc = "";
3826
+ if (typeof target === "string") {
3827
+ desc = target.trim();
3828
+ }
3829
+ else if (target && typeof target === "object") {
3830
+ const parts = [];
3831
+ if (target.name)
3832
+ parts.push(`name="${target.name}"`);
3833
+ if (target.package)
3834
+ parts.push(`package="${target.package}"`);
3835
+ if (target.command)
3836
+ parts.push(`command="${target.command}"`);
3837
+ if (target.args?.length)
3838
+ parts.push(`args=${JSON.stringify(target.args)}`);
3839
+ if (target.url)
3840
+ parts.push(`url="${target.url}"`);
3841
+ desc = parts.join(", ");
3842
+ }
3843
+ if (!desc) {
3844
+ return { ok: false, error: "mcp.promptInstall: target 不能为空" };
3845
+ }
3846
+ const cfgFile = scope === "global" ? "~/.pi/agent/mcp.json" : ".pi/mcp.json";
3847
+ const promptText = `请检查并安装以下 MCP 服务器(作用域:${scope},配置文件:\`${cfgFile}\`):${desc}。\n` +
3848
+ `- 若当前会话已启用 \`mcp_manage\` 工具,请先调用 \`mcp_manage({ action: "check", query: ... })\` 确认是否已安装,未安装则调用 \`mcp_manage({ action: "install", scope: "${scope}", ... })\` 完成安装并验证状态;\n` +
3849
+ `- 若未启用 \`mcp_manage\` 工具,请用 \`read\` 检查 \`${cfgFile}\`,并在 \`mcpServers\` 字段下写入对应的服务器配置(例如 \`{ "command": "npx", "args": ["-y", "<package>"] }\`),保存后系统会自动热加载该 MCP 服务器。`;
3850
+ const targetConvId = (typeof opts?.conversationId === "string" && opts.conversationId.trim()) ||
3851
+ self.conversationProvider?.()?.conversationId;
3852
+ if (targetConvId && self.conversationWriter) {
3853
+ try {
3854
+ const r = await self.conversationWriter(targetConvId, promptText);
3855
+ return { ok: r.ok, conversationId: targetConvId, ...(r.error ? { error: r.error } : {}) };
3856
+ }
3857
+ catch (err) {
3858
+ return { ok: false, error: err.message };
3859
+ }
3860
+ }
3861
+ if (self.chatProvider) {
3862
+ try {
3863
+ const r = await self.chatProvider(info.id, { text: promptText });
3864
+ return { ok: true, conversationId: r.conversationId };
3865
+ }
3866
+ catch (err) {
3867
+ return { ok: false, error: err.message };
3868
+ }
3869
+ }
3870
+ return { ok: false, error: "无可用对话通道(conversationWriter / chatProvider 未接入)" };
3871
+ },
3872
+ },
3760
3873
  onStats: (h) => {
3761
3874
  self.statsHandlers.add(h);
3762
3875
  return effects.add("onStats", () => {