feat: add MCP tool integration

This commit is contained in:
Xin Wang
2026-07-18 00:00:06 +08:00
parent bdf3d3dd9c
commit e39bb48ba8
21 changed files with 1641 additions and 62 deletions

View File

@@ -0,0 +1,449 @@
"use client";
import {
Loader2,
Pencil,
Plus,
RefreshCw,
ServerCog,
Trash2,
} from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DataList, type DataListColumn } from "@/components/ui/data-list";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import {
mcpServersApi,
type McpServer,
type McpServerUpsert,
type ToolStatus,
} from "@/lib/api";
type McpServerForm = {
name: string;
description: string;
url: string;
timeoutSeconds: string;
headers: string;
secretHeaders: string;
status: ToolStatus;
};
const EMPTY_OBJECT = "{}";
function blankForm(): McpServerForm {
return {
name: "",
description: "",
url: "",
timeoutSeconds: "30",
headers: EMPTY_OBJECT,
secretHeaders: EMPTY_OBJECT,
status: "active",
};
}
function formFromServer(server: McpServer): McpServerForm {
return {
name: server.name,
description: server.description,
url: server.url,
timeoutSeconds: String(server.timeoutSeconds),
headers: JSON.stringify(server.headers ?? {}, null, 2),
secretHeaders: JSON.stringify(server.secretHeaders ?? {}, null, 2),
status: server.status,
};
}
function parseStringMap(value: string, label: string): Record<string, string> {
let parsed: unknown;
try {
parsed = JSON.parse(value || EMPTY_OBJECT);
} catch {
throw new Error(`${label}不是有效的 JSON`);
}
if (!parsed || Array.isArray(parsed) || typeof parsed !== "object") {
throw new Error(`${label}必须是 JSON 对象`);
}
const entries = Object.entries(parsed);
if (entries.some(([, item]) => typeof item !== "string")) {
throw new Error(`${label}的值必须全部是字符串`);
}
return Object.fromEntries(entries) as Record<string, string>;
}
function payloadFromForm(form: McpServerForm): McpServerUpsert {
if (!form.name.trim()) throw new Error("请输入 MCP Server 名称");
if (!form.url.startsWith("http://") && !form.url.startsWith("https://")) {
throw new Error("MCP Server URL 必须使用 http:// 或 https://");
}
const timeoutSeconds = Number(form.timeoutSeconds);
if (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 1 || timeoutSeconds > 120) {
throw new Error("超时时间必须是 1 到 120 秒之间的整数");
}
return {
name: form.name.trim(),
description: form.description.trim(),
transport: "streamable_http",
url: form.url.trim(),
timeoutSeconds,
headers: parseStringMap(form.headers, "Header"),
secretHeaders: parseStringMap(form.secretHeaders, "敏感 Header"),
status: form.status,
};
}
export function McpServersSection({
onToolsChanged,
}: {
onToolsChanged: () => void | Promise<void>;
}) {
const [servers, setServers] = useState<McpServer[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [dialogOpen, setDialogOpen] = useState(false);
const [editing, setEditing] = useState<McpServer | null>(null);
const [form, setForm] = useState<McpServerForm>(blankForm);
const [formError, setFormError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [syncingId, setSyncingId] = useState<string | null>(null);
const [deletingId, setDeletingId] = useState<string | null>(null);
const loadServers = useCallback(async () => {
setLoading(true);
setError(null);
try {
setServers(await mcpServersApi.list());
} catch (loadError) {
setError(loadError instanceof Error ? loadError.message : "加载 MCP Server 失败");
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
void loadServers();
}, [loadServers]);
function openCreate() {
setEditing(null);
setForm(blankForm());
setFormError(null);
setDialogOpen(true);
}
function openEdit(server: McpServer) {
setEditing(server);
setForm(formFromServer(server));
setFormError(null);
setDialogOpen(true);
}
async function syncServer(serverId: string) {
setSyncingId(serverId);
setError(null);
try {
await mcpServersApi.sync(serverId);
await Promise.all([loadServers(), onToolsChanged()]);
} catch (syncError) {
setError(syncError instanceof Error ? syncError.message : "同步 MCP 工具失败");
} finally {
setSyncingId(null);
}
}
async function saveAndSync() {
if (saving) return;
setSaving(true);
setFormError(null);
try {
const payload = payloadFromForm(form);
const saved = editing
? await mcpServersApi.update(editing.id, payload)
: await mcpServersApi.create(payload);
await mcpServersApi.sync(saved.id);
setDialogOpen(false);
await Promise.all([loadServers(), onToolsChanged()]);
} catch (saveError) {
setFormError(
saveError instanceof Error ? saveError.message : "保存或同步 MCP Server 失败",
);
} finally {
setSaving(false);
}
}
async function removeServer(server: McpServer) {
if (!window.confirm(`确认删除 MCP Server“${server.name}”及其同步工具?`)) {
return;
}
setDeletingId(server.id);
setError(null);
try {
await mcpServersApi.remove(server.id);
await Promise.all([loadServers(), onToolsChanged()]);
} catch (removeError) {
setError(removeError instanceof Error ? removeError.message : "删除 MCP Server 失败");
} finally {
setDeletingId(null);
}
}
const columns: DataListColumn<McpServer>[] = [
{
key: "name",
header: "MCP SERVER",
cell: (server) => (
<>
<div className="flex min-w-0 items-center gap-2">
<ServerCog size={15} className="shrink-0 text-muted-foreground" />
<span className="truncate font-medium text-foreground">{server.name}</span>
</div>
<div className="mt-1 truncate font-mono text-xs text-muted-soft">
{server.url}
</div>
</>
),
},
{
key: "tools",
header: "工具",
width: "md:w-[120px]",
cell: (server) => (
<span className="text-muted-foreground">{server.toolCount} </span>
),
},
{
key: "status",
header: "状态",
width: "md:w-[120px]",
cell: (server) => (
<Badge variant="outline" className="h-6 px-3">
{server.status === "active"
? "启用"
: server.status === "draft"
? "草稿"
: "归档"}
</Badge>
),
},
{
key: "actions",
header: "操作",
width: "md:w-[260px]",
align: "right",
cellClassName: "flex justify-end gap-2",
cell: (server) => (
<>
<Button
variant="outline"
size="sm"
className="gap-1.5 border-hairline-strong"
disabled={syncingId === server.id}
onClick={() => void syncServer(server.id)}
>
{syncingId === server.id ? (
<Loader2 size={14} className="animate-spin" />
) : (
<RefreshCw size={14} />
)}
</Button>
<Button
variant="outline"
size="icon-sm"
aria-label={`编辑 ${server.name}`}
onClick={() => openEdit(server)}
>
<Pencil size={14} />
</Button>
<Button
variant="outline"
size="icon-sm"
aria-label={`删除 ${server.name}`}
disabled={deletingId === server.id}
onClick={() => void removeServer(server)}
>
{deletingId === server.id ? (
<Loader2 size={14} className="animate-spin" />
) : (
<Trash2 size={14} />
)}
</Button>
</>
),
},
];
return (
<>
<section className="rounded-2xl border border-hairline bg-card p-6 shadow-sm">
<div className="mb-5 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
<div>
<div className="caption-label text-muted-soft">MCP CONNECTIONS</div>
<h2 className="mt-1 text-lg font-medium text-foreground">MCP Server</h2>
<p className="mt-1 text-sm text-muted-foreground">
MCP Server
</p>
</div>
<Button variant="outline" className="gap-2" onClick={openCreate}>
<Plus size={15} />
MCP Server
</Button>
</div>
<DataList<McpServer>
columns={columns}
rows={servers}
rowKey={(server) => server.id}
loading={loading}
loadingText="正在加载 MCP Server…"
error={error}
onRetry={() => void loadServers()}
empty={{
title: "暂无 MCP Server",
description: "添加连接后,系统会显式同步远端工具,不会自动暴露新能力。",
}}
/>
</section>
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent className="max-h-[calc(100vh-3rem)] overflow-y-auto sm:max-w-2xl">
<DialogHeader>
<DialogTitle>{editing ? "编辑 MCP Server" : "添加 MCP Server"}</DialogTitle>
<DialogDescription>
Streamable HTTP
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<label className="block">
<span className="mb-1.5 block text-sm font-medium"></span>
<Input
value={form.name}
onChange={(event) =>
setForm((current) => ({ ...current, name: event.target.value }))
}
/>
</label>
<label className="block">
<span className="mb-1.5 block text-sm font-medium">Streamable HTTP URL</span>
<Input
value={form.url}
placeholder="https://mcp.example.com/mcp"
onChange={(event) =>
setForm((current) => ({ ...current, url: event.target.value }))
}
/>
</label>
<div className="grid gap-4 sm:grid-cols-2">
<label className="block">
<span className="mb-1.5 block text-sm font-medium"></span>
<Input
type="number"
min={1}
max={120}
value={form.timeoutSeconds}
onChange={(event) =>
setForm((current) => ({
...current,
timeoutSeconds: event.target.value,
}))
}
/>
</label>
<label className="block">
<span className="mb-1.5 block text-sm font-medium"></span>
<Select
value={form.status}
onValueChange={(status: ToolStatus) =>
setForm((current) => ({ ...current, status }))
}
>
<SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="active"></SelectItem>
<SelectItem value="draft">稿</SelectItem>
<SelectItem value="archived"></SelectItem>
</SelectContent>
</Select>
</label>
</div>
<label className="block">
<span className="mb-1.5 block text-sm font-medium"> HeaderJSON</span>
<Textarea
rows={4}
className="font-mono text-xs"
value={form.headers}
onChange={(event) =>
setForm((current) => ({ ...current, headers: event.target.value }))
}
/>
</label>
<label className="block">
<span className="mb-1.5 block text-sm font-medium"> HeaderJSON</span>
<Textarea
rows={4}
className="font-mono text-xs"
value={form.secretHeaders}
placeholder={'{"Authorization":"Bearer ..."}'}
onChange={(event) =>
setForm((current) => ({
...current,
secretHeaders: event.target.value,
}))
}
/>
<span className="mt-1.5 block text-xs text-muted-foreground">
</span>
</label>
<label className="block">
<span className="mb-1.5 block text-sm font-medium"></span>
<Textarea
rows={3}
value={form.description}
onChange={(event) =>
setForm((current) => ({
...current,
description: event.target.value,
}))
}
/>
</label>
</div>
{formError && <div className="text-sm text-destructive">{formError}</div>}
<DialogFooter>
<Button variant="outline" onClick={() => setDialogOpen(false)}>
</Button>
<Button onClick={() => void saveAndSync()} disabled={saving}>
{saving && <Loader2 size={15} className="animate-spin" />}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}