feat(mcp): add configuration wizard and simplify form modal

- Simplify McpFormModal to 3 inputs: title (required), description (optional), and JSON config (optional)
- Add JSON validation similar to ProviderForm (must be object, real-time error display)
- Create McpWizardModal component for quick configuration:
  - 5 input fields: type (stdio/sse), command (required), args, cwd, env
  - Real-time JSON preview
  - Emerald theme color (consistent with MCP button)
  - Z-index 70 (above McpFormModal's 60)
- Add "or use configuration wizard" link next to JSON config label
- Update i18n translations (zh/en) for form and wizard
- All changes pass TypeScript typecheck and Prettier formatting
This commit is contained in:
Jason
2025-10-09 11:30:28 +08:00
parent 59c13c3366
commit d0fe9d7533
4 changed files with 431 additions and 125 deletions

View File

@@ -1,8 +1,9 @@
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { X, Save, Wrench } from "lucide-react";
import { X, Save, AlertCircle } from "lucide-react";
import { McpServer } from "../../types";
import { buttonStyles, inputStyles } from "../../lib/styles";
import McpWizardModal from "./McpWizardModal";
interface McpFormModalProps {
editingId?: string;
@@ -11,33 +12,25 @@ interface McpFormModalProps {
onClose: () => void;
}
const parseEnvText = (text: string): Record<string, string> => {
const lines = text
.split("\n")
.map((l) => l.trim())
.filter((l) => l.length > 0);
const env: Record<string, string> = {};
for (const l of lines) {
const idx = l.indexOf("=");
if (idx > 0) {
const k = l.slice(0, idx).trim();
const v = l.slice(idx + 1).trim();
if (k) env[k] = v;
/**
* 验证 JSON 格式
*/
const validateJson = (text: string): string => {
if (!text.trim()) return "";
try {
const parsed = JSON.parse(text);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
return "JSON 必须是对象";
}
return "";
} catch {
return "JSON 格式错误";
}
return env;
};
const formatEnvText = (env?: Record<string, string>): string => {
if (!env) return "";
return Object.entries(env)
.map(([k, v]) => `${k}=${v}`)
.join("\n");
};
/**
* MCP 表单模态框组件
* 用于添加或编辑 MCP 服务器
* MCP 表单模态框组件(简化版)
* 仅包含标题必填、描述可选、JSON 配置(可选,带格式校验)
*/
const McpFormModal: React.FC<McpFormModalProps> = ({
editingId,
@@ -47,32 +40,25 @@ const McpFormModal: React.FC<McpFormModalProps> = ({
}) => {
const { t } = useTranslation();
const [formId, setFormId] = useState(editingId || "");
const [formType, setFormType] = useState<"stdio" | "sse">(
initialData?.type || "stdio",
const [formDescription, setFormDescription] = useState("");
const [formJson, setFormJson] = useState(
initialData ? JSON.stringify(initialData, null, 2) : "",
);
const [formCommand, setFormCommand] = useState(initialData?.command || "");
const [formArgsText, setFormArgsText] = useState(
(initialData?.args || []).join(" "),
);
const [formEnvText, setFormEnvText] = useState(
formatEnvText(initialData?.env),
);
const [formCwd, setFormCwd] = useState(initialData?.cwd || "");
const [jsonError, setJsonError] = useState("");
const [saving, setSaving] = useState(false);
const [isWizardOpen, setIsWizardOpen] = useState(false);
// 编辑模式下禁止修改 ID
const isEditing = !!editingId;
const handleValidateCommand = async () => {
if (!formCommand) return;
try {
const ok = await window.api.validateMcpCommand(formCommand.trim());
const message = ok ? t("mcp.validation.ok") : t("mcp.validation.fail");
// 这里简单使用 alert实际项目中应该使用 notification 系统
alert(message);
} catch (_error) {
alert(t("mcp.validation.fail"));
}
const handleJsonChange = (value: string) => {
setFormJson(value);
setJsonError(validateJson(value));
};
const handleWizardApply = (json: string) => {
setFormJson(json);
setJsonError(validateJson(json));
};
const handleSubmit = async () => {
@@ -80,29 +66,38 @@ const McpFormModal: React.FC<McpFormModalProps> = ({
alert(t("mcp.error.idRequired"));
return;
}
if (!formCommand.trim()) {
alert(t("mcp.error.commandRequired"));
// 验证 JSON
const currentJsonError = validateJson(formJson);
setJsonError(currentJsonError);
if (currentJsonError) {
alert(t("mcp.error.jsonInvalid"));
return;
}
setSaving(true);
try {
const server: McpServer = {
type: formType,
command: formCommand.trim(),
args: formArgsText
.split(/\s+/)
.map((s) => s.trim())
.filter((s) => s.length > 0),
env: parseEnvText(formEnvText),
...(formCwd ? { cwd: formCwd } : {}),
// 保留原有的 enabled 状态
...(initialData?.enabled !== undefined
? { enabled: initialData.enabled }
: {}),
};
let server: McpServer;
if (formJson.trim()) {
// 解析 JSON 配置
server = JSON.parse(formJson) as McpServer;
} else {
// 空 JSON 时提供默认值
server = {
type: "stdio",
command: "",
args: [],
};
}
// 保留原有的 enabled 状态
if (initialData?.enabled !== undefined) {
server.enabled = initialData.enabled;
}
onSave(formId.trim(), server);
} catch (error) {
alert(t("mcp.error.saveFailed"));
} finally {
setSaving(false);
}
@@ -133,94 +128,59 @@ const McpFormModal: React.FC<McpFormModalProps> = ({
{/* Content */}
<div className="p-6 space-y-4">
{/* ID */}
{/* ID (标题) */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{t("mcp.id")}
{t("mcp.form.title")} <span className="text-red-500">*</span>
</label>
<input
className={inputStyles.text}
placeholder="my-mcp"
placeholder={t("mcp.form.titlePlaceholder")}
value={formId}
onChange={(e) => setFormId(e.target.value)}
disabled={isEditing}
/>
</div>
{/* Type & CWD */}
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{t("mcp.type")}
</label>
<select
className={inputStyles.select}
value={formType}
onChange={(e) => setFormType(e.target.value as "stdio" | "sse")}
>
<option value="stdio">stdio</option>
<option value="sse">sse</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{t("mcp.cwd")}
</label>
<input
className={inputStyles.text}
placeholder="/path/to/project"
value={formCwd}
onChange={(e) => setFormCwd(e.target.value)}
/>
</div>
</div>
{/* Command */}
{/* Description (描述) */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{t("mcp.command")}
</label>
<div className="flex gap-2">
<input
className={inputStyles.text}
placeholder="uvx"
value={formCommand}
onChange={(e) => setFormCommand(e.target.value)}
/>
<button
type="button"
onClick={handleValidateCommand}
className="px-3 py-2 rounded-md bg-emerald-500 text-white hover:bg-emerald-600 dark:bg-emerald-600 dark:hover:bg-emerald-700 text-sm inline-flex items-center gap-1 flex-shrink-0 transition-colors"
>
<Wrench size={16} /> {t("mcp.validateCommand")}
</button>
</div>
</div>
{/* Args */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{t("mcp.args")}
{t("mcp.form.description")}
</label>
<input
className={inputStyles.text}
placeholder={t("mcp.argsPlaceholder")}
value={formArgsText}
onChange={(e) => setFormArgsText(e.target.value)}
placeholder={t("mcp.form.descriptionPlaceholder")}
value={formDescription}
onChange={(e) => setFormDescription(e.target.value)}
/>
</div>
{/* Env */}
{/* JSON 配置 */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{t("mcp.env")}
</label>
<div className="flex items-center justify-between mb-2">
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
{t("mcp.form.jsonConfig")}
</label>
<button
type="button"
onClick={() => setIsWizardOpen(true)}
className="text-xs text-blue-500 dark:text-blue-400 hover:text-blue-600 dark:hover:text-blue-300 transition-colors"
>
{t("mcp.form.useWizard")}
</button>
</div>
<textarea
className={`${inputStyles.text} h-24 resize-none`}
placeholder={t("mcp.envPlaceholder")}
value={formEnvText}
onChange={(e) => setFormEnvText(e.target.value)}
className={`${inputStyles.text} h-64 resize-none font-mono text-xs`}
placeholder={t("mcp.form.jsonPlaceholder")}
value={formJson}
onChange={(e) => handleJsonChange(e.target.value)}
/>
{jsonError && (
<div className="flex items-center gap-2 mt-2 text-red-500 dark:text-red-400 text-sm">
<AlertCircle size={16} />
<span>{jsonError}</span>
</div>
)}
</div>
</div>
@@ -243,6 +203,13 @@ const McpFormModal: React.FC<McpFormModalProps> = ({
</button>
</div>
</div>
{/* Wizard Modal */}
<McpWizardModal
isOpen={isWizardOpen}
onClose={() => setIsWizardOpen(false)}
onApply={handleWizardApply}
/>
</div>
);
};

View File

@@ -0,0 +1,289 @@
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { X, Save } from "lucide-react";
import { McpServer } from "../../types";
import { isLinux } from "../../lib/platform";
interface McpWizardModalProps {
isOpen: boolean;
onClose: () => void;
onApply: (json: string) => void;
}
/**
* 解析环境变量文本为对象
*/
const parseEnvText = (text: string): Record<string, string> => {
const lines = text
.split("\n")
.map((l) => l.trim())
.filter((l) => l.length > 0);
const env: Record<string, string> = {};
for (const l of lines) {
const idx = l.indexOf("=");
if (idx > 0) {
const k = l.slice(0, idx).trim();
const v = l.slice(idx + 1).trim();
if (k) env[k] = v;
}
}
return env;
};
/**
* MCP 配置向导模态框
* 帮助用户快速生成 MCP JSON 配置
*/
const McpWizardModal: React.FC<McpWizardModalProps> = ({
isOpen,
onClose,
onApply,
}) => {
const { t } = useTranslation();
const [wizardType, setWizardType] = useState<"stdio" | "sse">("stdio");
const [wizardCommand, setWizardCommand] = useState("");
const [wizardArgs, setWizardArgs] = useState("");
const [wizardCwd, setWizardCwd] = useState("");
const [wizardEnv, setWizardEnv] = useState("");
// 生成预览 JSON
const generatePreview = (): string => {
const config: McpServer = {
type: wizardType,
command: wizardCommand.trim(),
};
// 添加可选字段
if (wizardArgs.trim()) {
config.args = wizardArgs
.split(/\s+/)
.map((s) => s.trim())
.filter((s) => s.length > 0);
}
if (wizardCwd.trim()) {
config.cwd = wizardCwd.trim();
}
if (wizardEnv.trim()) {
const env = parseEnvText(wizardEnv);
if (Object.keys(env).length > 0) {
config.env = env;
}
}
return JSON.stringify(config, null, 2);
};
const handleApply = () => {
if (!wizardCommand.trim()) {
alert(t("mcp.error.commandRequired"));
return;
}
const json = generatePreview();
onApply(json);
handleClose();
};
const handleClose = () => {
// 重置表单
setWizardType("stdio");
setWizardCommand("");
setWizardArgs("");
setWizardCwd("");
setWizardEnv("");
onClose();
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Enter" && e.metaKey) {
e.preventDefault();
handleApply();
}
};
if (!isOpen) return null;
const preview = generatePreview();
return (
<div
className="fixed inset-0 z-[70] flex items-center justify-center"
onMouseDown={(e) => {
if (e.target === e.currentTarget) {
handleClose();
}
}}
>
{/* Backdrop */}
<div
className={`absolute inset-0 bg-black/50 dark:bg-black/70${
isLinux() ? "" : " backdrop-blur-sm"
}`}
/>
{/* Modal */}
<div className="relative mx-4 flex max-h-[90vh] w-full max-w-2xl flex-col overflow-hidden rounded-xl bg-white shadow-lg dark:bg-gray-900">
{/* Header */}
<div className="flex items-center justify-between border-b border-gray-200 p-6 dark:border-gray-800">
<h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">
{t("mcp.wizard.title")}
</h2>
<button
type="button"
onClick={handleClose}
className="rounded-md p-1 text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-100"
aria-label={t("common.close")}
>
<X size={18} />
</button>
</div>
{/* Content */}
<div className="flex-1 min-h-0 space-y-4 overflow-auto p-6">
{/* Hint */}
<div className="rounded-lg border border-blue-200 bg-blue-50 p-3 dark:border-blue-800 dark:bg-blue-900/20">
<p className="text-sm text-blue-800 dark:text-blue-200">
{t("mcp.wizard.hint")}
</p>
</div>
{/* Form Fields */}
<div className="space-y-4">
{/* Type */}
<div>
<label className="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-100">
{t("mcp.wizard.type")} <span className="text-red-500">*</span>
</label>
<div className="flex gap-4">
<label className="inline-flex items-center gap-2 cursor-pointer">
<input
type="radio"
value="stdio"
checked={wizardType === "stdio"}
onChange={(e) =>
setWizardType(e.target.value as "stdio" | "sse")
}
className="w-4 h-4 text-emerald-500 bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700 focus:ring-emerald-500 dark:focus:ring-emerald-400 focus:ring-2"
/>
<span className="text-sm text-gray-900 dark:text-gray-100">
stdio
</span>
</label>
<label className="inline-flex items-center gap-2 cursor-pointer">
<input
type="radio"
value="sse"
checked={wizardType === "sse"}
onChange={(e) =>
setWizardType(e.target.value as "stdio" | "sse")
}
className="w-4 h-4 text-emerald-500 bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700 focus:ring-emerald-500 dark:focus:ring-emerald-400 focus:ring-2"
/>
<span className="text-sm text-gray-900 dark:text-gray-100">
sse
</span>
</label>
</div>
</div>
{/* Command */}
<div>
<label className="mb-1 block text-sm font-medium text-gray-900 dark:text-gray-100">
{t("mcp.wizard.command")}{" "}
<span className="text-red-500">*</span>
</label>
<input
type="text"
value={wizardCommand}
onChange={(e) => setWizardCommand(e.target.value)}
onKeyDown={handleKeyDown}
placeholder={t("mcp.wizard.commandPlaceholder")}
required
className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500/20 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-100"
/>
</div>
{/* Args */}
<div>
<label className="mb-1 block text-sm font-medium text-gray-900 dark:text-gray-100">
{t("mcp.wizard.args")}
</label>
<input
type="text"
value={wizardArgs}
onChange={(e) => setWizardArgs(e.target.value)}
onKeyDown={handleKeyDown}
placeholder={t("mcp.wizard.argsPlaceholder")}
className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500/20 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-100"
/>
</div>
{/* CWD */}
<div>
<label className="mb-1 block text-sm font-medium text-gray-900 dark:text-gray-100">
{t("mcp.wizard.cwd")}
</label>
<input
type="text"
value={wizardCwd}
onChange={(e) => setWizardCwd(e.target.value)}
onKeyDown={handleKeyDown}
placeholder={t("mcp.wizard.cwdPlaceholder")}
className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500/20 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-100"
/>
</div>
{/* Env */}
<div>
<label className="mb-1 block text-sm font-medium text-gray-900 dark:text-gray-100">
{t("mcp.wizard.env")}
</label>
<textarea
value={wizardEnv}
onChange={(e) => setWizardEnv(e.target.value)}
placeholder={t("mcp.wizard.envPlaceholder")}
rows={3}
className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-emerald-500/20 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-100 resize-y"
/>
</div>
</div>
{/* Preview */}
{(wizardCommand || wizardArgs || wizardCwd || wizardEnv) && (
<div className="space-y-2 border-t border-gray-200 pt-4 dark:border-gray-700">
<h3 className="text-sm font-medium text-gray-900 dark:text-gray-100">
{t("mcp.wizard.preview")}
</h3>
<pre className="overflow-x-auto rounded-lg bg-gray-50 p-3 text-xs font-mono text-gray-700 dark:bg-gray-800 dark:text-gray-300">
{preview}
</pre>
</div>
)}
</div>
{/* Footer */}
<div className="flex items-center justify-end gap-3 border-t border-gray-200 bg-gray-100 p-6 dark:border-gray-800 dark:bg-gray-800">
<button
type="button"
onClick={handleClose}
className="rounded-lg px-4 py-2 text-sm font-medium text-gray-500 transition-colors hover:bg-white hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-gray-100"
>
{t("common.cancel")}
</button>
<button
type="button"
onClick={handleApply}
className="flex items-center gap-2 rounded-lg bg-emerald-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-emerald-600 dark:bg-emerald-600 dark:hover:bg-emerald-700"
>
<Save className="h-4 w-4" />
{t("mcp.wizard.apply")}
</button>
</div>
</div>
</div>
);
};
export default McpWizardModal;

View File

@@ -265,6 +265,30 @@
"template": {
"fetch": "Quick Template: mcp-fetch"
},
"form": {
"title": "Server Title",
"titlePlaceholder": "my-mcp-server",
"description": "Description",
"descriptionPlaceholder": "Optional description",
"jsonConfig": "JSON Configuration",
"jsonPlaceholder": "{\n \"type\": \"stdio\",\n \"command\": \"uvx\",\n \"args\": [\"mcp-server-fetch\"]\n}",
"useWizard": "or use configuration wizard"
},
"wizard": {
"title": "MCP Configuration Wizard",
"hint": "Quickly configure MCP server and auto-generate JSON configuration",
"type": "Type",
"command": "Command",
"commandPlaceholder": "uvx",
"args": "Arguments",
"argsPlaceholder": "mcp-server-fetch",
"cwd": "Working Directory",
"cwdPlaceholder": "/path/to/project",
"env": "Environment Variables",
"envPlaceholder": "KEY=VALUE\n(one per line)",
"preview": "Configuration Preview",
"apply": "Apply Configuration"
},
"id": "Identifier (unique)",
"type": "Type",
"cwd": "Working Directory (optional)",
@@ -287,6 +311,7 @@
},
"error": {
"idRequired": "Please enter identifier",
"jsonInvalid": "Invalid JSON format",
"commandRequired": "Please enter command",
"saveFailed": "Save failed",
"deleteFailed": "Delete failed"

View File

@@ -265,6 +265,30 @@
"template": {
"fetch": "快速模板mcp-fetch"
},
"form": {
"title": "服务器标题",
"titlePlaceholder": "my-mcp-server",
"description": "描述",
"descriptionPlaceholder": "可选的描述信息",
"jsonConfig": "JSON 配置",
"jsonPlaceholder": "{\n \"type\": \"stdio\",\n \"command\": \"uvx\",\n \"args\": [\"mcp-server-fetch\"]\n}",
"useWizard": "或者使用配置向导"
},
"wizard": {
"title": "MCP 配置向导",
"hint": "快速配置 MCP 服务器,自动生成 JSON 配置",
"type": "类型",
"command": "命令",
"commandPlaceholder": "uvx",
"args": "参数",
"argsPlaceholder": "mcp-server-fetch",
"cwd": "工作目录",
"cwdPlaceholder": "/path/to/project",
"env": "环境变量",
"envPlaceholder": "KEY=VALUE\n(一行一个)",
"preview": "配置预览",
"apply": "应用配置"
},
"id": "标识 (唯一)",
"type": "类型",
"cwd": "工作目录 (可选)",
@@ -287,6 +311,7 @@
},
"error": {
"idRequired": "请填写标识",
"jsonInvalid": "JSON 格式错误,请检查",
"commandRequired": "请填写命令",
"saveFailed": "保存失败",
"deleteFailed": "删除失败"