@eum-agent/integration-mcp 0.0.0-stage → 1.0.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 (4) hide show
  1. package/dist/index.js +3201 -0
  2. package/package.json +51 -3
  3. package/ui/ui.js +2690 -0
  4. package/README.md +0 -3
package/ui/ui.js ADDED
@@ -0,0 +1,2690 @@
1
+ import { useCallback, useEffect, useId, useRef, useState, useSyncExternalStore } from "react";
2
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ //#region src/tool-names.ts
4
+ /** Canonical names shared by tool registration and browser presentation. */
5
+ var TOOL_NAMES = [
6
+ "mcp_server_list",
7
+ "mcp_server_create",
8
+ "mcp_server_update",
9
+ "mcp_server_set_selected"
10
+ ];
11
+ //#endregion
12
+ //#region src/ui/metadata.ts
13
+ var CATALOGUES$1 = {
14
+ "en-US": {
15
+ section: "Built-in plugins",
16
+ servers: "MCP servers",
17
+ group: "MCP",
18
+ mcp_server_list: "Inspect MCP servers",
19
+ mcp_server_create: "Add MCP server",
20
+ mcp_server_update: "Edit MCP server",
21
+ mcp_server_set_selected: "Select MCP server"
22
+ },
23
+ "zh-CN": {
24
+ section: "内置插件",
25
+ servers: "MCP 服务器",
26
+ group: "MCP",
27
+ mcp_server_list: "查看 MCP 服务器",
28
+ mcp_server_create: "添加 MCP 服务器",
29
+ mcp_server_update: "修改 MCP 服务器",
30
+ mcp_server_set_selected: "选用 MCP 服务器"
31
+ }
32
+ };
33
+ var names = new Set(TOOL_NAMES);
34
+ /** Registers presentation facets with the same activation lifetime as the tools. */
35
+ function registerMetadata(ctx) {
36
+ ctx.i18n.register(CATALOGUES$1, "en-US");
37
+ ctx.i18n.contribute(Object.fromEntries(Object.entries(CATALOGUES$1).map(([language, catalogue]) => [language, Object.fromEntries([...names].map((tool) => [`transcript.actions.${tool}`, catalogue[tool] ?? tool]))])), "en-US");
38
+ ctx.slots.register("chat.tool.presentation", {
39
+ id: "tool-metadata",
40
+ describe: ({ call }) => {
41
+ if (!(names.has(call.name) || call.name === "mcp_resource_read" || /^mcp_([a-z0-9][a-z0-9-]{0,23})_(.+)$/.test(call.name))) return void 0;
42
+ const input = call.input !== null && typeof call.input === "object" ? call.input : {};
43
+ const summary = [
44
+ "path",
45
+ "url",
46
+ "query",
47
+ "command",
48
+ "skill",
49
+ "id",
50
+ "name",
51
+ "task",
52
+ "prompt"
53
+ ].flatMap((key) => typeof input[key] === "string" ? [input[key]] : []).slice(0, 2).join(" · ").replace(/\s+/g, " ").slice(0, 240);
54
+ return {
55
+ label: names.has(call.name) ? ctx.i18n.t(call.name) : call.name,
56
+ icon: "hammer",
57
+ summary
58
+ };
59
+ }
60
+ });
61
+ ctx.slots.register("shell.tools.group", {
62
+ id: "tool-groups",
63
+ describe: (tool) => {
64
+ if (tool.plugin !== ctx.plugin) return void 0;
65
+ const slug = /^mcp_([a-z0-9][a-z0-9-]{0,23})_(.+)$/.exec(tool.name)?.[1];
66
+ if (slug && !names.has(tool.name) && tool.name !== "mcp_resource_read") return {
67
+ key: `mcp-server:${slug}`,
68
+ label: slug,
69
+ source: `${ctx.plugin} · ${slug}`,
70
+ sectionLabel: ctx.i18n.t("servers"),
71
+ sectionOrder: 3,
72
+ order: 0
73
+ };
74
+ return {
75
+ key: `plugin:${ctx.plugin}`,
76
+ label: ctx.i18n.t("group"),
77
+ source: ctx.plugin,
78
+ sectionLabel: ctx.i18n.t("section"),
79
+ sectionOrder: 1,
80
+ order: 9
81
+ };
82
+ }
83
+ });
84
+ }
85
+ //#endregion
86
+ //#region src/ui/shared.ts
87
+ /** Returns feature failures; the global dialog owns gateway connectivity and authentication. */
88
+ function failureText(_ctx, error) {
89
+ const failure = error?.failure;
90
+ if (failure === "offline" || failure === "authentication") return null;
91
+ return error instanceof Error ? error.message : String(error);
92
+ }
93
+ /** Shows a failure outside a form as a toast. An offline failure says
94
+ * nothing: the host's connection dialog owns the outage. */
95
+ function useFailureToast(ctx) {
96
+ const toast = ctx.ui.useToast();
97
+ const toastRef = useRef(toast);
98
+ toastRef.current = toast;
99
+ return useCallback((error) => {
100
+ const text = failureText(ctx, error);
101
+ if (text === null) return;
102
+ toastRef.current.add({
103
+ id: `failure::${text}`,
104
+ tone: "destructive",
105
+ title: text
106
+ });
107
+ }, [ctx]);
108
+ }
109
+ function stateLabel(ctx, state) {
110
+ return ctx.i18n.t(`mcp.state.${state}`);
111
+ }
112
+ /** Maps a status to the dot's colour class. */
113
+ function stateTone(state) {
114
+ if (state === "connected") return "ok";
115
+ if (state === "failed" || state === "needs-auth") return "failed";
116
+ if (state === "disabled") return "off";
117
+ return "pending";
118
+ }
119
+ /**
120
+ * The agents `config.agent.list` answers, re-read when an agent changes or is
121
+ * removed. Kept as `null` until the first answer, and left as it was when a
122
+ * read is refused, so names never flicker away.
123
+ */
124
+ function useAgents(ctx) {
125
+ const [agents, setAgents] = useState(null);
126
+ useEffect(() => {
127
+ let live = true;
128
+ const load = () => {
129
+ ctx.call("config.agent.list").then((rows) => {
130
+ if (live && !ctx.signal.aborted) setAgents(rows);
131
+ }, () => {});
132
+ };
133
+ if (ctx.host.get().connection === "online") load();
134
+ let previous = ctx.host.get().connection;
135
+ const offConnection = ctx.host.subscribe(() => {
136
+ const connection = ctx.host.get().connection;
137
+ const restored = connection === "online" && previous !== "online";
138
+ previous = connection;
139
+ if (restored) load();
140
+ });
141
+ const offChanged = ctx.onCore("config.agentChanged", load);
142
+ const offRemoved = ctx.onCore("config.agentRemoved", load);
143
+ return () => {
144
+ live = false;
145
+ offChanged();
146
+ offRemoved();
147
+ offConnection();
148
+ };
149
+ }, []);
150
+ return agents;
151
+ }
152
+ /** Names of the agents among `ids` that still exist; a removed agent's id is
153
+ * skipped, because its selection rows outlive it harmlessly. */
154
+ function agentNames(agents, ids) {
155
+ if (!agents) return [];
156
+ const byId = new Map(agents.map((agent) => [agent.agentId, agent.name]));
157
+ return ids.flatMap((id) => {
158
+ const name = byId.get(id);
159
+ return name === void 0 ? [] : [name];
160
+ });
161
+ }
162
+ //#endregion
163
+ //#region src/ui/wire.ts
164
+ /** Local method names, as `ctx.invoke` takes them. */
165
+ var METHOD = {
166
+ commandParse: "commandParse",
167
+ listServers: "listServers",
168
+ getServer: "getServer",
169
+ saveServer: "saveServer",
170
+ removeServer: "removeServer",
171
+ setEnabled: "setEnabled",
172
+ retryServer: "retryServer",
173
+ testServer: "testServer",
174
+ authorize: "authorize",
175
+ cancelAuthorize: "cancelAuthorize",
176
+ signOut: "signOut",
177
+ agentServers: "agentServers",
178
+ setAgentServers: "setAgentServers",
179
+ prompts: "prompts",
180
+ getPrompt: "getPrompt",
181
+ resources: "resources",
182
+ readResource: "readResource"
183
+ };
184
+ /** Local frame names, as `ctx.on` takes them. */
185
+ var FRAME = {
186
+ serversChanged: "serversChanged",
187
+ selectionChanged: "selectionChanged"
188
+ };
189
+ /** Credential names under a server's scope. */
190
+ var envCredential = (name) => `env.${name}`;
191
+ var headerCredential = (name) => `header.${name}`;
192
+ //#endregion
193
+ //#region src/ui/agent-tab.tsx
194
+ function agentTabFor(ctx) {
195
+ return function McpAgentTab({ editor }) {
196
+ const t = ctx.i18n.t;
197
+ const host = useSyncExternalStore(ctx.host.subscribe, ctx.host.get);
198
+ const [servers, setServers] = useState(null);
199
+ const values = editor.read({ mcpServerIds: [] });
200
+ const selected = values.mcpServerIds;
201
+ const [loadFailed, setLoadFailed] = useState(false);
202
+ const fail = useFailureToast(ctx);
203
+ useEffect(() => {
204
+ let live = true;
205
+ setServers(null);
206
+ setLoadFailed(false);
207
+ if (host.connection !== "online") return;
208
+ ctx.invoke(METHOD.listServers, {}).then((list) => {
209
+ if (!live || ctx.signal.aborted) return;
210
+ setServers(list.servers);
211
+ }, (failure) => {
212
+ if (live && !ctx.signal.aborted) {
213
+ setLoadFailed(failureText(ctx, failure) !== null);
214
+ fail(failure);
215
+ }
216
+ });
217
+ return () => {
218
+ live = false;
219
+ };
220
+ }, [host.connection, fail]);
221
+ useEffect(() => {
222
+ return ctx.on(FRAME.serversChanged, ({ payload }) => {
223
+ const next = payload?.servers;
224
+ if (next) setServers(next);
225
+ });
226
+ }, []);
227
+ function toggle(serverId, on) {
228
+ editor.update({ mcpServerIds: on ? [...selected, serverId] : selected.filter((id) => id !== serverId) });
229
+ }
230
+ return /* @__PURE__ */ jsxs("div", {
231
+ className: "mcp-tab",
232
+ children: [
233
+ !servers && !loadFailed && /* @__PURE__ */ jsx("p", {
234
+ role: "status",
235
+ className: "mcp-muted",
236
+ children: t("mcp.loading")
237
+ }),
238
+ servers && !servers.length && /* @__PURE__ */ jsx(ctx.ui.EmptyState, {
239
+ title: t("mcp.tabEmpty"),
240
+ description: t("mcp.tabEmptyHint")
241
+ }),
242
+ servers && !!servers.length && /* @__PURE__ */ jsxs(Fragment, { children: [editor.tools && /* @__PURE__ */ jsx(ctx.ui.Alert, {
243
+ tone: "warning",
244
+ className: "mcp-alert",
245
+ children: t("mcp.tabWhitelist")
246
+ }), /* @__PURE__ */ jsx("ul", {
247
+ className: "mcp-agents",
248
+ children: servers.map((server) => /* @__PURE__ */ jsxs("li", {
249
+ className: "mcp-agent-row",
250
+ children: [/* @__PURE__ */ jsxs("span", {
251
+ className: "mcp-agent-name",
252
+ children: [/* @__PURE__ */ jsx("strong", { children: server.name }), /* @__PURE__ */ jsxs("small", { children: [/* @__PURE__ */ jsx("span", {
253
+ className: "mcp-dot",
254
+ "data-state": stateTone(server.status.state),
255
+ "aria-hidden": "true"
256
+ }), stateLabel(ctx, server.status.state)] })]
257
+ }), /* @__PURE__ */ jsx(ctx.ui.Switch, {
258
+ "aria-label": server.name,
259
+ checked: selected.includes(server.id),
260
+ disabled: editor.pending || values.mcpServerIds === void 0,
261
+ onCheckedChange: (next) => void toggle(server.id, next)
262
+ })]
263
+ }, server.id))
264
+ })] })
265
+ ]
266
+ });
267
+ };
268
+ }
269
+ //#endregion
270
+ //#region src/ui/composer.ts
271
+ /** Hears both frames that can change what a source lists. */
272
+ function subscribeFor(ctx) {
273
+ return (listener) => {
274
+ const offServers = ctx.on(FRAME.serversChanged, () => listener());
275
+ const offSelection = ctx.on(FRAME.selectionChanged, () => listener());
276
+ return () => {
277
+ offServers();
278
+ offSelection();
279
+ };
280
+ };
281
+ }
282
+ function commandFor(ctx, entry) {
283
+ return {
284
+ kind: "expand",
285
+ name: `${entry.slug}.${entry.name}`,
286
+ description: entry.description?.trim() || entry.name,
287
+ group: entry.serverName,
288
+ arguments: (entry.arguments ?? []).map((argument) => ({
289
+ name: argument.name,
290
+ ...argument.description ? { description: argument.description } : {},
291
+ ...argument.required ? { required: true } : {}
292
+ })),
293
+ async expand(input, session) {
294
+ return await ctx.invoke(METHOD.getPrompt, {
295
+ agentId: session.agentId,
296
+ serverId: entry.serverId,
297
+ name: entry.name,
298
+ args: { ...input.args }
299
+ });
300
+ }
301
+ };
302
+ }
303
+ function commandSource(ctx) {
304
+ return {
305
+ id: "mcp-prompts",
306
+ namespace: "mcp",
307
+ label: () => ctx.i18n.t("mcp.title"),
308
+ async commands(session) {
309
+ const { prompts } = await ctx.invoke(METHOD.prompts, { agentId: session.agentId });
310
+ return prompts.map((entry) => commandFor(ctx, entry));
311
+ },
312
+ subscribe: subscribeFor(ctx)
313
+ };
314
+ }
315
+ /** An attachment id carries the server and the URI; JSON keeps any URI intact. */
316
+ function itemId(entry) {
317
+ return JSON.stringify([entry.serverId, entry.uri]);
318
+ }
319
+ function parseItemId(id) {
320
+ const parsed = JSON.parse(id);
321
+ if (!Array.isArray(parsed) || parsed.length !== 2 || typeof parsed[0] !== "string" || typeof parsed[1] !== "string") throw new Error(`not an MCP resource: ${id}`);
322
+ return {
323
+ serverId: parsed[0],
324
+ uri: parsed[1]
325
+ };
326
+ }
327
+ function attachmentSource(ctx) {
328
+ return {
329
+ id: "mcp-resources",
330
+ namespace: "mcp",
331
+ label: () => ctx.i18n.t("mcp.title"),
332
+ async items(session, query) {
333
+ const { resources } = await ctx.invoke(METHOD.resources, {
334
+ agentId: session.agentId,
335
+ query
336
+ });
337
+ return resources.map((entry) => ({
338
+ id: itemId(entry),
339
+ label: entry.name?.trim() || entry.uri,
340
+ description: entry.description?.trim() || entry.uri,
341
+ group: entry.serverName
342
+ }));
343
+ },
344
+ async read(id, session) {
345
+ const { serverId, uri } = parseItemId(id);
346
+ return await ctx.invoke(METHOD.readResource, {
347
+ agentId: session.agentId,
348
+ serverId,
349
+ uri
350
+ });
351
+ },
352
+ subscribe: subscribeFor(ctx)
353
+ };
354
+ }
355
+ /** Browser translations keyed by the product's supported language-region IDs. */
356
+ var CATALOGUES = {
357
+ "zh-CN": {
358
+ "mcp.title": "MCP",
359
+ "mcp.servers": "MCP 服务器",
360
+ "mcp.add": "添加服务器",
361
+ "mcp.loading": "正在加载…",
362
+ "mcp.listFailed": "未能加载服务器列表",
363
+ "mcp.detailFailed": "未能加载服务器详情",
364
+ "mcp.emptyTitle": "尚未添加 MCP 服务器",
365
+ "mcp.emptyBody": "添加服务器后,可在智能体设置中选用它的工具、资源与提示词。",
366
+ "mcp.enable": "启用 {{name}}",
367
+ "mcp.turnOn": "启用",
368
+ "mcp.turnOff": "停用",
369
+ "mcp.retry": "重试",
370
+ "mcp.agents": "智能体",
371
+ "mcp.agentUses": "{{name}} 选用此服务器",
372
+ "mcp.agentWhitelist": "工具白名单",
373
+ "mcp.noAgents": "还没有智能体",
374
+ "mcp.state.disabled": "已停用",
375
+ "mcp.state.connecting": "连接中",
376
+ "mcp.state.connected": "已连接",
377
+ "mcp.state.needs-auth": "需要授权",
378
+ "mcp.state.reconnecting": "重连中",
379
+ "mcp.state.failed": "失败",
380
+ "mcp.readStatusReason": "查看异常原因",
381
+ "mcp.transport": "连接方式",
382
+ "mcp.transport.stdio": "本机命令(stdio)",
383
+ "mcp.transport.http": "远程(HTTP)",
384
+ "mcp.name": "名称",
385
+ "mcp.slug": "标识",
386
+ "mcp.slugHelp": "小写字母、数字与连字符,工具名以 mcp_<标识>_ 开头;创建后不可修改。",
387
+ "mcp.command": "命令",
388
+ "mcp.commandHelp": "绝对路径或 PATH 中的命令名;粘贴整行命令会自动拆出参数。",
389
+ "mcp.args": "参数",
390
+ "mcp.arg": "参数 {{n}}",
391
+ "mcp.argAdd": "添加参数",
392
+ "mcp.argRemove": "删除参数 {{n}}",
393
+ "mcp.argMove": "拖动以调整参数 {{n}} 的顺序",
394
+ "mcp.more": "工作目录与环境变量",
395
+ "mcp.moreCwd": "已设工作目录",
396
+ "mcp.moreEnv": "{{count}} 个变量",
397
+ "mcp.cwd": "工作目录",
398
+ "mcp.env": "环境变量",
399
+ "mcp.envName": "变量名",
400
+ "mcp.envValue": "值",
401
+ "mcp.envSecret": "密钥",
402
+ "mcp.envSecretOn": "标为密钥",
403
+ "mcp.envSecretHelp": "密钥:加密保存,只写不读",
404
+ "mcp.envAdd": "添加变量",
405
+ "mcp.envRemove": "删除变量",
406
+ "mcp.url": "URL",
407
+ "mcp.auth": "认证方式",
408
+ "mcp.auth.none": "无",
409
+ "mcp.auth.headers": "Header",
410
+ "mcp.auth.oauth": "OAuth",
411
+ "mcp.headers": "Header",
412
+ "mcp.headerName": "Header 名",
413
+ "mcp.headerValue": "Header 值",
414
+ "mcp.headerAdd": "添加 Header",
415
+ "mcp.headerRemove": "删除 Header",
416
+ "mcp.plainHttp": "该地址不在本机且使用 http://:凭据与内容将明文传输。",
417
+ "mcp.risk": "在沙箱外以你的用户权限运行",
418
+ "mcp.riskDetail": "它可以读写你能访问的一切,只在信任它时保存。",
419
+ "mcp.riskCwd": "工作目录:{{cwd}}",
420
+ "mcp.riskEnv": "环境变量:{{names}}",
421
+ "mcp.trustSave": "信任并保存",
422
+ "mcp.save": "保存",
423
+ "mcp.saving": "正在保存…",
424
+ "mcp.cancel": "取消",
425
+ "mcp.delete": "删除",
426
+ "mcp.error.name": "请填写 1–80 个字符的名称",
427
+ "mcp.error.slug": "请使用 1–24 个小写字母、数字或连字符,并以字母或数字开头",
428
+ "mcp.error.command": "请填写命令",
429
+ "mcp.commandParseFailed": "无法解析命令,请逐项填写命令和参数。",
430
+ "mcp.error.url": "请填写 http:// 或 https:// 开头的 URL",
431
+ "mcp.error.envName": "变量名须以字母或下划线开头,只含字母、数字与下划线",
432
+ "mcp.error.headerName": "Header 名只能包含字母、数字、下划线与连字符,不以连字符开头,至多 100 个字符",
433
+ "mcp.error.duplicate": "名字重复",
434
+ "mcp.credentialsFailed": "配置已保存,但凭据未能写入:{{reason}}",
435
+ "mcp.test": "测试连接",
436
+ "mcp.testing": "正在测试…",
437
+ "mcp.testOk": "连接成功:{{tools}} 个工具、{{resources}} 个资源、{{prompts}} 个提示词",
438
+ "mcp.testSaveFirst": "请先保存修改再测试。",
439
+ "mcp.oauth": "授权",
440
+ "mcp.oauth.none": "未授权",
441
+ "mcp.oauth.authorized": "已授权",
442
+ "mcp.oauth.expires": "已授权,{{time}} 到期",
443
+ "mcp.oauth.reauth": "需要重新授权:{{reason}}",
444
+ "mcp.authorize": "授权",
445
+ "mcp.authorizePending": "等待授权完成",
446
+ "mcp.authorizeHint": "请在浏览器中完成授权,完成后此页面会自动更新。",
447
+ "mcp.authorizeOpen": "打开授权页面",
448
+ "mcp.copyLink": "复制链接",
449
+ "mcp.copied": "已复制",
450
+ "mcp.showLink": "显示授权地址",
451
+ "mcp.copyLinkFailed": "未能复制链接,请展开授权地址后手动复制。",
452
+ "mcp.authorizeWaiting": "正在等待浏览器中完成授权…",
453
+ "mcp.authorizeCancel": "取消授权",
454
+ "mcp.authorizeBlocked": "浏览器拦截了新窗口,请点击链接打开授权页:",
455
+ "mcp.authorizeFailed": "没能打开系统浏览器,请复制地址自行打开:",
456
+ "mcp.authorizeFailedTitle": "没能打开授权页面",
457
+ "mcp.signOut": "登出",
458
+ "mcp.capabilities": "能力",
459
+ "mcp.connection": "连接",
460
+ "mcp.filterCapabilities": "筛选工具、资源与提示词",
461
+ "mcp.noMatches": "没有匹配的项",
462
+ "mcp.kinds": "按类型筛选",
463
+ "mcp.kind.all": "全部",
464
+ "mcp.kind.tools": "工具",
465
+ "mcp.kind.resources": "资源",
466
+ "mcp.kind.prompts": "提示词",
467
+ "mcp.parameters": "参数",
468
+ "mcp.required": "必填",
469
+ "mcp.noParameters": "无参数",
470
+ "mcp.noDescription": "服务器没有提供说明",
471
+ "mcp.mimeType": "内容类型",
472
+ "mcp.refused": "未注册:{{reason}}",
473
+ "mcp.noCapabilities": "连接成功后在这里列出。",
474
+ "mcp.deleteTitle": "删除服务器",
475
+ "mcp.deleteBody": "删除“{{name}}”将撤下工具、停止进程、清除凭据。",
476
+ "mcp.deleteAgents": "将失去它的智能体:{{names}}",
477
+ "mcp.deleteConfirm": "删除服务器",
478
+ "mcp.unsavedTitle": "未保存的修改",
479
+ "mcp.unsavedBody": "修改尚未保存,离开将丢弃这些修改。",
480
+ "mcp.keepEditing": "继续编辑",
481
+ "mcp.discard": "放弃修改",
482
+ "mcp.tabEmpty": "尚未添加 MCP 服务器",
483
+ "mcp.tabEmptyHint": "请在 设置 → 扩展 → MCP 中添加。",
484
+ "mcp.tabWhitelist": "该智能体设置了工具白名单:还需在工具页勾选要使用的 MCP 工具。",
485
+ "mcp.tabSaving": "正在保存…",
486
+ "connection.offline": "未连接到网关服务",
487
+ "connection.authenticationRequired": "认证不可用,请重新打开页面"
488
+ },
489
+ "en-US": {
490
+ "mcp.title": "MCP",
491
+ "mcp.servers": "MCP servers",
492
+ "mcp.add": "Add server",
493
+ "mcp.loading": "Loading…",
494
+ "mcp.listFailed": "Could not load servers",
495
+ "mcp.detailFailed": "Could not load server details",
496
+ "mcp.emptyTitle": "No MCP servers yet",
497
+ "mcp.emptyBody": "Add a server, then choose it in an agent’s settings to use its tools, resources and prompts.",
498
+ "mcp.enable": "Enable {{name}}",
499
+ "mcp.turnOn": "Enable",
500
+ "mcp.turnOff": "Disable",
501
+ "mcp.retry": "Retry",
502
+ "mcp.agents": "Agents",
503
+ "mcp.agentUses": "{{name}} uses this server",
504
+ "mcp.agentWhitelist": "Tool whitelist",
505
+ "mcp.noAgents": "No agents yet",
506
+ "mcp.state.disabled": "Disabled",
507
+ "mcp.state.connecting": "Connecting",
508
+ "mcp.state.connected": "Connected",
509
+ "mcp.state.needs-auth": "Needs authorization",
510
+ "mcp.state.reconnecting": "Reconnecting",
511
+ "mcp.state.failed": "Failed",
512
+ "mcp.readStatusReason": "Read failure reason",
513
+ "mcp.transport": "Connection",
514
+ "mcp.transport.stdio": "Local command (stdio)",
515
+ "mcp.transport.http": "Remote (HTTP)",
516
+ "mcp.name": "Name",
517
+ "mcp.slug": "Identifier",
518
+ "mcp.slugHelp": "Lowercase letters, digits and hyphens; tool names start with mcp_<identifier>_. Cannot be changed after creation.",
519
+ "mcp.command": "Command",
520
+ "mcp.commandHelp": "An absolute path or a command on PATH; pasting a whole command line splits out the arguments.",
521
+ "mcp.args": "Arguments",
522
+ "mcp.arg": "Argument {{n}}",
523
+ "mcp.argAdd": "Add argument",
524
+ "mcp.argRemove": "Remove argument {{n}}",
525
+ "mcp.argMove": "Drag to reorder argument {{n}}",
526
+ "mcp.more": "Working directory and environment",
527
+ "mcp.moreCwd": "working directory set",
528
+ "mcp.moreEnv": "{{count}} variables",
529
+ "mcp.cwd": "Working directory",
530
+ "mcp.env": "Environment variables",
531
+ "mcp.envName": "Variable name",
532
+ "mcp.envValue": "Value",
533
+ "mcp.envSecret": "Secret",
534
+ "mcp.envSecretOn": "Mark as secret",
535
+ "mcp.envSecretHelp": "Secret: stored encrypted, write-only",
536
+ "mcp.envAdd": "Add variable",
537
+ "mcp.envRemove": "Remove variable",
538
+ "mcp.url": "URL",
539
+ "mcp.auth": "Authentication",
540
+ "mcp.auth.none": "None",
541
+ "mcp.auth.headers": "Headers",
542
+ "mcp.auth.oauth": "OAuth",
543
+ "mcp.headers": "Headers",
544
+ "mcp.headerName": "Header name",
545
+ "mcp.headerValue": "Header value",
546
+ "mcp.headerAdd": "Add header",
547
+ "mcp.headerRemove": "Remove header",
548
+ "mcp.plainHttp": "This address is not on this machine and uses http://: credentials and content travel unencrypted.",
549
+ "mcp.risk": "Runs outside the sandbox with your user permissions",
550
+ "mcp.riskDetail": "It can read and write everything you can; save only if you trust it.",
551
+ "mcp.riskCwd": "Working directory: {{cwd}}",
552
+ "mcp.riskEnv": "Environment variables: {{names}}",
553
+ "mcp.trustSave": "Trust and save",
554
+ "mcp.save": "Save",
555
+ "mcp.saving": "Saving…",
556
+ "mcp.cancel": "Cancel",
557
+ "mcp.delete": "Delete",
558
+ "mcp.error.name": "Enter a name of 1–80 characters",
559
+ "mcp.error.slug": "Use 1–24 lowercase letters, digits or hyphens, starting with a letter or digit",
560
+ "mcp.error.command": "Enter a command",
561
+ "mcp.commandParseFailed": "Could not parse the command. Enter the command and arguments separately.",
562
+ "mcp.error.url": "Enter an http:// or https:// URL",
563
+ "mcp.error.envName": "A variable name starts with a letter or underscore and holds only letters, digits and underscores",
564
+ "mcp.error.headerName": "A header name holds only letters, digits, underscores and hyphens, does not start with a hyphen, and has at most 100 characters",
565
+ "mcp.error.duplicate": "This name is repeated",
566
+ "mcp.credentialsFailed": "The configuration was saved, but a credential was not written: {{reason}}",
567
+ "mcp.test": "Test connection",
568
+ "mcp.testing": "Testing…",
569
+ "mcp.testOk": "Connected: {{tools}} tools, {{resources}} resources, {{prompts}} prompts",
570
+ "mcp.testSaveFirst": "Save your changes before testing.",
571
+ "mcp.oauth": "Authorization",
572
+ "mcp.oauth.none": "Not authorized",
573
+ "mcp.oauth.authorized": "Authorized",
574
+ "mcp.oauth.expires": "Authorized, expires {{time}}",
575
+ "mcp.oauth.reauth": "Needs authorization again: {{reason}}",
576
+ "mcp.authorize": "Authorize",
577
+ "mcp.authorizePending": "Waiting for authorization",
578
+ "mcp.authorizeHint": "Complete authorization in the browser. This page updates automatically.",
579
+ "mcp.authorizeOpen": "Open authorization page",
580
+ "mcp.copyLink": "Copy link",
581
+ "mcp.copied": "Copied",
582
+ "mcp.showLink": "Show authorization address",
583
+ "mcp.copyLinkFailed": "Could not copy the link. Expand the authorization address and copy it manually.",
584
+ "mcp.authorizeWaiting": "Waiting for authorization to finish in the browser…",
585
+ "mcp.authorizeCancel": "Cancel authorization",
586
+ "mcp.authorizeBlocked": "The browser blocked the new window. Open the authorization page here:",
587
+ "mcp.authorizeFailed": "Could not open the system browser. Copy the address and open it yourself:",
588
+ "mcp.authorizeFailedTitle": "Could not open the authorization page",
589
+ "mcp.signOut": "Sign out",
590
+ "mcp.capabilities": "Capabilities",
591
+ "mcp.connection": "Connection",
592
+ "mcp.filterCapabilities": "Filter tools, resources and prompts",
593
+ "mcp.noMatches": "Nothing matches",
594
+ "mcp.kinds": "Filter by kind",
595
+ "mcp.kind.all": "All",
596
+ "mcp.kind.tools": "Tools",
597
+ "mcp.kind.resources": "Resources",
598
+ "mcp.kind.prompts": "Prompts",
599
+ "mcp.parameters": "Parameters",
600
+ "mcp.required": "Required",
601
+ "mcp.noParameters": "No parameters",
602
+ "mcp.noDescription": "The server gives no description",
603
+ "mcp.mimeType": "Content type",
604
+ "mcp.refused": "Not registered: {{reason}}",
605
+ "mcp.noCapabilities": "Listed here once connected.",
606
+ "mcp.deleteTitle": "Delete server",
607
+ "mcp.deleteBody": "Deleting “{{name}}” withdraws its tools, stops its process and clears its credentials.",
608
+ "mcp.deleteAgents": "These agents will lose it: {{names}}",
609
+ "mcp.deleteConfirm": "Delete server",
610
+ "mcp.unsavedTitle": "Unsaved changes",
611
+ "mcp.unsavedBody": "Your changes have not been saved. Leaving will discard them.",
612
+ "mcp.keepEditing": "Keep editing",
613
+ "mcp.discard": "Discard changes",
614
+ "mcp.tabEmpty": "No MCP servers yet",
615
+ "mcp.tabEmptyHint": "Add one under Settings → Extensions → MCP.",
616
+ "mcp.tabWhitelist": "This agent has a tool whitelist: also tick the MCP tools it should use on the Tools tab.",
617
+ "mcp.tabSaving": "Saving…",
618
+ "connection.offline": "Not connected to the gateway",
619
+ "connection.authenticationRequired": "Authentication is unavailable. Reopen this page."
620
+ }
621
+ };
622
+ /** Fills `{{name}}` placeholders in a translated string. */
623
+ function fill(text, values) {
624
+ return text.replace(/\{\{(\w+)\}\}/g, (whole, key) => key in values ? String(values[key]) : whole);
625
+ }
626
+ //#endregion
627
+ //#region src/command-text.ts
628
+ /** Shared command-paste input bounds for the owner RPC and browser editor. */
629
+ var COMMAND_TEXT_LIMIT = 65536;
630
+ /** Checks the UTF-8 byte limit before command text crosses the authenticated connection. */
631
+ function commandTextFits(text) {
632
+ return new TextEncoder().encode(text).length <= COMMAND_TEXT_LIMIT;
633
+ }
634
+ //#endregion
635
+ //#region src/names.ts
636
+ /**
637
+ * The name rules both halves apply: the gateway's zod in `config.ts` and the
638
+ * settings form in `ui/draft.ts`. Imports nothing, so the browser program can
639
+ * take it without Node types.
640
+ */
641
+ /** A server's short name: part of every tool and command name it contributes. */
642
+ var SLUG = /^[a-z0-9][a-z0-9-]{0,23}$/;
643
+ /** An environment variable a person configures: a portable shell identifier. */
644
+ var ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
645
+ /** An HTTP header name (RFC 9110 token) that is also a valid credential name. */
646
+ var HEADER_NAME = /^[A-Za-z0-9_][A-Za-z0-9_-]{0,99}$/;
647
+ //#endregion
648
+ //#region src/ui/draft.ts
649
+ /**
650
+ * The server form's draft and the pure rules over it: what it saves as, what
651
+ * the risk confirmation is bound to, what a person must fix, and which
652
+ * credential writes a save implies.
653
+ */
654
+ var nextKey = 1;
655
+ /** A row key unique within this page; never saved. */
656
+ var rowKey = () => nextKey++;
657
+ function isStdio(config) {
658
+ return "command" in config;
659
+ }
660
+ function draftFrom(detail) {
661
+ const empty = {
662
+ name: "",
663
+ slug: "",
664
+ transport: "stdio",
665
+ command: "",
666
+ args: [],
667
+ cwd: "",
668
+ env: [],
669
+ url: "",
670
+ auth: "none",
671
+ headers: []
672
+ };
673
+ if (!detail) return empty;
674
+ const base = {
675
+ ...empty,
676
+ name: detail.name,
677
+ slug: detail.slug,
678
+ transport: detail.transport
679
+ };
680
+ if (isStdio(detail.config)) return {
681
+ ...base,
682
+ command: detail.config.command,
683
+ args: detail.config.args.map((value) => ({
684
+ key: rowKey(),
685
+ value
686
+ })),
687
+ cwd: detail.config.cwd ?? "",
688
+ env: detail.config.env.map((entry) => ({
689
+ key: rowKey(),
690
+ name: entry.name,
691
+ secret: entry.secret,
692
+ value: entry.secret ? "" : entry.value ?? "",
693
+ cleared: false
694
+ }))
695
+ };
696
+ return {
697
+ ...base,
698
+ url: detail.config.url,
699
+ auth: detail.config.auth,
700
+ headers: detail.config.headers.map((name) => ({
701
+ key: rowKey(),
702
+ name,
703
+ value: "",
704
+ cleared: false
705
+ }))
706
+ };
707
+ }
708
+ /** Rows a person added and left blank are not part of the configuration. */
709
+ var usedEnv = (draft) => draft.env.filter((row) => row.name.trim() || row.value);
710
+ var usedHeaders = (draft) => draft.auth === "headers" ? draft.headers.filter((row) => row.name.trim() || row.value) : [];
711
+ function configOf(draft) {
712
+ if (draft.transport === "stdio") {
713
+ const cwd = draft.cwd;
714
+ return {
715
+ command: draft.command,
716
+ args: draft.args.map((row) => row.value),
717
+ ...cwd ? { cwd } : {},
718
+ env: usedEnv(draft).map((row) => row.secret ? {
719
+ name: row.name.trim(),
720
+ secret: true
721
+ } : {
722
+ name: row.name.trim(),
723
+ secret: false,
724
+ value: row.value
725
+ })
726
+ };
727
+ }
728
+ return {
729
+ url: draft.url.trim(),
730
+ auth: draft.auth,
731
+ headers: usedHeaders(draft).map((row) => row.name.trim())
732
+ };
733
+ }
734
+ /**
735
+ * What the risk confirmation is bound to: command, arguments, working
736
+ * directory and the set of variable names. A display name or a variable's
737
+ * value can change without asking again.
738
+ */
739
+ function riskKey(config) {
740
+ if (!isStdio(config)) return null;
741
+ return JSON.stringify([
742
+ config.command,
743
+ config.args,
744
+ config.cwd ?? "",
745
+ config.env.map((entry) => entry.name).sort()
746
+ ]);
747
+ }
748
+ /** Whether saving this draft needs a fresh confirmation. */
749
+ function needsAcknowledgement(draft, detail) {
750
+ if (draft.transport !== "stdio") return false;
751
+ if (!detail || !detail.acknowledged || !isStdio(detail.config)) return true;
752
+ return riskKey(configOf(draft)) !== riskKey(detail.config);
753
+ }
754
+ /** The command line as it will run, each word quoted when a shell would split it. */
755
+ function commandLine(config) {
756
+ return [config.command, ...config.args].map((word) => word === "" || /[^\w@%+=:,./-]/.test(word) ? `'${word.replace(/'/g, `'\\''`)}'` : word).join(" ");
757
+ }
758
+ /** Variable names that read as a secret, so a pasted one is marked as such. */
759
+ var SECRET_NAME = /KEY|SECRET|TOKEN|PASSWORD/i;
760
+ /**
761
+ * Pasted `NAME=value` lines, as a `.env` file or an `export` list holds them:
762
+ * blank lines and `#` comments skipped, one pair of surrounding quotes taken
763
+ * off the value. `null` when a line is not an assignment, so ordinary text
764
+ * pastes as text.
765
+ */
766
+ function parseEnvBlock(text) {
767
+ const lines = text.split(/\r?\n/).map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
768
+ if (!lines.length) return null;
769
+ const rows = [];
770
+ for (const line of lines) {
771
+ const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);
772
+ if (!match) return null;
773
+ const name = match[1];
774
+ const raw = match[2];
775
+ const value = /^(['"]).*\1$/.test(raw) ? raw.slice(1, -1) : raw;
776
+ rows.push({
777
+ name,
778
+ value,
779
+ secret: SECRET_NAME.test(name)
780
+ });
781
+ }
782
+ return rows;
783
+ }
784
+ /** A plain-http address that leaves this machine. */
785
+ function isPlainRemoteHttp(url) {
786
+ let parsed;
787
+ try {
788
+ parsed = new URL(url.trim());
789
+ } catch {
790
+ return false;
791
+ }
792
+ if (parsed.protocol !== "http:") return false;
793
+ const host = parsed.hostname.replace(/^\[|\]$/g, "");
794
+ return !(host === "localhost" || host.endsWith(".localhost") || host === "::1" || /^127\./.test(host));
795
+ }
796
+ /** Field key → catalogue key of the message to show beside it. */
797
+ function validate(draft, creating) {
798
+ const errors = {};
799
+ const name = draft.name.trim();
800
+ if (!name || [...name].length > 80) errors.name = "mcp.error.name";
801
+ if (creating && !SLUG.test(draft.slug)) errors.slug = "mcp.error.slug";
802
+ if (draft.transport === "stdio") {
803
+ if (!draft.command.trim()) errors.command = "mcp.error.command";
804
+ const seen = /* @__PURE__ */ new Set();
805
+ for (const row of usedEnv(draft)) {
806
+ const key = `env:${row.key}`;
807
+ const rowName = row.name.trim();
808
+ if (!ENV_NAME.test(rowName) || rowName.startsWith("YAOGUANG_")) errors[key] = "mcp.error.envName";
809
+ else if (seen.has(rowName)) errors[key] = "mcp.error.duplicate";
810
+ seen.add(rowName);
811
+ }
812
+ } else {
813
+ let valid = false;
814
+ try {
815
+ valid = ["http:", "https:"].includes(new URL(draft.url.trim()).protocol);
816
+ } catch {}
817
+ if (!valid) errors.url = "mcp.error.url";
818
+ const seen = /* @__PURE__ */ new Set();
819
+ for (const row of usedHeaders(draft)) {
820
+ const key = `header:${row.key}`;
821
+ const rowName = row.name.trim();
822
+ if (!HEADER_NAME.test(rowName)) errors[key] = "mcp.error.headerName";
823
+ else if (seen.has(rowName.toLowerCase())) errors[key] = "mcp.error.duplicate";
824
+ seen.add(rowName.toLowerCase());
825
+ }
826
+ }
827
+ return errors;
828
+ }
829
+ /**
830
+ * The credential writes a save implies, given the names already stored:
831
+ * every typed replacement is set; a stored `env.*` or `header.*` name the
832
+ * saved configuration no longer carries as a credential, or one the person
833
+ * cleared without typing a replacement, is cleared. Machine-written names
834
+ * (`oauth.*`) are the gateway half's and are never touched here.
835
+ */
836
+ function credentialPlan(draft, stored) {
837
+ const set = [];
838
+ const wanted = /* @__PURE__ */ new Map();
839
+ if (draft.transport === "stdio") for (const row of usedEnv(draft)) {
840
+ if (!row.secret) continue;
841
+ const name = envCredential(row.name.trim());
842
+ wanted.set(name, row.cleared);
843
+ if (row.value.trim()) set.push({
844
+ name,
845
+ value: row.value
846
+ });
847
+ }
848
+ else for (const row of usedHeaders(draft)) {
849
+ const name = headerCredential(row.name.trim());
850
+ wanted.set(name, row.cleared);
851
+ if (row.value.trim()) set.push({
852
+ name,
853
+ value: row.value
854
+ });
855
+ }
856
+ const setNames = new Set(set.map((one) => one.name));
857
+ return {
858
+ set,
859
+ clear: [...stored].filter((name) => {
860
+ if (!name.startsWith("env.") && !name.startsWith("header.")) return false;
861
+ if (!wanted.has(name)) return true;
862
+ return wanted.get(name) === true && !setNames.has(name);
863
+ })
864
+ };
865
+ }
866
+ /** A comparable snapshot of everything a save would send. */
867
+ function fingerprint(draft) {
868
+ return JSON.stringify([
869
+ draft.name.trim(),
870
+ draft.slug,
871
+ draft.transport,
872
+ configOf(draft)
873
+ ]);
874
+ }
875
+ /** Whether the draft carries credential edits not yet written. */
876
+ function hasCredentialEdits(draft) {
877
+ return (draft.transport === "stdio" ? draft.env.filter((row) => row.secret) : draft.headers).some((row) => row.cleared || row.value.trim() !== "");
878
+ }
879
+ //#endregion
880
+ //#region src/ui/editor.tsx
881
+ function ServerEditor({ ctx, detail, onSaved, registerGuard, children }) {
882
+ const t = ctx.i18n.t;
883
+ const creating = !detail;
884
+ const [draft, setDraft] = useState(() => draftFrom(detail));
885
+ const baseline = useRef(fingerprint(draft));
886
+ const editingRevision = useRef(0);
887
+ const [stored, setStored] = useState(/* @__PURE__ */ new Map());
888
+ const [credentialsLoading, setCredentialsLoading] = useState(!creating);
889
+ const [credentialsError, setCredentialsError] = useState(null);
890
+ const reloadCredentials = useRef(() => {});
891
+ const [dragging, setDragging] = useState(null);
892
+ const [moreOpen, setMoreOpen] = useState(() => draft.cwd !== "" || draft.env.length > 0);
893
+ const [showErrors, setShowErrors] = useState(false);
894
+ const [saving, setSaving] = useState(false);
895
+ const savingRef = useRef(false);
896
+ const [error, setError] = useState(null);
897
+ const [testing, setTesting] = useState(false);
898
+ const testingRef = useRef(false);
899
+ const [test, setTest] = useState(null);
900
+ useEffect(() => {
901
+ let connection = ctx.host.get().connection;
902
+ const unsubscribe = ctx.host.subscribe(() => {
903
+ const next = ctx.host.get().connection;
904
+ if (next !== connection) editingRevision.current++;
905
+ connection = next;
906
+ });
907
+ return () => {
908
+ editingRevision.current++;
909
+ unsubscribe();
910
+ };
911
+ }, [ctx, detail?.id]);
912
+ useEffect(() => {
913
+ if (!detail) return;
914
+ let live = true;
915
+ let reading = false;
916
+ const read = async () => {
917
+ if (reading || !live || ctx.signal.aborted) return;
918
+ reading = true;
919
+ setCredentialsLoading(true);
920
+ setCredentialsError(null);
921
+ try {
922
+ const rows = await ctx.credentials.status(detail.id);
923
+ if (live && !ctx.signal.aborted) setStored(new Map(rows.map((row) => [row.name, row.hint])));
924
+ } catch (failure) {
925
+ if (live && !ctx.signal.aborted) setCredentialsError(failureText(ctx, failure));
926
+ } finally {
927
+ reading = false;
928
+ if (live && !ctx.signal.aborted) setCredentialsLoading(false);
929
+ }
930
+ };
931
+ reloadCredentials.current = () => {
932
+ read();
933
+ };
934
+ read();
935
+ return () => {
936
+ live = false;
937
+ reloadCredentials.current = () => {};
938
+ };
939
+ }, [ctx, detail?.id]);
940
+ const config = configOf(draft);
941
+ const dirty = fingerprint(draft) !== baseline.current || hasCredentialEdits(draft);
942
+ const dirtyRef = useRef(dirty);
943
+ dirtyRef.current = dirty;
944
+ useEffect(() => {
945
+ registerGuard?.(() => !dirtyRef.current);
946
+ return () => registerGuard?.(null);
947
+ }, [registerGuard]);
948
+ const needsAck = needsAcknowledgement(draft, detail);
949
+ const errors = validate(draft, creating);
950
+ const errorFor = (key) => showErrors && errors[key] ? t(errors[key]) : void 0;
951
+ const update = (patch) => {
952
+ editingRevision.current++;
953
+ setDraft((current) => ({
954
+ ...current,
955
+ ...patch
956
+ }));
957
+ setTest(null);
958
+ };
959
+ const updateEnv = (key, patch) => update({ env: draft.env.map((row) => row.key === key ? {
960
+ ...row,
961
+ ...patch
962
+ } : row) });
963
+ const insertArg = (at) => {
964
+ const row = {
965
+ key: rowKey(),
966
+ value: ""
967
+ };
968
+ update({ args: [
969
+ ...draft.args.slice(0, at),
970
+ row,
971
+ ...draft.args.slice(at)
972
+ ] });
973
+ focusArg.current = row.key;
974
+ };
975
+ const removeArg = (key, focusAt) => {
976
+ const rest = draft.args.filter((one) => one.key !== key);
977
+ update({ args: rest });
978
+ const next = focusAt === null ? void 0 : rest[Math.max(0, focusAt)];
979
+ if (next) focusArg.current = next.key;
980
+ };
981
+ const moveArg = (from, to) => {
982
+ if (from === to || to < 0 || to >= draft.args.length) return;
983
+ const next = [...draft.args];
984
+ const [moved] = next.splice(from, 1);
985
+ if (moved) next.splice(to, 0, moved);
986
+ update({ args: next });
987
+ };
988
+ const focusArg = useRef(null);
989
+ useEffect(() => {
990
+ if (focusArg.current === null) return;
991
+ const input = document.querySelector(`[data-arg-key="${focusArg.current}"]`);
992
+ focusArg.current = null;
993
+ input?.focus();
994
+ });
995
+ const moreHint = [draft.cwd.trim() ? t("mcp.moreCwd") : "", isStdio(config) && config.env.length ? fill(t("mcp.moreEnv"), { count: config.env.length }) : ""].filter(Boolean).join(" · ");
996
+ const updateHeader = (key, patch) => update({ headers: draft.headers.map((row) => row.key === key ? {
997
+ ...row,
998
+ ...patch
999
+ } : row) });
1000
+ async function save() {
1001
+ if (savingRef.current || testingRef.current) return;
1002
+ setShowErrors(true);
1003
+ setError(null);
1004
+ if (Object.keys(errors).length) return;
1005
+ savingRef.current = true;
1006
+ setSaving(true);
1007
+ const params = {
1008
+ ...detail ? { id: detail.id } : {},
1009
+ slug: detail ? detail.slug : draft.slug,
1010
+ name: draft.name.trim(),
1011
+ transport: draft.transport,
1012
+ config,
1013
+ ...needsAck ? { acknowledge: true } : {}
1014
+ };
1015
+ let saved;
1016
+ try {
1017
+ saved = await ctx.invoke(METHOD.saveServer, params);
1018
+ } catch (failure) {
1019
+ savingRef.current = false;
1020
+ if (!ctx.signal.aborted) {
1021
+ setError(failureText(ctx, failure));
1022
+ setSaving(false);
1023
+ }
1024
+ return;
1025
+ }
1026
+ const plan = credentialPlan(draft, new Set(stored.keys()));
1027
+ let notice;
1028
+ try {
1029
+ for (const one of plan.set) await ctx.credentials.set(saved.id, one.name, one.value);
1030
+ for (const name of plan.clear) await ctx.credentials.clear(saved.id, name);
1031
+ } catch (failure) {
1032
+ const reason = failureText(ctx, failure);
1033
+ if (reason !== null) notice = fill(t("mcp.credentialsFailed"), { reason });
1034
+ }
1035
+ if (!notice && (creating || plan.set.length || plan.clear.length)) try {
1036
+ await ctx.invoke(METHOD.retryServer, { id: saved.id });
1037
+ } catch (failure) {
1038
+ notice = failureText(ctx, failure) ?? void 0;
1039
+ }
1040
+ savingRef.current = false;
1041
+ if (ctx.signal.aborted) return;
1042
+ setSaving(false);
1043
+ baseline.current = fingerprint(draft);
1044
+ onSaved(saved, notice);
1045
+ }
1046
+ async function runTest() {
1047
+ if (!detail || testingRef.current || savingRef.current) return;
1048
+ testingRef.current = true;
1049
+ setTesting(true);
1050
+ setTest(null);
1051
+ try {
1052
+ const result = await ctx.invoke(METHOD.testServer, { id: detail.id });
1053
+ if (ctx.signal.aborted) return;
1054
+ setTest(result.ok ? {
1055
+ ok: true,
1056
+ text: fill(t("mcp.testOk"), {
1057
+ tools: result.tools,
1058
+ resources: result.resources,
1059
+ prompts: result.prompts
1060
+ })
1061
+ } : {
1062
+ ok: false,
1063
+ text: result.reason
1064
+ });
1065
+ } catch (failure) {
1066
+ const text = failureText(ctx, failure);
1067
+ if (!ctx.signal.aborted && text !== null) setTest({
1068
+ ok: false,
1069
+ text
1070
+ });
1071
+ } finally {
1072
+ testingRef.current = false;
1073
+ if (!ctx.signal.aborted) setTesting(false);
1074
+ }
1075
+ }
1076
+ const row = (label, key, control, help, required = false) => /* @__PURE__ */ jsx(ctx.ui.Field, {
1077
+ inline: true,
1078
+ label,
1079
+ help,
1080
+ error: errorFor(key),
1081
+ required,
1082
+ children: (binding) => typeof control === "function" ? control(binding) : control
1083
+ });
1084
+ return /* @__PURE__ */ jsxs("form", {
1085
+ className: "mcp-form",
1086
+ noValidate: true,
1087
+ onSubmit: (event) => {
1088
+ event.preventDefault();
1089
+ save();
1090
+ },
1091
+ children: [
1092
+ creating && row(t("mcp.slug"), "slug", (binding) => /* @__PURE__ */ jsx(ctx.ui.Input, {
1093
+ ...binding,
1094
+ value: draft.slug,
1095
+ maxLength: 24,
1096
+ autoComplete: "off",
1097
+ spellCheck: false,
1098
+ onChange: (event) => update({ slug: event.currentTarget.value })
1099
+ }), t("mcp.slugHelp"), true),
1100
+ row(t("mcp.name"), "name", (binding) => /* @__PURE__ */ jsx(ctx.ui.Input, {
1101
+ ...binding,
1102
+ value: draft.name,
1103
+ maxLength: 80,
1104
+ onChange: (event) => update({ name: event.currentTarget.value })
1105
+ }), void 0, true),
1106
+ row(t("mcp.transport"), "transport", () => /* @__PURE__ */ jsx(ctx.ui.Segmented, {
1107
+ label: t("mcp.transport"),
1108
+ value: draft.transport,
1109
+ options: [{
1110
+ value: "stdio",
1111
+ label: t("mcp.transport.stdio")
1112
+ }, {
1113
+ value: "http",
1114
+ label: t("mcp.transport.http")
1115
+ }],
1116
+ onSelect: (value) => update({ transport: value }),
1117
+ fullWidth: true
1118
+ })),
1119
+ draft.transport === "stdio" ? /* @__PURE__ */ jsxs(Fragment, { children: [
1120
+ row(t("mcp.command"), "command", (binding) => /* @__PURE__ */ jsx(ctx.ui.Input, {
1121
+ ...binding,
1122
+ value: draft.command,
1123
+ spellCheck: false,
1124
+ autoComplete: "off",
1125
+ onChange: (event) => update({ command: event.currentTarget.value }),
1126
+ onPaste: (event) => {
1127
+ const text = event.clipboardData.getData("text");
1128
+ event.preventDefault();
1129
+ editingRevision.current++;
1130
+ setError(null);
1131
+ if (!commandTextFits(text)) {
1132
+ setError(t("mcp.commandParseFailed"));
1133
+ return;
1134
+ }
1135
+ update({ command: text });
1136
+ const revision = editingRevision.current;
1137
+ ctx.invoke(METHOD.commandParse, { text }).then((parsed) => {
1138
+ if (editingRevision.current !== revision || ctx.signal.aborted || ctx.host.get().connection !== "online") return;
1139
+ update({
1140
+ command: parsed.file,
1141
+ args: parsed.args.map((value) => ({
1142
+ key: rowKey(),
1143
+ value
1144
+ }))
1145
+ });
1146
+ }).catch(() => {
1147
+ if (editingRevision.current === revision && !ctx.signal.aborted) setError(t("mcp.commandParseFailed"));
1148
+ });
1149
+ }
1150
+ }), t("mcp.commandHelp"), true),
1151
+ /* @__PURE__ */ jsxs("fieldset", {
1152
+ className: "mcp-table",
1153
+ children: [
1154
+ /* @__PURE__ */ jsx("legend", { children: t("mcp.args") }),
1155
+ draft.args.length > 0 && /* @__PURE__ */ jsx("ol", {
1156
+ className: "mcp-args",
1157
+ children: draft.args.map((arg, index) => /* @__PURE__ */ jsx(ArgRowView, {
1158
+ ctx,
1159
+ arg,
1160
+ index,
1161
+ dragging,
1162
+ onDrag: setDragging,
1163
+ onMove: moveArg,
1164
+ onChange: (value) => update({ args: draft.args.map((one) => one.key === arg.key ? {
1165
+ ...one,
1166
+ value
1167
+ } : one) }),
1168
+ onInsertAfter: () => insertArg(index + 1),
1169
+ onRemove: (focusPrevious) => removeArg(arg.key, focusPrevious ? index - 1 : null)
1170
+ }, arg.key))
1171
+ }),
1172
+ /* @__PURE__ */ jsx(ctx.ui.Button, {
1173
+ variant: "outline",
1174
+ size: "sm",
1175
+ icon: "plus",
1176
+ onClick: () => insertArg(draft.args.length),
1177
+ children: t("mcp.argAdd")
1178
+ })
1179
+ ]
1180
+ }),
1181
+ /* @__PURE__ */ jsxs(ctx.ui.Disclosure, {
1182
+ className: "mcp-more",
1183
+ open: moreOpen,
1184
+ onToggle: (event) => setMoreOpen(event.currentTarget.open),
1185
+ children: [/* @__PURE__ */ jsxs(ctx.ui.DisclosureSummary, {
1186
+ className: "mcp-more-summary",
1187
+ children: [t("mcp.more"), moreHint && /* @__PURE__ */ jsx("span", {
1188
+ className: "mcp-more-hint",
1189
+ children: ` · ${moreHint}`
1190
+ })]
1191
+ }), /* @__PURE__ */ jsxs("div", {
1192
+ className: "mcp-more-body",
1193
+ children: [row(t("mcp.cwd"), "cwd", (binding) => /* @__PURE__ */ jsx(ctx.ui.PathInput, {
1194
+ ...binding,
1195
+ value: draft.cwd,
1196
+ onValueChange: (cwd) => update({ cwd })
1197
+ })), /* @__PURE__ */ jsxs("fieldset", {
1198
+ className: "mcp-table",
1199
+ children: [
1200
+ /* @__PURE__ */ jsx("legend", { children: t("mcp.env") }),
1201
+ draft.env.length > 0 && /* @__PURE__ */ jsx("div", {
1202
+ className: "mcp-kv",
1203
+ children: draft.env.map((entry, index) => {
1204
+ const n = index + 1;
1205
+ const hint = stored.get(envCredential(entry.name.trim()));
1206
+ const rowError = errorFor(`env:${entry.key}`);
1207
+ return /* @__PURE__ */ jsxs("div", {
1208
+ className: "mcp-kv-row",
1209
+ children: [
1210
+ /* @__PURE__ */ jsx(ctx.ui.Input, {
1211
+ "aria-label": `${t("mcp.envName")} ${n}`,
1212
+ "aria-invalid": rowError ? true : void 0,
1213
+ placeholder: t("mcp.envName"),
1214
+ spellCheck: false,
1215
+ autoComplete: "off",
1216
+ className: "mcp-mono",
1217
+ value: entry.name,
1218
+ onChange: (event) => updateEnv(entry.key, { name: event.currentTarget.value }),
1219
+ onPaste: (event) => {
1220
+ const rows = parseEnvBlock(event.clipboardData.getData("text"));
1221
+ if (!rows) return;
1222
+ event.preventDefault();
1223
+ update({ env: draft.env.flatMap((one) => one.key === entry.key ? rows.map((next) => ({
1224
+ key: rowKey(),
1225
+ ...next,
1226
+ cleared: false
1227
+ })) : [one]) });
1228
+ }
1229
+ }),
1230
+ entry.secret ? /* @__PURE__ */ jsx(ctx.ui.SecretInput, {
1231
+ label: `${t("mcp.envValue")} ${n}`,
1232
+ value: entry.value,
1233
+ stored: hint !== void 0 && !entry.cleared,
1234
+ ...hint !== void 0 ? { hint } : {},
1235
+ onValueChange: (value) => updateEnv(entry.key, { value }),
1236
+ onClear: () => updateEnv(entry.key, {
1237
+ cleared: true,
1238
+ value: ""
1239
+ })
1240
+ }) : /* @__PURE__ */ jsx(ctx.ui.Input, {
1241
+ "aria-label": `${t("mcp.envValue")} ${n}`,
1242
+ placeholder: t("mcp.envValue"),
1243
+ spellCheck: false,
1244
+ autoComplete: "off",
1245
+ value: entry.value,
1246
+ onChange: (event) => updateEnv(entry.key, { value: event.currentTarget.value })
1247
+ }),
1248
+ /* @__PURE__ */ jsx(ctx.ui.Tooltip, {
1249
+ content: entry.secret ? t("mcp.envSecretHelp") : t("mcp.envSecretOn"),
1250
+ children: /* @__PURE__ */ jsx(ctx.ui.Button, {
1251
+ variant: "ghost",
1252
+ size: "sm",
1253
+ icon: entry.secret ? "lock" : "unlock",
1254
+ className: "mcp-icon",
1255
+ "aria-label": `${t("mcp.envSecret")} ${n}`,
1256
+ "aria-pressed": entry.secret,
1257
+ onClick: () => updateEnv(entry.key, { secret: !entry.secret })
1258
+ })
1259
+ }),
1260
+ /* @__PURE__ */ jsx(ctx.ui.Button, {
1261
+ variant: "ghost",
1262
+ size: "sm",
1263
+ icon: "trash",
1264
+ className: "mcp-icon mcp-hover-action",
1265
+ "aria-label": `${t("mcp.envRemove")} ${n}`,
1266
+ onClick: () => update({ env: draft.env.filter((one) => one.key !== entry.key) })
1267
+ }),
1268
+ rowError && /* @__PURE__ */ jsx("p", {
1269
+ role: "alert",
1270
+ className: "mcp-row-error",
1271
+ children: rowError
1272
+ })
1273
+ ]
1274
+ }, entry.key);
1275
+ })
1276
+ }),
1277
+ /* @__PURE__ */ jsx(ctx.ui.Button, {
1278
+ variant: "outline",
1279
+ size: "sm",
1280
+ icon: "plus",
1281
+ onClick: () => update({ env: [...draft.env, {
1282
+ key: rowKey(),
1283
+ name: "",
1284
+ secret: false,
1285
+ value: "",
1286
+ cleared: false
1287
+ }] }),
1288
+ children: t("mcp.envAdd")
1289
+ })
1290
+ ]
1291
+ })]
1292
+ })]
1293
+ })
1294
+ ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
1295
+ row(t("mcp.url"), "url", (binding) => /* @__PURE__ */ jsx(ctx.ui.Input, {
1296
+ ...binding,
1297
+ type: "url",
1298
+ spellCheck: false,
1299
+ value: draft.url,
1300
+ placeholder: "https://",
1301
+ onChange: (event) => update({ url: event.currentTarget.value })
1302
+ }), void 0, true),
1303
+ isPlainRemoteHttp(draft.url) && /* @__PURE__ */ jsx(ctx.ui.Alert, {
1304
+ tone: "warning",
1305
+ className: "mcp-alert",
1306
+ children: t("mcp.plainHttp")
1307
+ }),
1308
+ row(t("mcp.auth"), "auth", () => /* @__PURE__ */ jsx(ctx.ui.Segmented, {
1309
+ label: t("mcp.auth"),
1310
+ value: draft.auth,
1311
+ options: [
1312
+ {
1313
+ value: "none",
1314
+ label: t("mcp.auth.none")
1315
+ },
1316
+ {
1317
+ value: "headers",
1318
+ label: t("mcp.auth.headers")
1319
+ },
1320
+ {
1321
+ value: "oauth",
1322
+ label: t("mcp.auth.oauth")
1323
+ }
1324
+ ],
1325
+ onSelect: (value) => update({ auth: value }),
1326
+ fullWidth: true
1327
+ })),
1328
+ draft.auth === "headers" && /* @__PURE__ */ jsxs("fieldset", {
1329
+ className: "mcp-table",
1330
+ children: [
1331
+ /* @__PURE__ */ jsx("legend", { children: t("mcp.headers") }),
1332
+ draft.headers.length > 0 && /* @__PURE__ */ jsx("div", {
1333
+ className: "mcp-kv",
1334
+ "data-columns": "3",
1335
+ children: draft.headers.map((entry, index) => {
1336
+ const n = index + 1;
1337
+ const hint = stored.get(headerCredential(entry.name.trim()));
1338
+ const rowError = errorFor(`header:${entry.key}`);
1339
+ return /* @__PURE__ */ jsxs("div", {
1340
+ className: "mcp-kv-row",
1341
+ children: [
1342
+ /* @__PURE__ */ jsx(ctx.ui.Input, {
1343
+ "aria-label": `${t("mcp.headerName")} ${n}`,
1344
+ "aria-invalid": rowError ? true : void 0,
1345
+ placeholder: t("mcp.headerName"),
1346
+ spellCheck: false,
1347
+ autoComplete: "off",
1348
+ className: "mcp-mono",
1349
+ value: entry.name,
1350
+ onChange: (event) => updateHeader(entry.key, { name: event.currentTarget.value })
1351
+ }),
1352
+ /* @__PURE__ */ jsx(ctx.ui.SecretInput, {
1353
+ label: `${t("mcp.headerValue")} ${n}`,
1354
+ value: entry.value,
1355
+ stored: hint !== void 0 && !entry.cleared,
1356
+ ...hint !== void 0 ? { hint } : {},
1357
+ onValueChange: (value) => updateHeader(entry.key, { value }),
1358
+ onClear: () => updateHeader(entry.key, {
1359
+ cleared: true,
1360
+ value: ""
1361
+ })
1362
+ }),
1363
+ /* @__PURE__ */ jsx(ctx.ui.Button, {
1364
+ variant: "ghost",
1365
+ size: "sm",
1366
+ icon: "trash",
1367
+ className: "mcp-icon mcp-hover-action",
1368
+ "aria-label": `${t("mcp.headerRemove")} ${n}`,
1369
+ onClick: () => update({ headers: draft.headers.filter((one) => one.key !== entry.key) })
1370
+ }),
1371
+ rowError && /* @__PURE__ */ jsx("p", {
1372
+ role: "alert",
1373
+ className: "mcp-row-error",
1374
+ children: rowError
1375
+ })
1376
+ ]
1377
+ }, entry.key);
1378
+ })
1379
+ }),
1380
+ /* @__PURE__ */ jsx(ctx.ui.Button, {
1381
+ variant: "outline",
1382
+ size: "sm",
1383
+ icon: "plus",
1384
+ onClick: () => update({ headers: [...draft.headers, {
1385
+ key: rowKey(),
1386
+ name: "",
1387
+ value: "",
1388
+ cleared: false
1389
+ }] }),
1390
+ children: t("mcp.headerAdd")
1391
+ })
1392
+ ]
1393
+ })
1394
+ ] }),
1395
+ children,
1396
+ credentialsLoading && /* @__PURE__ */ jsx(ctx.ui.Spinner, { label: t("mcp.loading") }),
1397
+ credentialsError && /* @__PURE__ */ jsx(ctx.ui.Alert, {
1398
+ tone: "destructive",
1399
+ role: "alert",
1400
+ className: "mcp-alert",
1401
+ children: /* @__PURE__ */ jsxs("div", {
1402
+ className: "flex flex-wrap items-start justify-between gap-2",
1403
+ children: [/* @__PURE__ */ jsx("p", {
1404
+ className: "min-w-0 flex-1",
1405
+ children: credentialsError
1406
+ }), /* @__PURE__ */ jsx(ctx.ui.Button, {
1407
+ variant: "outline",
1408
+ size: "sm",
1409
+ onClick: () => reloadCredentials.current(),
1410
+ children: t("mcp.retry")
1411
+ })]
1412
+ })
1413
+ }),
1414
+ error && /* @__PURE__ */ jsx(ctx.ui.Alert, {
1415
+ tone: "destructive",
1416
+ role: "alert",
1417
+ className: "mcp-alert",
1418
+ children: error
1419
+ }),
1420
+ /* @__PURE__ */ jsxs("div", {
1421
+ className: "mcp-footer",
1422
+ children: [
1423
+ needsAck && /* @__PURE__ */ jsxs("div", {
1424
+ className: "mcp-risk",
1425
+ role: "note",
1426
+ children: [/* @__PURE__ */ jsx("p", {
1427
+ className: "mcp-risk-title",
1428
+ children: t("mcp.risk")
1429
+ }), config.command && /* @__PURE__ */ jsx(ctx.ui.Tooltip, {
1430
+ content: riskFacts(ctx, config),
1431
+ side: "top",
1432
+ children: /* @__PURE__ */ jsx(ctx.ui.Button, {
1433
+ variant: "plain",
1434
+ className: "mcp-risk-command",
1435
+ children: /* @__PURE__ */ jsx("code", { children: commandLine(config) })
1436
+ })
1437
+ })]
1438
+ }),
1439
+ test && /* @__PURE__ */ jsx("p", {
1440
+ role: "status",
1441
+ className: test.ok ? "mcp-test-ok" : "mcp-row-error",
1442
+ children: test.text
1443
+ }),
1444
+ /* @__PURE__ */ jsxs("div", {
1445
+ className: "mcp-footer-actions",
1446
+ children: [detail && /* @__PURE__ */ jsx(ctx.ui.Tooltip, {
1447
+ content: dirty ? t("mcp.testSaveFirst") : void 0,
1448
+ children: /* @__PURE__ */ jsx(ctx.ui.Button, {
1449
+ variant: "outline",
1450
+ icon: "play",
1451
+ "aria-disabled": dirty || testing || saving,
1452
+ className: "mcp-footer-button",
1453
+ onClick: () => {
1454
+ if (!dirty && !testing && !saving) runTest();
1455
+ },
1456
+ children: testing ? t("mcp.testing") : t("mcp.test")
1457
+ })
1458
+ }), /* @__PURE__ */ jsx(ctx.ui.Button, {
1459
+ type: "submit",
1460
+ variant: "primary",
1461
+ icon: "save",
1462
+ className: "mcp-footer-button",
1463
+ disabled: saving || !creating && !dirty,
1464
+ children: saving ? t("mcp.saving") : needsAck ? t("mcp.trustSave") : t("mcp.save")
1465
+ })]
1466
+ })
1467
+ ]
1468
+ })
1469
+ ]
1470
+ });
1471
+ }
1472
+ /** What a person agrees to by pressing 信任并保存, in full. */
1473
+ function riskFacts(ctx, config) {
1474
+ const t = ctx.i18n.t;
1475
+ return [
1476
+ t("mcp.riskDetail"),
1477
+ commandLine(config),
1478
+ config.cwd ? fill(t("mcp.riskCwd"), { cwd: config.cwd }) : "",
1479
+ config.env.length ? fill(t("mcp.riskEnv"), { names: config.env.map((entry) => entry.name).join(", ") }) : ""
1480
+ ].filter(Boolean).join("\n");
1481
+ }
1482
+ /**
1483
+ * One argument: its own input, so a space inside it needs no quoting. The
1484
+ * grip drags it to another place, Alt+↑/↓ moves it from the keyboard, Enter
1485
+ * opens a new argument after it and Backspace in an empty one removes it.
1486
+ */
1487
+ function ArgRowView({ ctx, arg, index, dragging, onDrag, onMove, onChange, onInsertAfter, onRemove }) {
1488
+ const t = ctx.i18n.t;
1489
+ const n = index + 1;
1490
+ const row = useRef(null);
1491
+ return /* @__PURE__ */ jsxs("li", {
1492
+ ref: row,
1493
+ className: "mcp-arg",
1494
+ "data-dragging": dragging === index ? "true" : void 0,
1495
+ onDragOver: (event) => {
1496
+ if (dragging === null) return;
1497
+ event.preventDefault();
1498
+ if (dragging !== index) {
1499
+ onMove(dragging, index);
1500
+ onDrag(index);
1501
+ }
1502
+ },
1503
+ onDrop: (event) => event.preventDefault(),
1504
+ children: [
1505
+ /* @__PURE__ */ jsx(ctx.ui.Button, {
1506
+ variant: "ghost",
1507
+ size: "sm",
1508
+ icon: "grip",
1509
+ className: "mcp-icon mcp-grip",
1510
+ draggable: true,
1511
+ tabIndex: -1,
1512
+ "aria-label": fill(t("mcp.argMove"), { n }),
1513
+ onDragStart: (event) => {
1514
+ event.dataTransfer.effectAllowed = "move";
1515
+ event.dataTransfer.setData("text/plain", arg.value);
1516
+ if (row.current) event.dataTransfer.setDragImage(row.current, 12, 16);
1517
+ onDrag(index);
1518
+ },
1519
+ onDragEnd: () => onDrag(null)
1520
+ }),
1521
+ /* @__PURE__ */ jsx(ctx.ui.Input, {
1522
+ "aria-label": fill(t("mcp.arg"), { n }),
1523
+ "data-arg-key": arg.key,
1524
+ className: "mcp-mono",
1525
+ spellCheck: false,
1526
+ autoComplete: "off",
1527
+ value: arg.value,
1528
+ onChange: (event) => onChange(event.currentTarget.value),
1529
+ onKeyDown: (event) => {
1530
+ if (event.nativeEvent.isComposing) return;
1531
+ if (event.key === "Enter") {
1532
+ event.preventDefault();
1533
+ onInsertAfter();
1534
+ } else if (event.key === "Backspace" && arg.value === "") {
1535
+ event.preventDefault();
1536
+ onRemove(true);
1537
+ } else if (event.altKey && (event.key === "ArrowUp" || event.key === "ArrowDown")) {
1538
+ event.preventDefault();
1539
+ onMove(index, event.key === "ArrowUp" ? index - 1 : index + 1);
1540
+ const input = event.currentTarget;
1541
+ requestAnimationFrame(() => input.focus());
1542
+ }
1543
+ }
1544
+ }),
1545
+ /* @__PURE__ */ jsx(ctx.ui.Button, {
1546
+ variant: "ghost",
1547
+ size: "sm",
1548
+ icon: "trash",
1549
+ className: "mcp-icon mcp-hover-action",
1550
+ "aria-label": fill(t("mcp.argRemove"), { n }),
1551
+ onClick: () => onRemove(false)
1552
+ })
1553
+ ]
1554
+ });
1555
+ }
1556
+ //#endregion
1557
+ //#region src/ui/settings.tsx
1558
+ function settingsFor(ctx) {
1559
+ return function McpSettings({ onLeaveGuard }) {
1560
+ const t = ctx.i18n.t;
1561
+ const host = useSyncExternalStore(ctx.host.subscribe, ctx.host.get);
1562
+ const agents = useAgents(ctx);
1563
+ const [servers, setServers] = useState(null);
1564
+ const [loadFailed, setLoadFailed] = useState(false);
1565
+ const [listAttempt, setListAttempt] = useState(0);
1566
+ const [detailFailed, setDetailFailed] = useState(false);
1567
+ const fail = useFailureToast(ctx);
1568
+ const [creating, setCreating] = useState(false);
1569
+ const [openId, setOpenId] = useState(null);
1570
+ const [detail, setDetail] = useState(null);
1571
+ const [notice, setNotice] = useState(null);
1572
+ const [openStatusReason, setOpenStatusReason] = useState(null);
1573
+ const [tab, setTab] = useState("connection");
1574
+ const [leaving, setLeaving] = useState(null);
1575
+ const guard = useRef(null);
1576
+ const headingId = useId();
1577
+ const activeActions = useRef(/* @__PURE__ */ new Set());
1578
+ const [pendingActions, setPendingActions] = useState(/* @__PURE__ */ new Set());
1579
+ const detailReads = useRef(/* @__PURE__ */ new Map());
1580
+ const openRef = useRef(null);
1581
+ openRef.current = openId;
1582
+ const loadDetail = useCallback(async (id) => {
1583
+ if (ctx.host.get().connection !== "online") return;
1584
+ const running = detailReads.current.get(id);
1585
+ if (running) {
1586
+ running.again = true;
1587
+ return;
1588
+ }
1589
+ const request = { again: false };
1590
+ detailReads.current.set(id, request);
1591
+ if (openRef.current === id) setDetailFailed(false);
1592
+ try {
1593
+ do {
1594
+ request.again = false;
1595
+ const next = await ctx.invoke(METHOD.getServer, { id });
1596
+ if (ctx.signal.aborted || openRef.current !== id) return;
1597
+ if (!request.again) setDetail(next);
1598
+ } while (request.again);
1599
+ } catch (failure) {
1600
+ if (!ctx.signal.aborted && openRef.current === id) {
1601
+ setDetailFailed(failureText(ctx, failure) !== null);
1602
+ fail(failure);
1603
+ }
1604
+ } finally {
1605
+ detailReads.current.delete(id);
1606
+ }
1607
+ }, [fail]);
1608
+ useEffect(() => {
1609
+ let live = true;
1610
+ setLoadFailed(false);
1611
+ if (host.connection !== "online") return;
1612
+ ctx.invoke(METHOD.listServers, {}).then(({ servers: next }) => {
1613
+ if (live && !ctx.signal.aborted) {
1614
+ setServers(next);
1615
+ setLoadFailed(false);
1616
+ const id = openRef.current;
1617
+ if (id && next.some((one) => one.id === id)) loadDetail(id);
1618
+ }
1619
+ }, (failure) => {
1620
+ if (live && !ctx.signal.aborted) {
1621
+ setLoadFailed(failureText(ctx, failure) !== null);
1622
+ fail(failure);
1623
+ }
1624
+ });
1625
+ return () => {
1626
+ live = false;
1627
+ };
1628
+ }, [
1629
+ host.connection,
1630
+ fail,
1631
+ listAttempt,
1632
+ loadDetail
1633
+ ]);
1634
+ useEffect(() => ctx.on(FRAME.serversChanged, ({ payload }) => {
1635
+ const next = payload?.servers;
1636
+ if (!next) return;
1637
+ setServers(next);
1638
+ const id = openRef.current;
1639
+ if (id && next.some((one) => one.id === id)) loadDetail(id);
1640
+ }), [loadDetail]);
1641
+ /** Asks before leaving an editor that holds unsaved changes. */
1642
+ const confirmLeave = useCallback(() => new Promise((resolve) => {
1643
+ if (!guard.current || guard.current()) {
1644
+ resolve(true);
1645
+ return;
1646
+ }
1647
+ setLeaving(() => (leave) => {
1648
+ setLeaving(null);
1649
+ resolve(leave);
1650
+ });
1651
+ }), []);
1652
+ useEffect(() => {
1653
+ onLeaveGuard?.(confirmLeave);
1654
+ return () => onLeaveGuard?.(null);
1655
+ }, [onLeaveGuard, confirmLeave]);
1656
+ const replaceRow = (next) => setServers((current) => current?.map((one) => one.id === next.id ? next : one) ?? current);
1657
+ async function rowAction(id, call) {
1658
+ if (activeActions.current.has(id)) return;
1659
+ activeActions.current.add(id);
1660
+ setPendingActions(new Set(activeActions.current));
1661
+ try {
1662
+ replaceRow(await call());
1663
+ } catch (failure) {
1664
+ if (!ctx.signal.aborted) fail(failure);
1665
+ } finally {
1666
+ activeActions.current.delete(id);
1667
+ if (!ctx.signal.aborted) setPendingActions(new Set(activeActions.current));
1668
+ }
1669
+ }
1670
+ async function setEnabled(server, enabled) {
1671
+ await rowAction(server.id, () => ctx.invoke(METHOD.setEnabled, {
1672
+ id: server.id,
1673
+ enabled
1674
+ }));
1675
+ }
1676
+ function show(id) {
1677
+ setNotice(null);
1678
+ setDetail(null);
1679
+ setDetailFailed(false);
1680
+ setOpenId(id);
1681
+ openRef.current = id;
1682
+ loadDetail(id);
1683
+ }
1684
+ /** Moves the detail column to `id`, asking first when the form holds
1685
+ * unsaved changes. */
1686
+ async function open(id) {
1687
+ if (id === openRef.current) return;
1688
+ if (!await confirmLeave()) return;
1689
+ guard.current = null;
1690
+ show(id);
1691
+ }
1692
+ useEffect(() => {
1693
+ if (!servers) return;
1694
+ if (openRef.current && servers.some((one) => one.id === openRef.current)) return;
1695
+ const first = servers[0];
1696
+ if (first) show(first.id);
1697
+ else {
1698
+ setOpenId(null);
1699
+ openRef.current = null;
1700
+ setDetail(null);
1701
+ }
1702
+ }, [servers]);
1703
+ const registerGuard = useCallback((next) => {
1704
+ guard.current = next;
1705
+ }, []);
1706
+ function saved(next, message) {
1707
+ setCreating(false);
1708
+ setNotice(message ?? null);
1709
+ const { config: _config, acknowledged: _ack, catalog: _catalog, oauth: _oauth, ...row } = next;
1710
+ setServers((current) => current?.some((one) => one.id === row.id) ? current.map((one) => one.id === row.id ? row : one) : [...current ?? [], row]);
1711
+ setOpenId(next.id);
1712
+ openRef.current = next.id;
1713
+ setDetail(next);
1714
+ setTab("connection");
1715
+ }
1716
+ function removed(next) {
1717
+ guard.current = null;
1718
+ openRef.current = null;
1719
+ setOpenId(null);
1720
+ setDetail(null);
1721
+ setServers(next);
1722
+ }
1723
+ const [deleting, setDeleting] = useState(null);
1724
+ const [removing, setRemoving] = useState(false);
1725
+ const removingRef = useRef(false);
1726
+ async function remove() {
1727
+ if (!deleting || removingRef.current) return;
1728
+ removingRef.current = true;
1729
+ setRemoving(true);
1730
+ try {
1731
+ const { servers: next } = await ctx.invoke(METHOD.removeServer, { id: deleting.id });
1732
+ if (ctx.signal.aborted) return;
1733
+ setDeleting(null);
1734
+ if (deleting.id === openRef.current) removed(next);
1735
+ else setServers(next);
1736
+ } catch (failure) {
1737
+ if (!ctx.signal.aborted) fail(failure);
1738
+ } finally {
1739
+ removingRef.current = false;
1740
+ if (!ctx.signal.aborted) setRemoving(false);
1741
+ }
1742
+ }
1743
+ const shown = servers?.find((one) => one.id === openId);
1744
+ const users = shown ? agentNames(agents, shown.agentIds) : [];
1745
+ const offered = detail?.catalog ? detail.catalog.tools.length + detail.catalog.resources.length + detail.catalog.prompts.length : 0;
1746
+ const tone = shown ? stateTone(shown.status.state) : "off";
1747
+ const statusReason = shown && tone === "failed" ? shown.status.reason?.trim() || stateLabel(ctx, shown.status.state) : void 0;
1748
+ const statusReasonKey = JSON.stringify([
1749
+ shown?.id,
1750
+ shown?.status.state,
1751
+ statusReason
1752
+ ]);
1753
+ useEffect(() => setOpenStatusReason(null), [statusReasonKey]);
1754
+ const statusBadge = shown && /* @__PURE__ */ jsxs(ctx.ui.Badge, {
1755
+ size: "sm",
1756
+ className: "mcp-status",
1757
+ tone: tone === "ok" ? "success" : tone === "failed" ? "destructive" : tone === "pending" ? "warning" : "neutral",
1758
+ children: [/* @__PURE__ */ jsx("span", {
1759
+ className: "mcp-dot",
1760
+ "data-state": tone,
1761
+ "aria-hidden": "true"
1762
+ }), stateLabel(ctx, shown.status.state)]
1763
+ });
1764
+ return /* @__PURE__ */ jsxs("div", {
1765
+ className: "mcp-settings",
1766
+ children: [
1767
+ /* @__PURE__ */ jsxs("div", {
1768
+ className: "mcp-shell",
1769
+ children: [/* @__PURE__ */ jsxs("section", {
1770
+ className: "mcp-servers",
1771
+ "aria-labelledby": `${headingId}-servers`,
1772
+ children: [
1773
+ /* @__PURE__ */ jsx("h2", {
1774
+ id: `${headingId}-servers`,
1775
+ className: "mcp-servers-title",
1776
+ children: t("mcp.servers")
1777
+ }),
1778
+ !servers && !loadFailed && /* @__PURE__ */ jsx("p", {
1779
+ role: "status",
1780
+ children: t("mcp.loading")
1781
+ }),
1782
+ loadFailed && /* @__PURE__ */ jsxs("div", {
1783
+ role: "alert",
1784
+ children: [/* @__PURE__ */ jsx("p", { children: t("mcp.listFailed") }), /* @__PURE__ */ jsx(ctx.ui.Button, {
1785
+ onClick: () => setListAttempt((value) => value + 1),
1786
+ children: t("mcp.retry")
1787
+ })]
1788
+ }),
1789
+ /* @__PURE__ */ jsx("ul", {
1790
+ className: "mcp-list",
1791
+ "aria-busy": !servers && !loadFailed,
1792
+ children: (servers ?? []).map((server) => /* @__PURE__ */ jsxs("li", {
1793
+ className: "mcp-row",
1794
+ "data-active": server.id === openId ? "true" : void 0,
1795
+ children: [/* @__PURE__ */ jsxs(ctx.ui.Button, {
1796
+ variant: "plain",
1797
+ className: "mcp-row-open",
1798
+ "aria-label": server.name,
1799
+ "aria-current": server.id === openId ? "true" : void 0,
1800
+ onClick: () => void open(server.id),
1801
+ children: [/* @__PURE__ */ jsx("strong", { children: server.name }), /* @__PURE__ */ jsxs("small", { children: [/* @__PURE__ */ jsx("span", {
1802
+ className: "mcp-dot",
1803
+ "data-state": stateTone(server.status.state),
1804
+ "aria-hidden": "true"
1805
+ }), stateLabel(ctx, server.status.state)] })]
1806
+ }), /* @__PURE__ */ jsxs("span", {
1807
+ className: "mcp-row-actions",
1808
+ children: [/* @__PURE__ */ jsx(ctx.ui.Tooltip, {
1809
+ content: server.enabled ? t("mcp.turnOff") : t("mcp.turnOn"),
1810
+ children: /* @__PURE__ */ jsx(ctx.ui.Button, {
1811
+ variant: "ghost",
1812
+ size: "sm",
1813
+ icon: "power",
1814
+ className: "mcp-power",
1815
+ loading: pendingActions.has(server.id),
1816
+ disabled: pendingActions.has(server.id),
1817
+ "aria-pressed": server.enabled,
1818
+ "aria-label": fill(t("mcp.enable"), { name: server.name }),
1819
+ onClick: () => void setEnabled(server, !server.enabled)
1820
+ })
1821
+ }), /* @__PURE__ */ jsx(ctx.ui.Tooltip, {
1822
+ content: t("mcp.delete"),
1823
+ children: /* @__PURE__ */ jsx(ctx.ui.Button, {
1824
+ variant: "ghost",
1825
+ size: "sm",
1826
+ icon: "trash",
1827
+ "aria-label": `${t("mcp.delete")} ${server.name}`,
1828
+ onClick: () => setDeleting(server)
1829
+ })
1830
+ })]
1831
+ })]
1832
+ }, server.id))
1833
+ }),
1834
+ /* @__PURE__ */ jsx("div", {
1835
+ className: "mcp-servers-foot",
1836
+ children: /* @__PURE__ */ jsx(ctx.ui.Button, {
1837
+ variant: "outline",
1838
+ icon: "plus",
1839
+ className: "mcp-add",
1840
+ onClick: () => setCreating(true),
1841
+ children: t("mcp.add")
1842
+ })
1843
+ })
1844
+ ]
1845
+ }), /* @__PURE__ */ jsx("section", {
1846
+ className: "mcp-detail-pane",
1847
+ "aria-labelledby": `${headingId}-detail`,
1848
+ children: shown ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("header", {
1849
+ className: "mcp-detail-header",
1850
+ children: [/* @__PURE__ */ jsxs("div", {
1851
+ className: "mcp-grow",
1852
+ children: [/* @__PURE__ */ jsx("h3", {
1853
+ id: `${headingId}-detail`,
1854
+ children: shown.name
1855
+ }), detail?.id === shown.id && detail.description && /* @__PURE__ */ jsx(ctx.ui.Tooltip, {
1856
+ content: detail.description,
1857
+ side: "bottom",
1858
+ children: /* @__PURE__ */ jsx("p", {
1859
+ className: "mcp-description",
1860
+ children: detail.description
1861
+ })
1862
+ })]
1863
+ }), /* @__PURE__ */ jsx("div", {
1864
+ className: "mcp-status-control",
1865
+ children: statusReason ? /* @__PURE__ */ jsx(ctx.ui.Tooltip, {
1866
+ content: statusReason,
1867
+ open: openStatusReason === statusReasonKey,
1868
+ onOpenChange: (open) => setOpenStatusReason(open ? statusReasonKey : null),
1869
+ closeOnClick: false,
1870
+ children: /* @__PURE__ */ jsx(ctx.ui.Button, {
1871
+ variant: "plain",
1872
+ type: "button",
1873
+ className: "mcp-status-trigger",
1874
+ "aria-label": `${stateLabel(ctx, shown.status.state)}: ${t("mcp.readStatusReason")}`,
1875
+ onClick: () => setOpenStatusReason(statusReasonKey),
1876
+ children: statusBadge
1877
+ })
1878
+ }, statusReasonKey) : statusBadge
1879
+ })]
1880
+ }), /* @__PURE__ */ jsxs(ctx.ui.Tabs, {
1881
+ value: tab,
1882
+ onValueChange: (next) => {
1883
+ if (next === tab) return;
1884
+ confirmLeave().then((leave) => {
1885
+ if (leave) setTab(next);
1886
+ });
1887
+ },
1888
+ children: [/* @__PURE__ */ jsxs(ctx.ui.TabsList, {
1889
+ "aria-label": shown.name,
1890
+ activateOnFocus: false,
1891
+ children: [
1892
+ /* @__PURE__ */ jsx(ctx.ui.TabsTrigger, {
1893
+ value: "connection",
1894
+ children: t("mcp.connection")
1895
+ }),
1896
+ /* @__PURE__ */ jsxs(ctx.ui.TabsTrigger, {
1897
+ value: "capabilities",
1898
+ children: [t("mcp.capabilities"), /* @__PURE__ */ jsx("span", {
1899
+ className: "mcp-tab-count",
1900
+ children: offered
1901
+ })]
1902
+ }),
1903
+ /* @__PURE__ */ jsxs(ctx.ui.TabsTrigger, {
1904
+ value: "agents",
1905
+ children: [t("mcp.agents"), /* @__PURE__ */ jsx("span", {
1906
+ className: "mcp-tab-count",
1907
+ children: users.length
1908
+ })]
1909
+ })
1910
+ ]
1911
+ }), /* @__PURE__ */ jsxs("div", {
1912
+ className: "mcp-detail-body",
1913
+ onClickCapture: () => setOpenStatusReason(null),
1914
+ children: [
1915
+ notice && /* @__PURE__ */ jsx(ctx.ui.Alert, {
1916
+ tone: "warning",
1917
+ role: "alert",
1918
+ className: "mcp-alert",
1919
+ children: notice
1920
+ }),
1921
+ !detail && !detailFailed && /* @__PURE__ */ jsx("p", {
1922
+ role: "status",
1923
+ className: "mcp-muted",
1924
+ children: t("mcp.loading")
1925
+ }),
1926
+ detailFailed && /* @__PURE__ */ jsxs("div", {
1927
+ role: "alert",
1928
+ children: [/* @__PURE__ */ jsx("p", { children: t("mcp.detailFailed") }), /* @__PURE__ */ jsx(ctx.ui.Button, {
1929
+ onClick: () => void loadDetail(shown.id),
1930
+ children: t("mcp.retry")
1931
+ })]
1932
+ }),
1933
+ detail && /* @__PURE__ */ jsxs(Fragment, { children: [
1934
+ /* @__PURE__ */ jsx(ctx.ui.TabsContent, {
1935
+ value: "agents",
1936
+ children: /* @__PURE__ */ jsx(Agents, {
1937
+ ctx,
1938
+ server: shown,
1939
+ agents
1940
+ })
1941
+ }),
1942
+ /* @__PURE__ */ jsx(ctx.ui.TabsContent, {
1943
+ value: "capabilities",
1944
+ children: /* @__PURE__ */ jsx(Capabilities, {
1945
+ ctx,
1946
+ detail
1947
+ }, detail.id)
1948
+ }),
1949
+ /* @__PURE__ */ jsx(ctx.ui.TabsContent, {
1950
+ value: "connection",
1951
+ children: /* @__PURE__ */ jsx(ServerDetailView, {
1952
+ ctx,
1953
+ detail,
1954
+ registerGuard,
1955
+ onSaved: (next, message) => {
1956
+ setDetail(next);
1957
+ setNotice(message ?? null);
1958
+ }
1959
+ }, detail.id)
1960
+ })
1961
+ ] })
1962
+ ]
1963
+ })]
1964
+ })] }) : /* @__PURE__ */ jsxs("div", {
1965
+ className: "mcp-detail-empty",
1966
+ children: [!servers && !loadFailed && /* @__PURE__ */ jsx("p", {
1967
+ role: "status",
1968
+ className: "mcp-muted",
1969
+ children: t("mcp.loading")
1970
+ }), servers && !servers.length && /* @__PURE__ */ jsx(ctx.ui.EmptyState, {
1971
+ title: t("mcp.emptyTitle"),
1972
+ description: t("mcp.emptyBody")
1973
+ })]
1974
+ })
1975
+ })]
1976
+ }),
1977
+ /* @__PURE__ */ jsx(ctx.ui.Dialog, {
1978
+ open: creating,
1979
+ onOpenChange: (next) => {
1980
+ if (!next) setCreating(false);
1981
+ },
1982
+ title: t("mcp.add"),
1983
+ closeLabel: t("mcp.cancel"),
1984
+ children: creating && /* @__PURE__ */ jsx(ServerEditor, {
1985
+ ctx,
1986
+ onSaved: saved
1987
+ })
1988
+ }),
1989
+ /* @__PURE__ */ jsxs(ctx.ui.AlertDialog, {
1990
+ open: deleting !== null,
1991
+ onOpenChange: (next) => {
1992
+ if (!next && !removing) setDeleting(null);
1993
+ },
1994
+ title: t("mcp.deleteTitle"),
1995
+ actions: /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(ctx.ui.Button, {
1996
+ variant: "ghost",
1997
+ onClick: () => setDeleting(null),
1998
+ children: t("mcp.cancel")
1999
+ }), /* @__PURE__ */ jsx(ctx.ui.Button, {
2000
+ variant: "destructive",
2001
+ disabled: removing,
2002
+ onClick: () => void remove(),
2003
+ children: t("mcp.deleteConfirm")
2004
+ })] }),
2005
+ children: [/* @__PURE__ */ jsx("p", { children: fill(t("mcp.deleteBody"), { name: deleting?.name ?? "" }) }), deleting && agentNames(agents, deleting.agentIds).length > 0 && /* @__PURE__ */ jsx("p", { children: fill(t("mcp.deleteAgents"), { names: agentNames(agents, deleting.agentIds).join(", ") }) })]
2006
+ }),
2007
+ /* @__PURE__ */ jsx(ctx.ui.AlertDialog, {
2008
+ open: leaving !== null,
2009
+ onOpenChange: (next) => {
2010
+ if (!next) leaving?.(false);
2011
+ },
2012
+ title: t("mcp.unsavedTitle"),
2013
+ actions: /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(ctx.ui.Button, {
2014
+ variant: "ghost",
2015
+ onClick: () => leaving?.(false),
2016
+ children: t("mcp.keepEditing")
2017
+ }), /* @__PURE__ */ jsx(ctx.ui.Button, {
2018
+ variant: "destructive",
2019
+ onClick: () => leaving?.(true),
2020
+ children: t("mcp.discard")
2021
+ })] }),
2022
+ children: /* @__PURE__ */ jsx("p", { children: t("mcp.unsavedBody") })
2023
+ })
2024
+ ]
2025
+ });
2026
+ };
2027
+ }
2028
+ function ServerDetailView({ ctx, detail, registerGuard, onSaved }) {
2029
+ const oauth = detail.transport === "http" && "auth" in detail.config && detail.config.auth === "oauth";
2030
+ return /* @__PURE__ */ jsx("div", {
2031
+ className: "mcp-detail",
2032
+ children: /* @__PURE__ */ jsx(ServerEditor, {
2033
+ ctx,
2034
+ detail,
2035
+ onSaved,
2036
+ registerGuard,
2037
+ children: oauth && /* @__PURE__ */ jsx(AuthorizationArea, {
2038
+ ctx,
2039
+ detail
2040
+ })
2041
+ })
2042
+ });
2043
+ }
2044
+ /**
2045
+ * Authorization of an OAuth server. The opening is reserved during the
2046
+ * click (`prepareLink`), so a browser treats its window as the person's own,
2047
+ * and the address is opened once the gateway answers; a blocked window or a
2048
+ * system browser that would not start leaves the address written out.
2049
+ */
2050
+ function AuthorizationArea({ ctx, detail }) {
2051
+ const t = ctx.i18n.t;
2052
+ const [waiting, setWaiting] = useState(null);
2053
+ const [link, setLink] = useState(null);
2054
+ const fail = useFailureToast(ctx);
2055
+ const [copied, setCopied] = useState(false);
2056
+ const reserved = useRef(null);
2057
+ const actionRef = useRef(null);
2058
+ const [action, setAction] = useState(null);
2059
+ const statusKey = `${detail.status.state}\n${detail.status.reason ?? ""}\n${detail.oauth?.authorized ?? false}`;
2060
+ useEffect(() => {
2061
+ if (waiting && waiting.status !== statusKey) {
2062
+ setWaiting(null);
2063
+ setLink(null);
2064
+ }
2065
+ }, [statusKey]);
2066
+ useEffect(() => {
2067
+ setCopied(false);
2068
+ }, [link?.url]);
2069
+ useEffect(() => {
2070
+ if (!copied) return;
2071
+ const timer = setTimeout(() => setCopied(false), 2e3);
2072
+ return () => clearTimeout(timer);
2073
+ }, [copied]);
2074
+ async function copyLink() {
2075
+ if (!link) return;
2076
+ try {
2077
+ await navigator.clipboard.writeText(link.url);
2078
+ setCopied(true);
2079
+ } catch {
2080
+ fail(new Error(t("mcp.copyLinkFailed")));
2081
+ }
2082
+ }
2083
+ async function authorize() {
2084
+ if (actionRef.current || waiting) return;
2085
+ actionRef.current = "authorize";
2086
+ setAction("authorize");
2087
+ setLink(null);
2088
+ const pending = ctx.navigation.prepareLink();
2089
+ reserved.current = pending;
2090
+ try {
2091
+ const { url } = await ctx.invoke(METHOD.authorize, { id: detail.id });
2092
+ if (ctx.signal.aborted) return;
2093
+ const result = await pending.open(url);
2094
+ if (ctx.signal.aborted) return;
2095
+ setLink({
2096
+ url,
2097
+ problem: result === "blocked" || result === "failed" ? result : null
2098
+ });
2099
+ if (result === "failed") fail(new Error(t("mcp.authorizeFailedTitle")));
2100
+ setWaiting({ status: statusKey });
2101
+ } catch (failure) {
2102
+ pending.cancel();
2103
+ reserved.current = null;
2104
+ if (!ctx.signal.aborted) fail(failure);
2105
+ } finally {
2106
+ actionRef.current = null;
2107
+ if (!ctx.signal.aborted) setAction(null);
2108
+ }
2109
+ }
2110
+ async function cancel() {
2111
+ if (actionRef.current) return;
2112
+ actionRef.current = "cancel";
2113
+ setAction("cancel");
2114
+ reserved.current?.cancel();
2115
+ reserved.current = null;
2116
+ setWaiting(null);
2117
+ setLink(null);
2118
+ try {
2119
+ await ctx.invoke(METHOD.cancelAuthorize, { id: detail.id });
2120
+ } catch (failure) {
2121
+ if (!ctx.signal.aborted) fail(failure);
2122
+ } finally {
2123
+ actionRef.current = null;
2124
+ if (!ctx.signal.aborted) setAction(null);
2125
+ }
2126
+ }
2127
+ async function signOut() {
2128
+ if (actionRef.current) return;
2129
+ actionRef.current = "signOut";
2130
+ setAction("signOut");
2131
+ try {
2132
+ await ctx.invoke(METHOD.signOut, { id: detail.id });
2133
+ } catch (failure) {
2134
+ if (!ctx.signal.aborted) fail(failure);
2135
+ } finally {
2136
+ actionRef.current = null;
2137
+ if (!ctx.signal.aborted) setAction(null);
2138
+ }
2139
+ }
2140
+ const authorized = detail.oauth?.authorized === true;
2141
+ const needsAgain = detail.status.state === "needs-auth";
2142
+ let state = t("mcp.oauth.none");
2143
+ if (authorized && !needsAgain) state = detail.oauth?.expiresAt ? fill(t("mcp.oauth.expires"), { time: new Date(detail.oauth.expiresAt).toLocaleString() }) : t("mcp.oauth.authorized");
2144
+ else if (needsAgain && detail.status.reason) state = fill(t("mcp.oauth.reauth"), { reason: detail.status.reason });
2145
+ return /* @__PURE__ */ jsxs("section", {
2146
+ className: "mcp-oauth",
2147
+ "aria-label": t("mcp.oauth"),
2148
+ children: [/* @__PURE__ */ jsxs("div", {
2149
+ className: "mcp-oauth-header",
2150
+ children: [
2151
+ /* @__PURE__ */ jsx("span", {
2152
+ className: "mcp-oauth-label",
2153
+ children: t("mcp.oauth")
2154
+ }),
2155
+ /* @__PURE__ */ jsxs("span", {
2156
+ className: `mcp-oauth-status${authorized && !needsAgain ? " mcp-oauth-authorized" : ""}`,
2157
+ role: "status",
2158
+ children: [/* @__PURE__ */ jsx("span", {
2159
+ className: "mcp-oauth-dot",
2160
+ "aria-hidden": "true"
2161
+ }), waiting ? t("mcp.authorizePending") : state]
2162
+ }),
2163
+ /* @__PURE__ */ jsx("div", {
2164
+ className: "mcp-oauth-actions",
2165
+ children: waiting ? /* @__PURE__ */ jsx(ctx.ui.Button, {
2166
+ disabled: action !== null,
2167
+ loading: action === "cancel",
2168
+ onClick: () => void cancel(),
2169
+ children: t("mcp.authorizeCancel")
2170
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [(!authorized || needsAgain) && /* @__PURE__ */ jsx(ctx.ui.Button, {
2171
+ disabled: action !== null,
2172
+ loading: action === "authorize",
2173
+ onClick: () => void authorize(),
2174
+ children: t("mcp.authorize")
2175
+ }), authorized && /* @__PURE__ */ jsx(ctx.ui.Button, {
2176
+ disabled: action !== null,
2177
+ loading: action === "signOut",
2178
+ onClick: () => void signOut(),
2179
+ children: t("mcp.signOut")
2180
+ })] })
2181
+ })
2182
+ ]
2183
+ }), waiting && link && /* @__PURE__ */ jsxs("div", {
2184
+ className: `mcp-oauth-flow${link.problem ? " mcp-oauth-warning" : ""}`,
2185
+ children: [
2186
+ /* @__PURE__ */ jsx("strong", { children: t(link.problem ? "mcp.authorizeFailedTitle" : "mcp.authorizeWaiting") }),
2187
+ /* @__PURE__ */ jsx("p", {
2188
+ className: "mcp-oauth-hint",
2189
+ children: t(link.problem === "failed" ? "mcp.authorizeFailed" : link.problem === "blocked" ? "mcp.authorizeBlocked" : "mcp.authorizeHint")
2190
+ }),
2191
+ /* @__PURE__ */ jsxs("div", {
2192
+ className: "mcp-oauth-actions",
2193
+ children: [/* @__PURE__ */ jsxs(ctx.ui.ExternalLink, {
2194
+ href: link.url,
2195
+ className: "ui-button surface-control mcp-oauth-external",
2196
+ "data-variant": "primary",
2197
+ "data-size": "sm",
2198
+ "data-slot": "button",
2199
+ children: [t("mcp.authorizeOpen"), /* @__PURE__ */ jsx(ctx.ui.Icon, {
2200
+ name: "arrow-right",
2201
+ className: "-rotate-45"
2202
+ })]
2203
+ }), /* @__PURE__ */ jsx(ctx.ui.Button, {
2204
+ variant: "plain",
2205
+ onClick: () => void copyLink(),
2206
+ children: t(copied ? "mcp.copied" : "mcp.copyLink")
2207
+ })]
2208
+ }),
2209
+ link.problem && /* @__PURE__ */ jsxs(ctx.ui.Disclosure, {
2210
+ className: "mcp-oauth-address",
2211
+ open: true,
2212
+ children: [/* @__PURE__ */ jsx(ctx.ui.DisclosureSummary, { children: t("mcp.showLink") }), /* @__PURE__ */ jsx(ctx.ui.ExternalLink, {
2213
+ href: link.url,
2214
+ className: "mcp-oauth-url",
2215
+ children: link.url
2216
+ })]
2217
+ }),
2218
+ /* @__PURE__ */ jsxs("div", {
2219
+ className: "mcp-oauth-footer",
2220
+ role: "status",
2221
+ children: [/* @__PURE__ */ jsx("span", {
2222
+ className: "mcp-oauth-dot",
2223
+ "aria-hidden": "true"
2224
+ }), t("mcp.authorizePending")]
2225
+ })
2226
+ ]
2227
+ })]
2228
+ });
2229
+ }
2230
+ var KIND_ICON = {
2231
+ tools: "wrench",
2232
+ resources: "file-text",
2233
+ prompts: "message-square-text"
2234
+ };
2235
+ /**
2236
+ * What the server offers, narrowed by one filter text and by kind. The kinds
2237
+ * are pill chips under the filter rather than a second row of tabs; with all
2238
+ * of them shown the list keeps one group per kind, and every row carries its
2239
+ * kind's icon so a mixed search result still reads by kind.
2240
+ */
2241
+ function Capabilities({ ctx, detail }) {
2242
+ const t = ctx.i18n.t;
2243
+ const [filter, setFilter] = useState("");
2244
+ const [kind, setKind] = useState("all");
2245
+ const [open, setOpen] = useState(null);
2246
+ const catalog = detail.catalog;
2247
+ if (!catalog) return /* @__PURE__ */ jsx(ctx.ui.EmptyState, { title: t("mcp.noCapabilities") });
2248
+ const query = filter.trim().toLocaleLowerCase();
2249
+ const matches = (...texts) => texts.some((text) => text?.toLocaleLowerCase().includes(query));
2250
+ const all = [
2251
+ {
2252
+ key: "tools",
2253
+ label: t("mcp.kind.tools"),
2254
+ total: catalog.tools.length,
2255
+ rows: catalog.tools.map((tool) => ({
2256
+ key: tool.name,
2257
+ name: tool.name,
2258
+ detail: tool.mappedName,
2259
+ description: tool.description,
2260
+ parameters: tool.parameters,
2261
+ refused: tool.refused
2262
+ }))
2263
+ },
2264
+ {
2265
+ key: "resources",
2266
+ label: t("mcp.kind.resources"),
2267
+ total: catalog.resources.length,
2268
+ rows: catalog.resources.map((resource) => ({
2269
+ key: resource.uri ?? resource.name,
2270
+ name: resource.name,
2271
+ detail: resource.uri,
2272
+ description: resource.description,
2273
+ mimeType: resource.mimeType,
2274
+ refused: resource.refused
2275
+ }))
2276
+ },
2277
+ {
2278
+ key: "prompts",
2279
+ label: t("mcp.kind.prompts"),
2280
+ total: catalog.prompts.length,
2281
+ rows: catalog.prompts.map((prompt) => ({
2282
+ key: prompt.name,
2283
+ name: prompt.name,
2284
+ description: prompt.description,
2285
+ parameters: prompt.parameters ?? [],
2286
+ refused: prompt.refused
2287
+ }))
2288
+ }
2289
+ ];
2290
+ const groups = all.filter((group) => kind === "all" || group.key === kind).map((group) => ({
2291
+ ...group,
2292
+ rows: group.rows.filter((row) => matches(row.name, row.detail, row.description))
2293
+ })).filter((group) => group.rows.length);
2294
+ const total = all.reduce((sum, group) => sum + group.total, 0);
2295
+ return /* @__PURE__ */ jsxs("section", {
2296
+ className: "mcp-capabilities",
2297
+ "aria-label": t("mcp.capabilities"),
2298
+ children: [
2299
+ /* @__PURE__ */ jsx(ctx.ui.Input, {
2300
+ type: "search",
2301
+ className: "mcp-filter",
2302
+ "aria-label": t("mcp.filterCapabilities"),
2303
+ placeholder: t("mcp.filterCapabilities"),
2304
+ value: filter,
2305
+ onChange: (event) => setFilter(event.target.value)
2306
+ }),
2307
+ /* @__PURE__ */ jsx(ctx.ui.FilterChips, {
2308
+ label: t("mcp.kinds"),
2309
+ value: kind,
2310
+ onSelect: (next) => setKind(next),
2311
+ options: [{
2312
+ value: "all",
2313
+ label: t("mcp.kind.all"),
2314
+ count: total
2315
+ }, ...all.map((group) => ({
2316
+ value: group.key,
2317
+ label: group.label,
2318
+ icon: KIND_ICON[group.key],
2319
+ count: group.total
2320
+ }))]
2321
+ }),
2322
+ groups.map((group) => /* @__PURE__ */ jsxs("section", {
2323
+ className: "mcp-cap-group",
2324
+ "aria-label": group.label,
2325
+ children: [kind === "all" && /* @__PURE__ */ jsxs("h4", { children: [
2326
+ /* @__PURE__ */ jsx(ctx.ui.Icon, {
2327
+ name: KIND_ICON[group.key],
2328
+ className: "mcp-cap-group-icon"
2329
+ }),
2330
+ group.label,
2331
+ " ",
2332
+ group.rows.length
2333
+ ] }), /* @__PURE__ */ jsx("ul", { children: group.rows.map((row) => {
2334
+ const current = open?.kind === group.key && open.key === row.key;
2335
+ return /* @__PURE__ */ jsx("li", {
2336
+ className: "mcp-cap-row",
2337
+ "data-selected": current ? "true" : void 0,
2338
+ children: /* @__PURE__ */ jsx(ctx.ui.Popover, {
2339
+ label: row.name,
2340
+ width: 360,
2341
+ className: "mcp-cap-popover",
2342
+ open: current,
2343
+ onOpenChange: (next) => setOpen(next ? {
2344
+ kind: group.key,
2345
+ key: row.key
2346
+ } : null),
2347
+ trigger: /* @__PURE__ */ jsxs(ctx.ui.Button, {
2348
+ variant: "plain",
2349
+ className: "mcp-cap-open",
2350
+ children: [
2351
+ /* @__PURE__ */ jsx("span", {
2352
+ className: "mcp-cap-kind",
2353
+ children: /* @__PURE__ */ jsx(ctx.ui.Icon, { name: KIND_ICON[group.key] })
2354
+ }),
2355
+ /* @__PURE__ */ jsxs("span", {
2356
+ className: "mcp-cap-name",
2357
+ children: [/* @__PURE__ */ jsx("strong", { children: row.name }), row.detail && /* @__PURE__ */ jsx("small", { children: row.detail })]
2358
+ }),
2359
+ row.refused && /* @__PURE__ */ jsx(ctx.ui.Badge, {
2360
+ size: "sm",
2361
+ shape: "rounded",
2362
+ tone: "destructive",
2363
+ children: fill(t("mcp.refused"), { reason: row.refused })
2364
+ })
2365
+ ]
2366
+ }),
2367
+ children: /* @__PURE__ */ jsx(CapabilityDetails, {
2368
+ ctx,
2369
+ kind: group.key,
2370
+ row
2371
+ })
2372
+ })
2373
+ }, row.key);
2374
+ }) })]
2375
+ }, group.key)),
2376
+ !groups.length && /* @__PURE__ */ jsx(ctx.ui.EmptyState, { title: t("mcp.noMatches") })
2377
+ ]
2378
+ });
2379
+ }
2380
+ /**
2381
+ * What one capability is, as its server described it: the description, then
2382
+ * what it asks for — a tool's inputs from its schema, a prompt's arguments —
2383
+ * or, for a resource, what kind of content it holds. Read from what the last
2384
+ * listing returned; nothing here asks the server anything.
2385
+ */
2386
+ function CapabilityDetails({ ctx, kind, row }) {
2387
+ const t = ctx.i18n.t;
2388
+ return /* @__PURE__ */ jsxs("div", {
2389
+ className: "mcp-cap-details",
2390
+ children: [
2391
+ row.refused && /* @__PURE__ */ jsx(ctx.ui.Alert, {
2392
+ tone: "destructive",
2393
+ children: fill(t("mcp.refused"), { reason: row.refused })
2394
+ }),
2395
+ row.description ? /* @__PURE__ */ jsx("p", {
2396
+ className: "mcp-cap-description",
2397
+ children: row.description
2398
+ }) : /* @__PURE__ */ jsx("p", {
2399
+ className: "mcp-muted",
2400
+ children: t("mcp.noDescription")
2401
+ }),
2402
+ kind === "resources" ? row.mimeType && /* @__PURE__ */ jsxs("dl", {
2403
+ className: "mcp-cap-facts",
2404
+ children: [/* @__PURE__ */ jsx("dt", { children: t("mcp.mimeType") }), /* @__PURE__ */ jsx("dd", { children: /* @__PURE__ */ jsx("code", { children: row.mimeType }) })]
2405
+ }) : /* @__PURE__ */ jsxs("section", {
2406
+ className: "mcp-cap-params",
2407
+ "aria-label": t("mcp.parameters"),
2408
+ children: [/* @__PURE__ */ jsx("h4", { children: t("mcp.parameters") }), row.parameters?.length ? /* @__PURE__ */ jsx("ul", { children: row.parameters.map((parameter) => /* @__PURE__ */ jsxs("li", {
2409
+ className: "mcp-cap-param",
2410
+ children: [/* @__PURE__ */ jsxs("span", {
2411
+ className: "mcp-cap-param-head",
2412
+ children: [
2413
+ /* @__PURE__ */ jsx("code", { children: parameter.name }),
2414
+ parameter.type && /* @__PURE__ */ jsx(ctx.ui.Badge, {
2415
+ size: "sm",
2416
+ shape: "rounded",
2417
+ children: parameter.type
2418
+ }),
2419
+ parameter.required && /* @__PURE__ */ jsx(ctx.ui.Badge, {
2420
+ size: "sm",
2421
+ shape: "rounded",
2422
+ tone: "warning",
2423
+ children: t("mcp.required")
2424
+ })
2425
+ ]
2426
+ }), parameter.description && /* @__PURE__ */ jsx("small", { children: parameter.description })]
2427
+ }, parameter.name)) }) : /* @__PURE__ */ jsx("p", {
2428
+ className: "mcp-muted",
2429
+ children: t("mcp.noParameters")
2430
+ })]
2431
+ })
2432
+ ]
2433
+ });
2434
+ }
2435
+ /**
2436
+ * Which agents select this server, one switch per agent. A switch is a save:
2437
+ * the agent's own selection is read, this server added or taken out, and the
2438
+ * whole set written back through `setAgentServers`, whose `serversChanged`
2439
+ * brings `server.agentIds` up to date. One write at a time, because each is
2440
+ * computed from the selection the previous one left.
2441
+ */
2442
+ function Agents({ ctx, server, agents }) {
2443
+ const t = ctx.i18n.t;
2444
+ const [pending, setPending] = useState(null);
2445
+ const fail = useFailureToast(ctx);
2446
+ const pendingRef = useRef(false);
2447
+ async function toggle(agentId, on) {
2448
+ if (pendingRef.current) return;
2449
+ pendingRef.current = true;
2450
+ setPending({
2451
+ id: agentId,
2452
+ on
2453
+ });
2454
+ try {
2455
+ const { serverIds, revision, contentHash } = await ctx.invoke(METHOD.agentServers, { agentId });
2456
+ const next = on ? [...serverIds.filter((id) => id !== server.id), server.id] : serverIds.filter((id) => id !== server.id);
2457
+ await ctx.invoke(METHOD.setAgentServers, {
2458
+ agentId,
2459
+ serverIds: next,
2460
+ expectedRevision: revision,
2461
+ expectedContentHash: contentHash
2462
+ });
2463
+ } catch (failure) {
2464
+ if (!ctx.signal.aborted) fail(failure);
2465
+ } finally {
2466
+ pendingRef.current = false;
2467
+ if (!ctx.signal.aborted) setPending(null);
2468
+ }
2469
+ }
2470
+ if (!agents) return /* @__PURE__ */ jsx("p", {
2471
+ role: "status",
2472
+ className: "mcp-muted",
2473
+ children: t("mcp.loading")
2474
+ });
2475
+ if (!agents.length) return /* @__PURE__ */ jsx(ctx.ui.EmptyState, { title: t("mcp.noAgents") });
2476
+ return /* @__PURE__ */ jsx("ul", {
2477
+ className: "mcp-agents",
2478
+ children: agents.map((agent) => {
2479
+ const on = pending?.id === agent.agentId ? pending.on : server.agentIds.includes(agent.agentId);
2480
+ return /* @__PURE__ */ jsxs("li", {
2481
+ className: "mcp-agent-row",
2482
+ children: [
2483
+ /* @__PURE__ */ jsxs("span", {
2484
+ className: "mcp-agent-name",
2485
+ children: [/* @__PURE__ */ jsx("strong", { children: agent.name }), agent.description && /* @__PURE__ */ jsx("small", { children: agent.description })]
2486
+ }),
2487
+ agent.tools && /* @__PURE__ */ jsx(ctx.ui.Tooltip, {
2488
+ content: t("mcp.tabWhitelist"),
2489
+ children: /* @__PURE__ */ jsx(ctx.ui.Badge, {
2490
+ size: "sm",
2491
+ tone: "warning",
2492
+ children: t("mcp.agentWhitelist")
2493
+ })
2494
+ }),
2495
+ /* @__PURE__ */ jsx(ctx.ui.Switch, {
2496
+ "aria-label": fill(t("mcp.agentUses"), { name: agent.name }),
2497
+ checked: on,
2498
+ disabled: pending !== null,
2499
+ onCheckedChange: (next) => void toggle(agent.agentId, next)
2500
+ })
2501
+ ]
2502
+ }, agent.agentId);
2503
+ })
2504
+ });
2505
+ }
2506
+ //#endregion
2507
+ //#region src/ui/index.tsx
2508
+ var runtimeVersion = 5;
2509
+ var STYLES = `
2510
+ .mcp-settings { container: mcp / inline-size; display: flex; flex: 1; min-width: 0; min-height: 0; font-size: .875rem; }
2511
+ .mcp-shell { display: grid; flex: 1; min-width: 0; min-height: 0; grid-template-columns: 15rem minmax(0, 1fr); }
2512
+ .mcp-detail, .mcp-form, .mcp-tab { display: flex; min-width: 0; flex-direction: column; gap: 1rem; font-size: .875rem; }
2513
+ .mcp-actions { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: .5rem; }
2514
+ .mcp-servers { display: flex; flex-direction: column; min-height: 0; padding: 0 .75rem .75rem; border-inline-end: 1px solid var(--border); }
2515
+ .mcp-servers-title { display: flex; align-items: center; height: 4rem; flex: none; margin: 0; padding-inline: .625rem; font-size: 1.125rem; font-weight: 600; }
2516
+ .mcp-list { display: flex; flex-direction: column; gap: 2px; flex: 1; min-height: 0; margin: 0; padding: 0; overflow-y: auto; list-style: none; }
2517
+ .mcp-servers-foot { flex: none; padding-top: .75rem; }
2518
+ .mcp-servers-foot .mcp-add { width: 100%; }
2519
+ .mcp-row { --row-fill: var(--card); position: relative; min-width: 0; border-radius: var(--radius-control); background: var(--row-fill); transition: background-color 150ms ease; }
2520
+ .mcp-row:hover { --row-fill: var(--muted); }
2521
+ .mcp-row[data-active] { --row-fill: color-mix(in srgb, var(--primary) 10%, var(--card)); }
2522
+ .mcp-row:has(> .mcp-row-open:focus-visible) { outline: var(--focus-ring-width) solid var(--focus-ring-color); }
2523
+ .mcp-settings .mcp-row-open { display: flex; width: 100%; flex-direction: column; align-items: flex-start; min-width: 0; padding: .625rem; border-radius: var(--radius-control); text-align: start; cursor: pointer; outline: none; }
2524
+ .mcp-row-open strong { max-width: 100%; overflow: hidden; font-weight: 500; text-overflow: ellipsis; white-space: nowrap; }
2525
+ .mcp-row[data-active] .mcp-row-open strong { color: var(--primary); }
2526
+ .mcp-row-open small { display: flex; align-items: center; max-width: 100%; margin-top: .125rem; overflow: hidden; font-size: .75rem; color: var(--muted-foreground); white-space: nowrap; }
2527
+ .mcp-power[aria-pressed=true] { color: var(--success); }
2528
+ .mcp-row-actions { position: absolute; inset-block: 0; inset-inline-end: 0; display: flex; align-items: center; padding-inline: 1.25rem .375rem; border-radius: var(--radius-control); background: linear-gradient(to right, transparent, var(--row-fill) 1rem); opacity: 0; pointer-events: none; transition: opacity 150ms ease; }
2529
+ .mcp-row:hover .mcp-row-actions, .mcp-row:focus-within .mcp-row-actions { opacity: 1; pointer-events: auto; }
2530
+ @media (hover: none) { .mcp-row-actions { opacity: 1; pointer-events: auto; } }
2531
+ .mcp-detail-pane { display: flex; flex-direction: column; min-width: 0; min-height: 0; }
2532
+ .mcp-detail-header { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, auto); grid-template-rows: 2.5rem; align-items: center; gap: 0 .875rem; flex: none; min-height: 4.5rem; padding: 1rem 3.5rem 1rem 1.5rem; }
2533
+ .mcp-grow { display: flex; flex-direction: column; justify-content: center; height: 2.5rem; min-width: 0; }
2534
+ .mcp-detail-header h3 { margin: 0; overflow: hidden; font-size: 1.125rem; font-weight: 600; line-height: 1.25rem; text-overflow: ellipsis; white-space: nowrap; }
2535
+ .mcp-status-control { display: flex; align-items: center; justify-content: flex-end; justify-self: end; max-width: 100%; min-width: 0; }
2536
+ .mcp-status[data-slot=badge] { min-width: 0; overflow: hidden; gap: .375rem; white-space: nowrap; }
2537
+ .mcp-status-trigger { display: inline-flex; align-items: center; max-width: 100%; min-width: 0; min-height: 0; height: 1.25rem; padding: 0; border: 0; border-radius: var(--radius-pill); background: none; line-height: 1.25rem; }
2538
+ .mcp-status-trigger:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
2539
+ .mcp-status .mcp-dot { margin-right: 0; }
2540
+ .mcp-detail-body { display: flex; flex: 1; flex-direction: column; gap: 1rem; min-height: 0; overflow-y: auto; padding: 1rem 1.5rem 1.5rem; }
2541
+ .mcp-detail-empty { display: flex; flex: 1; flex-direction: column; justify-content: center; gap: 1rem; padding: 1.5rem; }
2542
+ @container mcp (max-width: 38rem) {
2543
+ .mcp-shell { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); }
2544
+ .mcp-servers { flex-direction: row; align-items: center; gap: .5rem; padding: .5rem 3rem .5rem 1rem; border-inline-end: 0; border-bottom: 1px solid var(--border); }
2545
+ .mcp-servers-title, .mcp-row-open small, .mcp-row-actions { display: none; }
2546
+ .mcp-list { flex-direction: row; overflow-x: auto; overflow-y: hidden; }
2547
+ .mcp-row { flex: none; }
2548
+ /* The chosen chip keeps its switch and delete, inline, since a strip has no hover room. */
2549
+ .mcp-row[data-active] { display: flex; align-items: center; padding-inline-end: .25rem; }
2550
+ .mcp-row[data-active] .mcp-row-actions { position: static; display: flex; padding: 0; background: none; opacity: 1; pointer-events: auto; }
2551
+ .mcp-servers-foot { padding: 0; }
2552
+ .mcp-detail-header, .mcp-detail-body { padding-inline: 1rem; }
2553
+ .mcp-detail-body { --body-pad-x: 1rem; }
2554
+ .mcp-detail-pane > [data-slot=tabs] > [data-slot=tabs-list] { margin-inline: 1rem; }
2555
+ }
2556
+ .mcp-row-error { color: var(--destructive); font-size: .75rem; overflow-wrap: anywhere; }
2557
+ .mcp-muted { margin: 0; color: var(--muted-foreground); font-size: .75rem; }
2558
+ .mcp-dot { display: inline-block; width: .5rem; height: .5rem; margin-right: .375rem; border-radius: var(--radius-pill); background: var(--muted-foreground); }
2559
+ .mcp-dot[data-state="ok"] { background: var(--success); }
2560
+ .mcp-dot[data-state="pending"] { background: var(--warning); }
2561
+ .mcp-dot[data-state="failed"] { background: var(--destructive); }
2562
+ .mcp-table { position: relative; display: flex; flex-direction: column; gap: .5rem; min-width: 0; margin: 0; padding: 0 0 0 8rem; border: 0; }
2563
+ .mcp-table > legend { position: absolute; top: 0; left: 0; width: 7rem; padding: .375rem 0 0; font-size: .875rem; }
2564
+ .mcp-table > [data-slot=button] { align-self: flex-start; }
2565
+ @container (max-width: 28rem) { .mcp-table { padding-left: 0; } .mcp-table > legend { position: static; padding: 0; } }
2566
+ .mcp-mono { font-family: var(--font-mono, ui-monospace, monospace); }
2567
+ button.mcp-icon { flex: none; width: 1.75rem; padding: 0; color: var(--muted-foreground); }
2568
+ .mcp-icon[aria-pressed=true] { color: var(--warning); }
2569
+ .mcp-hover-action { opacity: 0; transition: opacity 150ms ease; }
2570
+ :is(.mcp-arg, .mcp-kv-row):is(:hover, :focus-within) .mcp-hover-action { opacity: 1; }
2571
+ @media (hover: none) { .mcp-hover-action { opacity: 1; } }
2572
+ .mcp-args { display: flex; flex-direction: column; gap: .375rem; margin: 0; padding: 0; list-style: none; }
2573
+ .mcp-arg { display: flex; align-items: center; gap: .25rem; min-width: 0; margin-inline-start: -2rem; border-radius: var(--radius-control); transition: opacity 150ms ease; }
2574
+ .mcp-arg[data-dragging=true] { opacity: .4; }
2575
+ .mcp-arg > [data-slot=input], .mcp-arg > input { flex: 1; min-width: 0; }
2576
+ button.mcp-grip { cursor: grab; opacity: .5; }
2577
+ button.mcp-grip:hover, .mcp-arg:focus-within .mcp-grip { opacity: 1; }
2578
+ @container (max-width: 28rem) { .mcp-arg { margin-inline-start: 0; } }
2579
+ .mcp-kv { display: flex; flex-direction: column; gap: .375rem; }
2580
+ .mcp-kv-row { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 3fr) auto auto; align-items: center; gap: .375rem; }
2581
+ .mcp-kv[data-columns="3"] .mcp-kv-row { grid-template-columns: minmax(0, 2fr) minmax(0, 3fr) auto; }
2582
+ .mcp-kv-row .mcp-row-error { grid-column: 1 / -1; margin: 0; }
2583
+ .mcp-more { display: flex; flex-direction: column; gap: 1rem; }
2584
+ .mcp-more-summary { padding-block: .25rem; color: var(--muted-foreground); transition: color 150ms ease; }
2585
+ .mcp-more-summary:hover, .mcp-more[open] > .mcp-more-summary { color: var(--foreground); }
2586
+ .mcp-more-hint { color: var(--muted-foreground); }
2587
+ .mcp-more-body { display: flex; flex-direction: column; gap: 1rem; }
2588
+ .mcp-detail-body { --body-pad-x: 1.5rem; --body-pad-bottom: 1.5rem; }
2589
+ .mcp-detail-body > [role=tabpanel], .mcp-detail-body .mcp-detail { display: flex; flex: 1; flex-direction: column; }
2590
+ .mcp-detail-body .mcp-form { flex: 1; }
2591
+ /* The footer's buttons rest .75rem above the pane's floor, where the server column's add button rests. */
2592
+ .mcp-footer { position: sticky; bottom: calc(-1 * var(--body-pad-bottom, 0px)); z-index: 1; display: flex; flex-direction: column; gap: .75rem; margin: auto calc(-1 * var(--body-pad-x, 0px)) calc(-1 * var(--body-pad-bottom, 0px)); padding: .75rem var(--body-pad-x, 0px); background: var(--card); }
2593
+ .mcp-footer-actions { display: flex; gap: .5rem; }
2594
+ .mcp-footer > [role=status] { margin: 0; font-size: .75rem; }
2595
+ .mcp-footer-actions > *, .mcp-footer-button { flex: 1 1 0; min-width: 0; }
2596
+ .mcp-footer-button[aria-disabled=true] { opacity: .4; cursor: not-allowed; }
2597
+ .mcp-risk { display: flex; flex-direction: column; min-width: 0; font-size: .75rem; }
2598
+ .mcp-risk-title { margin: 0; color: var(--warning); font-weight: 500; }
2599
+ button.mcp-risk-command { display: block; width: fit-content; max-width: 100%; height: auto; padding: 0; overflow: hidden; border-radius: 2px; color: var(--muted-foreground); font-size: inherit; text-align: start; text-overflow: ellipsis; white-space: nowrap; }
2600
+ .mcp-risk-command code { font-family: var(--font-mono, ui-monospace, monospace); }
2601
+ .mcp-test-ok { color: var(--success); }
2602
+ .mcp-oauth { display: flex; flex-direction: column; min-width: 0; gap: .5rem; }
2603
+ .mcp-oauth-header { display: grid; grid-template-columns: 5rem minmax(0, 1fr) auto; align-items: center; gap: .75rem; min-height: var(--form-control-height); }
2604
+ .mcp-oauth-label { font-size: .8125rem; font-weight: 500; }
2605
+ .mcp-oauth-status { display: inline-flex; align-items: center; gap: .375rem; min-width: 0; font-size: .75rem; color: var(--muted-foreground); }
2606
+ .mcp-oauth-authorized { color: var(--success); }
2607
+ .mcp-oauth-dot { display: inline-block; flex: none; width: .375rem; height: .375rem; border-radius: var(--radius-pill); background: currentColor; }
2608
+ .mcp-oauth-actions { display: flex; align-items: center; flex-wrap: wrap; gap: .5rem .75rem; min-width: 0; }
2609
+ .mcp-oauth-header .mcp-oauth-actions { justify-content: flex-end; flex-wrap: nowrap; gap: .5rem; }
2610
+ .mcp-oauth-flow { display: flex; flex-direction: column; min-width: 0; gap: .875rem; margin-top: .5rem; padding: 1.125rem; border: 1px solid var(--border); border-radius: var(--radius-control); background: color-mix(in srgb, var(--success) 4%, var(--background)); }
2611
+ .mcp-oauth-flow > strong { font-size: .8125rem; font-weight: 600; }
2612
+ .mcp-oauth-flow .mcp-oauth-hint { margin: 0; font-size: .75rem; line-height: 1.7; color: var(--muted-foreground); }
2613
+ .mcp-oauth-warning { background: color-mix(in srgb, var(--warning) 5%, var(--background)); }
2614
+ .mcp-oauth-footer { display: flex; align-items: center; gap: .375rem; padding-top: .75rem; border-top: 1px solid var(--border); font-size: var(--text-2xs); color: var(--muted-foreground); }
2615
+ .mcp-oauth-footer .mcp-oauth-dot { color: var(--success); }
2616
+ .mcp-oauth-external { flex: none; white-space: nowrap; text-decoration: none; background: var(--primary); color: var(--primary-foreground); }
2617
+ .mcp-oauth-external:hover { background: color-mix(in srgb, var(--primary) 90%, var(--foreground)); }
2618
+ .mcp-oauth-external svg { width: .875rem; height: .875rem; }
2619
+ .mcp-oauth-url { overflow-wrap: anywhere; }
2620
+ .mcp-oauth .mcp-oauth-address { min-width: 0; padding: 0; border: 0; color: var(--muted-foreground); font-size: .75rem; }
2621
+ @container (min-width: 28rem) { .mcp-oauth-header { grid-template-columns: 7rem minmax(0, 1fr) auto; gap: 1rem; } }
2622
+ @container (max-width: 27.999rem) { .mcp-oauth-header { grid-template-columns: 4rem minmax(0, 1fr) auto; gap: .5rem; } .mcp-oauth-header .mcp-oauth-actions button { padding-inline: .5rem; } .mcp-oauth-flow { padding: .75rem; } }
2623
+ .mcp-capabilities { display: flex; flex-direction: column; gap: .75rem; min-width: 0; }
2624
+ .mcp-cap-group h4 { display: flex; align-items: center; gap: .375rem; margin: 0 0 .25rem; font-size: .75rem; font-weight: 500; color: var(--muted-foreground); }
2625
+ .mcp-cap-group-icon { width: .8125rem; height: .8125rem; }
2626
+ .mcp-cap-kind { display: grid; flex: none; place-items: center; width: 1.75rem; height: 1.75rem; border-radius: var(--radius-control); background: var(--muted); color: var(--muted-foreground); transition: background-color 150ms ease; }
2627
+ .mcp-cap-kind > svg { width: .875rem; height: .875rem; }
2628
+ .mcp-cap-row:is(:hover, [data-selected]) .mcp-cap-kind { background: var(--card); }
2629
+ .mcp-cap-group ul { display: flex; flex-direction: column; gap: 2px; margin: 0 -.75rem; padding: 0; list-style: none; }
2630
+ .mcp-cap-row { min-width: 0; border-radius: var(--radius-control); transition: background-color 150ms ease; }
2631
+ .mcp-cap-row:hover { background: var(--muted); }
2632
+ .mcp-cap-row[data-selected] { background: var(--accent); }
2633
+ .mcp-cap-row[data-selected] .mcp-cap-name strong { color: var(--primary); }
2634
+ .mcp-cap-row:has(> .mcp-cap-open:focus-visible) { outline: var(--focus-ring-width) solid var(--focus-ring-color); }
2635
+ button.mcp-cap-open { display: flex; align-items: center; gap: .75rem; width: 100%; min-width: 0; padding: .5rem .75rem; border-radius: var(--radius-control); text-align: start; cursor: pointer; outline: none; }
2636
+ .mcp-cap-name { display: flex; flex: 1; flex-direction: column; min-width: 0; }
2637
+ .mcp-cap-name strong, .mcp-cap-name small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2638
+ .mcp-cap-name strong { font-size: .875rem; font-weight: 500; }
2639
+ .mcp-cap-name small { font-family: var(--font-mono, monospace); font-size: .75rem; color: var(--muted-foreground); }
2640
+ .mcp-cap-open [data-slot=badge] { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2641
+ .mcp-tab-count { display: inline-block; min-width: 1.25rem; margin-inline-start: .375rem; padding-inline: .375rem; border-radius: var(--radius-pill); background: var(--muted); font-size: .6875rem; line-height: 1.125rem; text-align: center; color: var(--muted-foreground); }
2642
+ [aria-selected=true] .mcp-tab-count { background: color-mix(in srgb, var(--primary) 10%, var(--card)); color: var(--primary); }
2643
+ .mcp-detail-pane > [data-slot=tabs] { flex: 1; min-height: 0; gap: 0; }
2644
+ .mcp-detail-pane > [data-slot=tabs] > [data-slot=tabs-list] { margin-inline: 1.5rem; }
2645
+ .mcp-description { margin: 0; overflow: hidden; font-size: .75rem; line-height: 1.25rem; color: var(--muted-foreground); text-overflow: ellipsis; white-space: nowrap; }
2646
+ .mcp-agents { display: flex; flex-direction: column; gap: 2px; margin: 0 -.75rem; padding: 0; list-style: none; }
2647
+ .mcp-agent-row { display: flex; align-items: center; gap: .75rem; min-width: 0; padding: .5rem .75rem; border-radius: var(--radius-control); transition: background-color 150ms ease; }
2648
+ .mcp-agent-row:hover { background: var(--muted); }
2649
+ .mcp-agent-name { display: flex; flex: 1; flex-direction: column; min-width: 0; }
2650
+ .mcp-agent-name strong, .mcp-agent-name small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2651
+ .mcp-agent-name strong { font-size: .875rem; font-weight: 500; }
2652
+ .mcp-agent-name small { font-size: .75rem; color: var(--muted-foreground); }
2653
+ /* The popup is itself the scope's root, so it is reached through :scope. */
2654
+ :scope.mcp-cap-popover { max-height: min(28rem, var(--available-height)); padding: .875rem 1rem; }
2655
+ .mcp-cap-details { display: flex; flex-direction: column; gap: .75rem; font-size: .8125rem; }
2656
+ .mcp-cap-description { margin: 0; line-height: 1.6; white-space: pre-wrap; overflow-wrap: anywhere; }
2657
+ .mcp-cap-facts { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: .25rem .75rem; margin: 0; font-size: .8125rem; }
2658
+ .mcp-cap-facts dt { color: var(--muted-foreground); }
2659
+ .mcp-cap-facts dd { margin: 0; overflow-wrap: anywhere; }
2660
+ .mcp-cap-params h4 { margin: 0 0 .5rem; font-size: .75rem; font-weight: 500; color: var(--muted-foreground); }
2661
+ .mcp-cap-params ul { display: flex; flex-direction: column; gap: .75rem; margin: 0; padding: 0; list-style: none; }
2662
+ .mcp-cap-param { display: flex; flex-direction: column; gap: .25rem; min-width: 0; }
2663
+ .mcp-cap-param-head { display: flex; flex-wrap: wrap; align-items: center; gap: .375rem; }
2664
+ .mcp-cap-param-head code { font-family: var(--font-mono, monospace); font-size: .8125rem; font-weight: 500; overflow-wrap: anywhere; }
2665
+ .mcp-cap-param small { font-size: .75rem; line-height: 1.5; color: var(--muted-foreground); overflow-wrap: anywhere; }
2666
+ `;
2667
+ var register = (ctx) => {
2668
+ registerMetadata(ctx);
2669
+ ctx.i18n.register(CATALOGUES, "en-US");
2670
+ ctx.styles.add(STYLES);
2671
+ const title = () => ctx.i18n.t("mcp.title");
2672
+ ctx.slots.register("shell.settings.category", {
2673
+ id: "mcp-settings",
2674
+ label: title,
2675
+ region: "preset",
2676
+ order: 60,
2677
+ icon: "blocks",
2678
+ layout: "fill",
2679
+ component: settingsFor(ctx)
2680
+ });
2681
+ ctx.slots.register("shell.agentEditor.tab", {
2682
+ id: "mcp-agent-tab",
2683
+ title,
2684
+ component: agentTabFor(ctx)
2685
+ });
2686
+ ctx.slots.register("chat.composer.commands", commandSource(ctx));
2687
+ ctx.slots.register("chat.composer.attachments", attachmentSource(ctx));
2688
+ };
2689
+ //#endregion
2690
+ export { register, runtimeVersion };