363 lines
11 KiB
TypeScript
363 lines
11 KiB
TypeScript
"use client";
|
||
|
||
import { useEffect, useMemo, useState } from "react";
|
||
import { toast } from "sonner";
|
||
|
||
import { Button } from "@/components/ui/button";
|
||
import {
|
||
Dialog,
|
||
DialogContent,
|
||
DialogFooter,
|
||
DialogHeader,
|
||
DialogTitle,
|
||
} from "@/components/ui/dialog";
|
||
import { Input } from "@/components/ui/input";
|
||
import {
|
||
Select,
|
||
SelectContent,
|
||
SelectItem,
|
||
SelectTrigger,
|
||
SelectValue,
|
||
} from "@/components/ui/select";
|
||
import { Switch } from "@/components/ui/switch";
|
||
import { Textarea } from "@/components/ui/textarea";
|
||
import { useUpsertMCPServer } from "@/core/mcp/hooks";
|
||
import type {
|
||
MCPServerConfig,
|
||
MCPServerTransport,
|
||
} from "@/core/mcp/types";
|
||
|
||
type EditMode = "create" | "edit";
|
||
|
||
export interface MCPServerEditDialogProps {
|
||
open: boolean;
|
||
onOpenChange: (open: boolean) => void;
|
||
mode: EditMode;
|
||
originalName?: string;
|
||
initialServer?: MCPServerConfig;
|
||
existingNames: string[];
|
||
}
|
||
|
||
const TRANSPORT_OPTIONS: { value: MCPServerTransport; label: string }[] = [
|
||
{ value: "stdio", label: "stdio(本地进程)" },
|
||
{ value: "http", label: "http(远端 HTTP)" },
|
||
{ value: "sse", label: "sse(远端 SSE)" },
|
||
];
|
||
|
||
const DEFAULT_SERVER: MCPServerConfig = {
|
||
enabled: true,
|
||
type: "stdio",
|
||
command: "",
|
||
args: [],
|
||
env: {},
|
||
url: "",
|
||
headers: {},
|
||
description: "",
|
||
disabled_tools: [],
|
||
};
|
||
|
||
function argsToText(args?: string[]): string {
|
||
return (args ?? []).join("\n");
|
||
}
|
||
|
||
function textToArgs(text: string): string[] {
|
||
return text
|
||
.split("\n")
|
||
.map((line) => line.trim())
|
||
.filter(Boolean);
|
||
}
|
||
|
||
function kvToText(map?: Record<string, string>): string {
|
||
if (!map) return "";
|
||
return Object.entries(map)
|
||
.map(([k, v]) => `${k}=${v}`)
|
||
.join("\n");
|
||
}
|
||
|
||
function textToKV(text: string): { value: Record<string, string>; error?: string } {
|
||
const result: Record<string, string> = {};
|
||
const lines = text.split("\n");
|
||
for (const rawLine of lines) {
|
||
const line = rawLine.trim();
|
||
if (!line) continue;
|
||
const eq = line.indexOf("=");
|
||
if (eq <= 0) {
|
||
return { value: {}, error: `每行需为 KEY=VALUE 格式:${line}` };
|
||
}
|
||
const key = line.slice(0, eq).trim();
|
||
const value = line.slice(eq + 1);
|
||
if (!key) {
|
||
return { value: {}, error: `键名不能为空:${line}` };
|
||
}
|
||
result[key] = value;
|
||
}
|
||
return { value: result };
|
||
}
|
||
|
||
export function MCPServerEditDialog({
|
||
open,
|
||
onOpenChange,
|
||
mode,
|
||
originalName,
|
||
initialServer,
|
||
existingNames,
|
||
}: MCPServerEditDialogProps) {
|
||
const upsert = useUpsertMCPServer();
|
||
|
||
const [name, setName] = useState("");
|
||
const [type, setType] = useState<MCPServerTransport>("stdio");
|
||
const [enabled, setEnabled] = useState(true);
|
||
const [description, setDescription] = useState("");
|
||
const [command, setCommand] = useState("");
|
||
const [argsText, setArgsText] = useState("");
|
||
const [envText, setEnvText] = useState("");
|
||
const [url, setUrl] = useState("");
|
||
const [headersText, setHeadersText] = useState("");
|
||
const [disabledToolsText, setDisabledToolsText] = useState("");
|
||
|
||
useEffect(() => {
|
||
if (!open) return;
|
||
const base = initialServer ?? DEFAULT_SERVER;
|
||
setName(originalName ?? "");
|
||
setType((base.type ?? "stdio") as MCPServerTransport);
|
||
setEnabled(base.enabled);
|
||
setDescription(base.description ?? "");
|
||
setCommand(base.command ?? "");
|
||
setArgsText(argsToText(base.args));
|
||
setEnvText(kvToText(base.env));
|
||
setUrl(base.url ?? "");
|
||
setHeadersText(kvToText(base.headers));
|
||
setDisabledToolsText((base.disabled_tools ?? []).join("\n"));
|
||
}, [open, initialServer, originalName]);
|
||
|
||
const nameConflict = useMemo(() => {
|
||
const trimmed = name.trim();
|
||
if (!trimmed) return false;
|
||
if (mode === "edit" && trimmed === originalName) return false;
|
||
return existingNames.includes(trimmed);
|
||
}, [name, existingNames, mode, originalName]);
|
||
|
||
const handleSubmit = async () => {
|
||
const trimmedName = name.trim();
|
||
if (!trimmedName) {
|
||
toast.error("请填写 MCP 服务器名称");
|
||
return;
|
||
}
|
||
if (nameConflict) {
|
||
toast.error(`已存在同名 MCP 服务器:${trimmedName}`);
|
||
return;
|
||
}
|
||
|
||
const env = textToKV(envText);
|
||
if (env.error) {
|
||
toast.error(`环境变量格式错误:${env.error}`);
|
||
return;
|
||
}
|
||
const headers = textToKV(headersText);
|
||
if (headers.error) {
|
||
toast.error(`Headers 格式错误:${headers.error}`);
|
||
return;
|
||
}
|
||
|
||
const args = textToArgs(argsText);
|
||
const disabledTools = textToArgs(disabledToolsText);
|
||
|
||
if (type === "stdio" && !command.trim()) {
|
||
toast.error("stdio 传输需要填写启动命令");
|
||
return;
|
||
}
|
||
if ((type === "http" || type === "sse") && !url.trim()) {
|
||
toast.error(`${type} 传输需要填写服务器 URL`);
|
||
return;
|
||
}
|
||
|
||
const server: MCPServerConfig = {
|
||
enabled,
|
||
type,
|
||
description: description.trim(),
|
||
command: type === "stdio" ? command.trim() : null,
|
||
args: type === "stdio" ? args : [],
|
||
env: type === "stdio" ? env.value : {},
|
||
url: type === "stdio" ? null : url.trim(),
|
||
headers: type === "stdio" ? {} : headers.value,
|
||
disabled_tools: disabledTools,
|
||
};
|
||
|
||
try {
|
||
await upsert.mutateAsync({
|
||
serverName: trimmedName,
|
||
server,
|
||
originalName: mode === "edit" ? originalName : undefined,
|
||
});
|
||
toast.success(mode === "create" ? "MCP 服务器已创建" : "MCP 服务器已更新");
|
||
onOpenChange(false);
|
||
} catch (err) {
|
||
toast.error(err instanceof Error ? err.message : String(err));
|
||
}
|
||
};
|
||
|
||
return (
|
||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||
<DialogContent
|
||
className="max-h-[85vh] overflow-y-auto sm:max-w-2xl"
|
||
aria-describedby={undefined}
|
||
>
|
||
<DialogHeader>
|
||
<DialogTitle>
|
||
{mode === "create" ? "新增 MCP 服务器" : `编辑 MCP 服务器`}
|
||
</DialogTitle>
|
||
</DialogHeader>
|
||
<div className="flex flex-col gap-4 py-2">
|
||
<Field label="名称" hint="作为 MCP 服务器的唯一标识,用于工具命名前缀">
|
||
<Input
|
||
value={name}
|
||
onChange={(e) => setName(e.target.value)}
|
||
placeholder="例如 github、filesystem"
|
||
aria-invalid={nameConflict || undefined}
|
||
/>
|
||
{nameConflict && (
|
||
<div className="text-destructive text-xs">已存在同名服务器</div>
|
||
)}
|
||
</Field>
|
||
|
||
<div className="grid grid-cols-2 gap-4">
|
||
<Field label="传输类型">
|
||
<Select
|
||
value={type}
|
||
onValueChange={(v) => setType(v as MCPServerTransport)}
|
||
>
|
||
<SelectTrigger>
|
||
<SelectValue />
|
||
</SelectTrigger>
|
||
<SelectContent>
|
||
{TRANSPORT_OPTIONS.map((opt) => (
|
||
<SelectItem key={opt.value} value={opt.value}>
|
||
{opt.label}
|
||
</SelectItem>
|
||
))}
|
||
</SelectContent>
|
||
</Select>
|
||
</Field>
|
||
<Field label="启用">
|
||
<div className="flex h-9 items-center">
|
||
<Switch
|
||
checked={enabled}
|
||
onCheckedChange={setEnabled}
|
||
/>
|
||
<span className="text-muted-foreground ml-2 text-xs">
|
||
{enabled ? "已启用" : "已停用"}
|
||
</span>
|
||
</div>
|
||
</Field>
|
||
</div>
|
||
|
||
<Field label="描述">
|
||
<Textarea
|
||
rows={2}
|
||
value={description}
|
||
onChange={(e) => setDescription(e.target.value)}
|
||
placeholder="给这个 MCP 服务器写一段说明,会展示在工具列表里"
|
||
/>
|
||
</Field>
|
||
|
||
{type === "stdio" && (
|
||
<>
|
||
<Field
|
||
label="启动命令"
|
||
hint="例如 npx、uvx、python,配合参数启动 MCP server 进程"
|
||
>
|
||
<Input
|
||
value={command}
|
||
onChange={(e) => setCommand(e.target.value)}
|
||
placeholder="npx"
|
||
/>
|
||
</Field>
|
||
<Field label="参数" hint="每行一个参数">
|
||
<Textarea
|
||
rows={3}
|
||
value={argsText}
|
||
onChange={(e) => setArgsText(e.target.value)}
|
||
placeholder={"-y\n@modelcontextprotocol/server-github"}
|
||
/>
|
||
</Field>
|
||
<Field
|
||
label="环境变量"
|
||
hint="每行 KEY=VALUE;值以 $ 开头会在加载时解析为对应环境变量"
|
||
>
|
||
<Textarea
|
||
rows={3}
|
||
value={envText}
|
||
onChange={(e) => setEnvText(e.target.value)}
|
||
placeholder={"GITHUB_TOKEN=$GITHUB_TOKEN"}
|
||
/>
|
||
</Field>
|
||
</>
|
||
)}
|
||
|
||
{(type === "http" || type === "sse") && (
|
||
<>
|
||
<Field label="服务器 URL">
|
||
<Input
|
||
value={url}
|
||
onChange={(e) => setUrl(e.target.value)}
|
||
placeholder="https://example.com/mcp"
|
||
/>
|
||
</Field>
|
||
<Field label="Headers" hint="每行 KEY=VALUE">
|
||
<Textarea
|
||
rows={3}
|
||
value={headersText}
|
||
onChange={(e) => setHeadersText(e.target.value)}
|
||
placeholder={"Authorization=Bearer xxx"}
|
||
/>
|
||
</Field>
|
||
</>
|
||
)}
|
||
|
||
<Field
|
||
label="禁用的工具"
|
||
hint="每行一个工具名(不带服务器前缀),加载时会被过滤掉"
|
||
>
|
||
<Textarea
|
||
rows={2}
|
||
value={disabledToolsText}
|
||
onChange={(e) => setDisabledToolsText(e.target.value)}
|
||
placeholder={"some_dangerous_tool"}
|
||
/>
|
||
</Field>
|
||
</div>
|
||
<DialogFooter>
|
||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||
取消
|
||
</Button>
|
||
<Button onClick={handleSubmit} disabled={upsert.isPending}>
|
||
{upsert.isPending
|
||
? "保存中..."
|
||
: mode === "create"
|
||
? "创建"
|
||
: "保存"}
|
||
</Button>
|
||
</DialogFooter>
|
||
</DialogContent>
|
||
</Dialog>
|
||
);
|
||
}
|
||
|
||
function Field({
|
||
label,
|
||
hint,
|
||
children,
|
||
}: {
|
||
label: string;
|
||
hint?: string;
|
||
children: React.ReactNode;
|
||
}) {
|
||
return (
|
||
<div className="flex flex-col gap-1">
|
||
<div className="text-sm font-medium">{label}</div>
|
||
{hint && <div className="text-muted-foreground text-xs">{hint}</div>}
|
||
{children}
|
||
</div>
|
||
);
|
||
}
|