refactor(mcp): switch to user-level config ~/.claude.json and remove project-level logic

- Read/write ~/.claude.json (preserve unknown fields) for mcpServers
- Remove settings.local.json and mcp.json handling
- Drop enableAllProjectMcpServers command and UI toggle
- Update types, Tauri APIs, and MCP panel to reflect new status fields
- Keep atomic write and command validation behaviors
This commit is contained in:
Jason
2025-10-08 23:22:19 +08:00
parent e0e84ca58a
commit 96a4b4fe95
9 changed files with 30 additions and 131 deletions

View File

@@ -4,29 +4,21 @@ use std::env;
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use crate::config::{atomic_write, get_claude_config_dir}; use crate::config::atomic_write;
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct McpStatus { pub struct McpStatus {
pub settings_local_path: String, pub user_config_path: String,
pub settings_local_exists: bool, pub user_config_exists: bool,
pub enable_all_project_mcp_servers: bool,
pub mcp_json_path: String,
pub mcp_json_exists: bool,
pub server_count: usize, pub server_count: usize,
} }
fn claude_dir() -> PathBuf { fn user_config_path() -> PathBuf {
get_claude_config_dir() // 用户级 MCP 配置文件:~/.claude.json
} dirs::home_dir()
.expect("无法获取用户主目录")
fn settings_local_path() -> PathBuf { .join(".claude.json")
claude_dir().join("settings.local.json")
}
fn mcp_json_path() -> PathBuf {
claude_dir().join("mcp.json")
} }
fn read_json_value(path: &Path) -> Result<Value, String> { fn read_json_value(path: &Path) -> Result<Value, String> {
@@ -50,20 +42,9 @@ fn write_json_value(path: &Path, value: &Value) -> Result<(), String> {
} }
pub fn get_mcp_status() -> Result<McpStatus, String> { pub fn get_mcp_status() -> Result<McpStatus, String> {
let settings_local = settings_local_path(); let path = user_config_path();
let mcp_path = mcp_json_path(); let (exists, count) = if path.exists() {
let v = read_json_value(&path)?;
let mut enable = false;
if settings_local.exists() {
let v = read_json_value(&settings_local)?;
enable = v
.get("enableAllProjectMcpServers")
.and_then(|x| x.as_bool())
.unwrap_or(false);
}
let (exists, count) = if mcp_path.exists() {
let v = read_json_value(&mcp_path)?;
let servers = v.get("mcpServers").and_then(|x| x.as_object()); let servers = v.get("mcpServers").and_then(|x| x.as_object());
(true, servers.map(|m| m.len()).unwrap_or(0)) (true, servers.map(|m| m.len()).unwrap_or(0))
} else { } else {
@@ -71,17 +52,14 @@ pub fn get_mcp_status() -> Result<McpStatus, String> {
}; };
Ok(McpStatus { Ok(McpStatus {
settings_local_path: settings_local.to_string_lossy().to_string(), user_config_path: path.to_string_lossy().to_string(),
settings_local_exists: settings_local.exists(), user_config_exists: exists,
enable_all_project_mcp_servers: enable,
mcp_json_path: mcp_path.to_string_lossy().to_string(),
mcp_json_exists: exists,
server_count: count, server_count: count,
}) })
} }
pub fn read_mcp_json() -> Result<Option<String>, String> { pub fn read_mcp_json() -> Result<Option<String>, String> {
let path = mcp_json_path(); let path = user_config_path();
if !path.exists() { if !path.exists() {
return Ok(None); return Ok(None);
} }
@@ -90,28 +68,6 @@ pub fn read_mcp_json() -> Result<Option<String>, String> {
Ok(Some(content)) Ok(Some(content))
} }
pub fn set_enable_all_projects(enable: bool) -> Result<bool, String> {
let path = settings_local_path();
let mut v = if path.exists() { read_json_value(&path)? } else { serde_json::json!({}) };
let current = v
.get("enableAllProjectMcpServers")
.and_then(|x| x.as_bool())
.unwrap_or(false);
if current == enable && path.exists() {
return Ok(false);
}
if let Some(obj) = v.as_object_mut() {
obj.insert(
"enableAllProjectMcpServers".to_string(),
Value::Bool(enable),
);
}
write_json_value(&path, &v)?;
Ok(true)
}
pub fn upsert_mcp_server(id: &str, spec: Value) -> Result<bool, String> { pub fn upsert_mcp_server(id: &str, spec: Value) -> Result<bool, String> {
if id.trim().is_empty() { if id.trim().is_empty() {
return Err("MCP 服务器 ID 不能为空".into()); return Err("MCP 服务器 ID 不能为空".into());
@@ -132,7 +88,7 @@ pub fn upsert_mcp_server(id: &str, spec: Value) -> Result<bool, String> {
return Err("MCP 服务器缺少 command".into()); return Err("MCP 服务器缺少 command".into());
} }
let path = mcp_json_path(); let path = user_config_path();
let mut root = if path.exists() { read_json_value(&path)? } else { serde_json::json!({}) }; let mut root = if path.exists() { read_json_value(&path)? } else { serde_json::json!({}) };
// 确保 mcpServers 对象存在 // 确保 mcpServers 对象存在
@@ -163,7 +119,7 @@ pub fn delete_mcp_server(id: &str) -> Result<bool, String> {
if id.trim().is_empty() { if id.trim().is_empty() {
return Err("MCP 服务器 ID 不能为空".into()); return Err("MCP 服务器 ID 不能为空".into());
} }
let path = mcp_json_path(); let path = user_config_path();
if !path.exists() { if !path.exists() {
return Ok(false); return Ok(false);
} }
@@ -215,4 +171,3 @@ pub fn validate_command_in_path(cmd: &str) -> Result<bool, String> {
} }
Ok(false) Ok(false)
} }

View File

@@ -676,11 +676,6 @@ pub async fn read_claude_mcp_config() -> Result<Option<String>, String> {
claude_mcp::read_mcp_json() claude_mcp::read_mcp_json()
} }
/// 设置 enableAllProjectMcpServers 开关
#[tauri::command]
pub async fn set_claude_mcp_enable_all_projects(enable: bool) -> Result<bool, String> {
claude_mcp::set_enable_all_projects(enable)
}
/// 新增或更新一个 MCP 服务器条目 /// 新增或更新一个 MCP 服务器条目
#[tauri::command] #[tauri::command]

View File

@@ -425,7 +425,6 @@ pub fn run() {
// Claude MCP management // Claude MCP management
commands::get_claude_mcp_status, commands::get_claude_mcp_status,
commands::read_claude_mcp_config, commands::read_claude_mcp_config,
commands::set_claude_mcp_enable_all_projects,
commands::upsert_claude_mcp_server, commands::upsert_claude_mcp_server,
commands::delete_claude_mcp_server, commands::delete_claude_mcp_server,
commands::validate_mcp_command, commands::validate_mcp_command,

View File

@@ -77,17 +77,7 @@ const McpPanel: React.FC<McpPanelProps> = ({ onClose, onNotify }) => {
reload(); reload();
}, []); }, []);
const handleToggleEnable = async (enable: boolean) => { // 用户级 MCP不需要项目级启用开关
try {
const changed = await window.api.setClaudeMcpEnableAllProjects(enable);
if (changed) {
await reload();
onNotify?.(t("mcp.notice.restartClaude"), "success", 2000);
}
} catch (e: any) {
onNotify?.(e?.message || t("mcp.error.toggleFailed"), "error", 5000);
}
};
const resetForm = () => { const resetForm = () => {
setEditingId(null); setEditingId(null);
@@ -200,24 +190,13 @@ const McpPanel: React.FC<McpPanelProps> = ({ onClose, onNotify }) => {
<div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-6"> <div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-6">
{/* Left: status & list */} {/* Left: status & list */}
<div> <div>
<div className="flex items-center justify-between mb-4"> <div className="mb-4">
<div> <div className="text-sm text-gray-500 dark:text-gray-400">
<div className="text-sm text-gray-500 dark:text-gray-400"> {t("mcp.userLevelPath")}
{t("mcp.enableProject")} </div>
</div> <div className="text-xs text-gray-400 dark:text-gray-500 break-all">
<div className="text-xs text-gray-400 dark:text-gray-500"> {status?.userConfigPath}
{status?.settingsLocalPath}
</div>
</div> </div>
<label className="inline-flex items-center cursor-pointer">
<input
type="checkbox"
className="sr-only peer"
checked={!!status?.enableAllProjectMcpServers}
onChange={(e) => handleToggleEnable(e.target.checked)}
/>
<div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-emerald-500 relative" />
</label>
</div> </div>
<div className="flex items-center gap-3 mb-3"> <div className="flex items-center gap-3 mb-3">
@@ -233,12 +212,6 @@ const McpPanel: React.FC<McpPanelProps> = ({ onClose, onNotify }) => {
> >
<Wrench size={16} /> {t("mcp.template.fetch")} <Wrench size={16} /> {t("mcp.template.fetch")}
</button> </button>
<button
onClick={() => window.api.openConfigFolder("claude")}
className="inline-flex items-center gap-2 px-3 py-2 text-sm font-medium rounded-md bg-gray-100 text-gray-700 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700"
>
{t("mcp.openFolder")}
</button>
</div> </div>
<div className="border border-gray-200 dark:border-gray-800 rounded-lg overflow-hidden"> <div className="border border-gray-200 dark:border-gray-800 rounded-lg overflow-hidden">
@@ -246,11 +219,7 @@ const McpPanel: React.FC<McpPanelProps> = ({ onClose, onNotify }) => {
<span> <span>
{t("mcp.serverList")} ({status?.serverCount || 0}) {t("mcp.serverList")} ({status?.serverCount || 0})
</span> </span>
{status?.mcpJsonExists ? ( <span className="text-gray-400">{status?.userConfigPath}</span>
<span className="text-gray-400">{status?.mcpJsonPath}</span>
) : (
<span className="text-gray-400">mcp.json</span>
)}
</div> </div>
<div className="max-h-64 overflow-auto divide-y divide-gray-200 dark:divide-gray-800"> <div className="max-h-64 overflow-auto divide-y divide-gray-200 dark:divide-gray-800">
{loading && ( {loading && (
@@ -403,4 +372,3 @@ const McpPanel: React.FC<McpPanelProps> = ({ onClose, onNotify }) => {
}; };
export default McpPanel; export default McpPanel;

View File

@@ -251,8 +251,7 @@
}, },
"mcp": { "mcp": {
"title": "MCP Management", "title": "MCP Management",
"enableProject": "Enable project-level MCP servers", "userLevelPath": "User-level MCP path",
"openFolder": "Open ~/.claude",
"serverList": "Servers", "serverList": "Servers",
"loading": "Loading...", "loading": "Loading...",
"empty": "No MCP servers", "empty": "No MCP servers",
@@ -281,7 +280,6 @@
"templateAdded": "Template added" "templateAdded": "Template added"
}, },
"error": { "error": {
"toggleFailed": "Failed to update toggle",
"idRequired": "Please enter identifier", "idRequired": "Please enter identifier",
"commandRequired": "Please enter command", "commandRequired": "Please enter command",
"saveFailed": "Save failed", "saveFailed": "Save failed",

View File

@@ -251,8 +251,7 @@
}, },
"mcp": { "mcp": {
"title": "MCP 管理", "title": "MCP 管理",
"enableProject": "启用项目级 MCP 服务器", "userLevelPath": "用户级 MCP 配置路径",
"openFolder": "打开 ~/.claude",
"serverList": "服务器列表", "serverList": "服务器列表",
"loading": "加载中...", "loading": "加载中...",
"empty": "暂无 MCP 服务器", "empty": "暂无 MCP 服务器",
@@ -281,7 +280,6 @@
"templateAdded": "已添加模板" "templateAdded": "已添加模板"
}, },
"error": { "error": {
"toggleFailed": "更新开关失败",
"idRequired": "请填写标识", "idRequired": "请填写标识",
"commandRequired": "请填写命令", "commandRequired": "请填写命令",
"saveFailed": "保存失败", "saveFailed": "保存失败",

View File

@@ -279,7 +279,7 @@ export const tauriAPI = {
} }
}, },
// Claude MCP获取状态settings.local.json + mcp.json // Claude MCP获取状态用户级 ~/.claude.json
getClaudeMcpStatus: async (): Promise<McpStatus> => { getClaudeMcpStatus: async (): Promise<McpStatus> => {
try { try {
return await invoke<McpStatus>("get_claude_mcp_status"); return await invoke<McpStatus>("get_claude_mcp_status");
@@ -289,7 +289,7 @@ export const tauriAPI = {
} }
}, },
// Claude MCP读取 mcp.json 文本 // Claude MCP读取 ~/.claude.json 文本
readClaudeMcpConfig: async (): Promise<string | null> => { readClaudeMcpConfig: async (): Promise<string | null> => {
try { try {
return await invoke<string | null>("read_claude_mcp_config"); return await invoke<string | null>("read_claude_mcp_config");
@@ -299,16 +299,6 @@ export const tauriAPI = {
} }
}, },
// Claude MCP设置项目级启用开关
setClaudeMcpEnableAllProjects: async (enable: boolean): Promise<boolean> => {
try {
return await invoke<boolean>("set_claude_mcp_enable_all_projects", { enable });
} catch (error) {
console.error("写入 settings.local.json 失败:", error);
throw error;
}
},
// Claude MCP新增/更新服务器定义 // Claude MCP新增/更新服务器定义
upsertClaudeMcpServer: async ( upsertClaudeMcpServer: async (
id: string, id: string,

View File

@@ -65,10 +65,7 @@ export interface McpServer {
// MCP 配置状态 // MCP 配置状态
export interface McpStatus { export interface McpStatus {
settingsLocalPath: string; userConfigPath: string;
settingsLocalExists: boolean; userConfigExists: boolean;
enableAllProjectMcpServers: boolean;
mcpJsonPath: string;
mcpJsonExists: boolean;
serverCount: number; serverCount: number;
} }

1
src/vite-env.d.ts vendored
View File

@@ -64,7 +64,6 @@ declare global {
// Claude MCP // Claude MCP
getClaudeMcpStatus: () => Promise<McpStatus>; getClaudeMcpStatus: () => Promise<McpStatus>;
readClaudeMcpConfig: () => Promise<string | null>; readClaudeMcpConfig: () => Promise<string | null>;
setClaudeMcpEnableAllProjects: (enable: boolean) => Promise<boolean>;
upsertClaudeMcpServer: ( upsertClaudeMcpServer: (
id: string, id: string,
spec: Record<string, any>, spec: Record<string, any>,