1use serde_json::{json, Value};
2use std::collections::HashMap;
3
4use crate::app_config::{AppType, McpConfig, MultiAppConfig};
5use crate::error::AppError;
6
7fn validate_server_spec(spec: &Value) -> Result<(), AppError> {
9 if !spec.is_object() {
10 return Err(AppError::McpValidation(
11 "MCP 服务器连接定义必须为 JSON 对象".into(),
12 ));
13 }
14 if let Some(type_val) = spec.get("type") {
15 if !type_val.is_string() {
16 return Err(AppError::McpValidation(
17 "MCP 服务器 type 必须是字符串".into(),
18 ));
19 }
20 }
21 let t_opt = spec.get("type").and_then(|x| x.as_str());
22 let is_stdio = t_opt.map(|t| t == "stdio").unwrap_or(true);
24 let is_http = t_opt.map(|t| t == "http").unwrap_or(false);
25 let is_sse = t_opt.map(|t| t == "sse").unwrap_or(false);
26
27 if !(is_stdio || is_http || is_sse) {
28 return Err(AppError::McpValidation(
29 "MCP 服务器 type 必须是 'stdio'、'http' 或 'sse'(或省略表示 stdio)".into(),
30 ));
31 }
32
33 if is_stdio {
34 let cmd = spec.get("command").and_then(|x| x.as_str()).unwrap_or("");
35 if cmd.trim().is_empty() {
36 return Err(AppError::McpValidation(
37 "stdio 类型的 MCP 服务器缺少 command 字段".into(),
38 ));
39 }
40 }
41 if is_http {
42 let url = spec.get("url").and_then(|x| x.as_str()).unwrap_or("");
43 if url.trim().is_empty() {
44 return Err(AppError::McpValidation(
45 "http 类型的 MCP 服务器缺少 url 字段".into(),
46 ));
47 }
48 }
49 if is_sse {
50 let url = spec.get("url").and_then(|x| x.as_str()).unwrap_or("");
51 if url.trim().is_empty() {
52 return Err(AppError::McpValidation(
53 "sse 类型的 MCP 服务器缺少 url 字段".into(),
54 ));
55 }
56 }
57 Ok(())
58}
59
60#[allow(dead_code)] fn validate_mcp_entry(entry: &Value) -> Result<(), AppError> {
62 let obj = entry
63 .as_object()
64 .ok_or_else(|| AppError::McpValidation("MCP 服务器条目必须为 JSON 对象".into()))?;
65
66 let server = obj
67 .get("server")
68 .ok_or_else(|| AppError::McpValidation("MCP 服务器条目缺少 server 字段".into()))?;
69 validate_server_spec(server)?;
70
71 for key in ["name", "description", "homepage", "docs"] {
72 if let Some(val) = obj.get(key) {
73 if !val.is_string() {
74 return Err(AppError::McpValidation(format!(
75 "MCP 服务器 {key} 必须为字符串"
76 )));
77 }
78 }
79 }
80
81 if let Some(tags) = obj.get("tags") {
82 let arr = tags
83 .as_array()
84 .ok_or_else(|| AppError::McpValidation("MCP 服务器 tags 必须为字符串数组".into()))?;
85 if !arr.iter().all(|item| item.is_string()) {
86 return Err(AppError::McpValidation(
87 "MCP 服务器 tags 必须为字符串数组".into(),
88 ));
89 }
90 }
91
92 if let Some(enabled) = obj.get("enabled") {
93 if !enabled.is_boolean() {
94 return Err(AppError::McpValidation(
95 "MCP 服务器 enabled 必须为布尔值".into(),
96 ));
97 }
98 }
99
100 Ok(())
101}
102
103fn normalize_server_keys(map: &mut HashMap<String, Value>) -> usize {
104 let mut change_count = 0usize;
105 let mut renames: Vec<(String, String)> = Vec::new();
106
107 for (key_ref, value) in map.iter_mut() {
108 let key = key_ref.clone();
109 let Some(obj) = value.as_object_mut() else {
110 continue;
111 };
112
113 let id_value = obj.get("id").cloned();
114
115 let target_id: String;
116
117 match id_value {
118 Some(id_val) => match id_val.as_str() {
119 Some(id_str) => {
120 let trimmed = id_str.trim();
121 if trimmed.is_empty() {
122 obj.insert("id".into(), json!(key.clone()));
123 change_count += 1;
124 target_id = key.clone();
125 } else {
126 if trimmed != id_str {
127 obj.insert("id".into(), json!(trimmed));
128 change_count += 1;
129 }
130 target_id = trimmed.to_string();
131 }
132 }
133 None => {
134 obj.insert("id".into(), json!(key.clone()));
135 change_count += 1;
136 target_id = key.clone();
137 }
138 },
139 None => {
140 obj.insert("id".into(), json!(key.clone()));
141 change_count += 1;
142 target_id = key.clone();
143 }
144 }
145
146 if target_id != key {
147 renames.push((key, target_id));
148 }
149 }
150
151 for (old_key, new_key) in renames {
152 if old_key == new_key {
153 continue;
154 }
155 if map.contains_key(&new_key) {
156 log::warn!("MCP 条目 '{old_key}' 的内部 id '{new_key}' 与现有键冲突,回退为原键");
157 if let Some(value) = map.get_mut(&old_key) {
158 if let Some(obj) = value.as_object_mut() {
159 if obj
160 .get("id")
161 .and_then(|v| v.as_str())
162 .map(|s| s != old_key)
163 .unwrap_or(true)
164 {
165 obj.insert("id".into(), json!(old_key.clone()));
166 change_count += 1;
167 }
168 }
169 }
170 continue;
171 }
172 if let Some(mut value) = map.remove(&old_key) {
173 if let Some(obj) = value.as_object_mut() {
174 obj.insert("id".into(), json!(new_key.clone()));
175 }
176 log::info!("MCP 条目键名已自动修复: '{old_key}' -> '{new_key}'");
177 map.insert(new_key, value);
178 change_count += 1;
179 }
180 }
181
182 change_count
183}
184
185pub fn normalize_servers_for(config: &mut MultiAppConfig, app: &AppType) -> usize {
186 let servers = &mut config.mcp_for_mut(app).servers;
187 normalize_server_keys(servers)
188}
189
190fn extract_server_spec(entry: &Value) -> Result<Value, AppError> {
191 let obj = entry
192 .as_object()
193 .ok_or_else(|| AppError::McpValidation("MCP 服务器条目必须为 JSON 对象".into()))?;
194 let server = obj
195 .get("server")
196 .ok_or_else(|| AppError::McpValidation("MCP 服务器条目缺少 server 字段".into()))?;
197
198 if !server.is_object() {
199 return Err(AppError::McpValidation(
200 "MCP 服务器 server 字段必须为 JSON 对象".into(),
201 ));
202 }
203
204 Ok(server.clone())
205}
206
207fn collect_enabled_servers(cfg: &McpConfig) -> HashMap<String, Value> {
209 let mut out = HashMap::new();
210 for (id, entry) in cfg.servers.iter() {
211 let enabled = entry
212 .get("enabled")
213 .and_then(|v| v.as_bool())
214 .unwrap_or(false);
215 if !enabled {
216 continue;
217 }
218 match extract_server_spec(entry) {
219 Ok(spec) => {
220 out.insert(id.clone(), spec);
221 }
222 Err(err) => {
223 log::warn!("跳过无效的 MCP 条目 '{id}': {err}");
224 }
225 }
226 }
227 out
228}
229
230#[allow(dead_code)] pub fn get_servers_snapshot_for(
232 config: &mut MultiAppConfig,
233 app: &AppType,
234) -> (HashMap<String, Value>, usize) {
235 let normalized = normalize_servers_for(config, app);
236 let mut snapshot = config.mcp_for(app).servers.clone();
237 snapshot.retain(|id, value| {
238 let Some(obj) = value.as_object_mut() else {
239 log::warn!("跳过无效的 MCP 条目 '{id}': 必须为 JSON 对象");
240 return false;
241 };
242
243 obj.entry(String::from("id")).or_insert(json!(id));
244
245 match validate_mcp_entry(value) {
246 Ok(()) => true,
247 Err(err) => {
248 log::error!("config.json 中存在无效的 MCP 条目 '{id}': {err}");
249 false
250 }
251 }
252 });
253 (snapshot, normalized)
254}
255
256#[allow(dead_code)] pub fn upsert_in_config_for(
258 config: &mut MultiAppConfig,
259 app: &AppType,
260 id: &str,
261 spec: Value,
262) -> Result<bool, AppError> {
263 if id.trim().is_empty() {
264 return Err(AppError::InvalidInput("MCP 服务器 ID 不能为空".into()));
265 }
266 normalize_servers_for(config, app);
267 validate_mcp_entry(&spec)?;
268
269 let mut entry_obj = spec
270 .as_object()
271 .cloned()
272 .ok_or_else(|| AppError::McpValidation("MCP 服务器条目必须为 JSON 对象".into()))?;
273 if let Some(existing_id) = entry_obj.get("id") {
274 let Some(existing_id_str) = existing_id.as_str() else {
275 return Err(AppError::McpValidation("MCP 服务器 id 必须为字符串".into()));
276 };
277 if existing_id_str != id {
278 return Err(AppError::McpValidation(format!(
279 "MCP 服务器条目中的 id '{existing_id_str}' 与参数 id '{id}' 不一致"
280 )));
281 }
282 } else {
283 entry_obj.insert(String::from("id"), json!(id));
284 }
285
286 let value = Value::Object(entry_obj);
287
288 let servers = &mut config.mcp_for_mut(app).servers;
289 let before = servers.get(id).cloned();
290 servers.insert(id.to_string(), value);
291
292 Ok(before.is_none())
293}
294
295#[allow(dead_code)] pub fn delete_in_config_for(
297 config: &mut MultiAppConfig,
298 app: &AppType,
299 id: &str,
300) -> Result<bool, AppError> {
301 if id.trim().is_empty() {
302 return Err(AppError::InvalidInput("MCP 服务器 ID 不能为空".into()));
303 }
304 normalize_servers_for(config, app);
305 let existed = config.mcp_for_mut(app).servers.remove(id).is_some();
306 Ok(existed)
307}
308
309#[allow(dead_code)] pub fn set_enabled_flag_for(
312 config: &mut MultiAppConfig,
313 app: &AppType,
314 id: &str,
315 enabled: bool,
316) -> Result<bool, AppError> {
317 if id.trim().is_empty() {
318 return Err(AppError::InvalidInput("MCP 服务器 ID 不能为空".into()));
319 }
320 normalize_servers_for(config, app);
321 if let Some(spec) = config.mcp_for_mut(app).servers.get_mut(id) {
322 let mut obj = spec
324 .as_object()
325 .cloned()
326 .ok_or_else(|| AppError::McpValidation("MCP 服务器定义必须为 JSON 对象".into()))?;
327 obj.insert("enabled".into(), json!(enabled));
328 *spec = Value::Object(obj);
329 } else {
330 return Ok(false);
332 }
333
334 Ok(true)
335}
336
337pub fn sync_enabled_to_claude(config: &MultiAppConfig) -> Result<(), AppError> {
339 if !crate::sync_policy::should_sync_live(&AppType::Claude) {
340 return Ok(());
341 }
342 let enabled = collect_enabled_servers(&config.mcp.claude);
343 crate::claude_mcp::set_mcp_servers_map(&enabled)
344}
345
346pub fn import_from_claude(config: &mut MultiAppConfig) -> Result<usize, AppError> {
349 use crate::app_config::{McpApps, McpServer};
350
351 let text_opt = crate::claude_mcp::read_mcp_json()?;
352 let Some(text) = text_opt else { return Ok(0) };
353
354 let v: Value = serde_json::from_str(&text)
355 .map_err(|e| AppError::McpValidation(format!("解析 ~/.claude.json 失败: {e}")))?;
356 let Some(map) = v.get("mcpServers").and_then(|x| x.as_object()) else {
357 return Ok(0);
358 };
359
360 if config.mcp.servers.is_none() {
362 config.mcp.servers = Some(HashMap::new());
363 }
364 let servers = config.mcp.servers.as_mut().unwrap();
365
366 let mut changed = 0;
367 let mut errors = Vec::new();
368
369 for (id, spec) in map.iter() {
370 if let Err(e) = validate_server_spec(spec) {
372 log::warn!("跳过无效 MCP 服务器 '{id}': {e}");
373 errors.push(format!("{id}: {e}"));
374 continue;
375 }
376
377 if let Some(existing) = servers.get_mut(id.as_str()) {
378 if !existing.apps.claude {
380 existing.apps.claude = true;
381 changed += 1;
382 log::info!("MCP 服务器 '{id}' 已启用 Claude 应用");
383 }
384 } else {
385 servers.insert(
387 id.clone(),
388 McpServer {
389 id: id.clone(),
390 name: id.clone(),
391 server: spec.clone(),
392 apps: McpApps {
393 claude: true,
394 codex: false,
395 gemini: false,
396 opencode: false,
397 openclaw: false,
398 hermes: false,
399 },
400 description: None,
401 homepage: None,
402 docs: None,
403 tags: Vec::new(),
404 },
405 );
406 changed += 1;
407 log::info!("导入新 MCP 服务器 '{id}'");
408 }
409 }
410
411 if !errors.is_empty() {
412 log::warn!("导入完成,但有 {} 项失败: {:?}", errors.len(), errors);
413 }
414
415 Ok(changed)
416}
417
418pub fn import_from_codex(config: &mut MultiAppConfig) -> Result<usize, AppError> {
426 use crate::app_config::{McpApps, McpServer};
427
428 let text = crate::codex_config::read_and_validate_codex_config_text()?;
429 if text.trim().is_empty() {
430 return Ok(0);
431 }
432
433 let root: toml::Table = toml::from_str(&text)
434 .map_err(|e| AppError::McpValidation(format!("解析 ~/.codex/config.toml 失败: {e}")))?;
435
436 if config.mcp.servers.is_none() {
438 config.mcp.servers = Some(HashMap::new());
439 }
440 let servers = config.mcp.servers.as_mut().unwrap();
441
442 let mut changed_total = 0usize;
443
444 let mut import_servers_tbl = |servers_tbl: &toml::value::Table| {
446 let mut changed = 0usize;
447 for (id, entry_val) in servers_tbl.iter() {
448 let Some(entry_tbl) = entry_val.as_table() else {
449 continue;
450 };
451
452 let toml_to_json = |toml_val: &toml::Value| -> Option<serde_json::Value> {
453 match toml_val {
454 toml::Value::String(s) => Some(json!(s)),
455 toml::Value::Integer(i) => Some(json!(i)),
456 toml::Value::Float(f) => Some(json!(f)),
457 toml::Value::Boolean(b) => Some(json!(b)),
458 toml::Value::Array(arr) => {
459 let json_arr: Vec<serde_json::Value> = arr
460 .iter()
461 .filter_map(|item| match item {
462 toml::Value::String(s) => Some(json!(s)),
463 toml::Value::Integer(i) => Some(json!(i)),
464 toml::Value::Float(f) => Some(json!(f)),
465 toml::Value::Boolean(b) => Some(json!(b)),
466 _ => None,
467 })
468 .collect();
469 if json_arr.is_empty() {
470 None
471 } else {
472 Some(serde_json::Value::Array(json_arr))
473 }
474 }
475 toml::Value::Table(tbl) => {
476 let mut json_obj = serde_json::Map::new();
477 for (k, v) in tbl.iter() {
478 if let Some(s) = v.as_str() {
479 json_obj.insert(k.clone(), json!(s));
480 }
481 }
482 if json_obj.is_empty() {
483 None
484 } else {
485 Some(serde_json::Value::Object(json_obj))
486 }
487 }
488 toml::Value::Datetime(_) => None,
489 }
490 };
491
492 let typ = if entry_tbl.contains_key("type") {
495 entry_tbl.get("type").and_then(|v| v.as_str())
496 } else {
497 entry_tbl
498 .get("url")
499 .and_then(|v| v.as_str())
500 .filter(|url| !url.trim().is_empty())
501 .map(|_| "http")
502 .or(Some("stdio"))
503 };
504
505 let mut spec = serde_json::Map::new();
507 if let Some(typ) = typ {
508 spec.insert("type".into(), json!(typ));
509 } else if let Some(type_val) = entry_tbl.get("type").and_then(toml_to_json) {
510 spec.insert("type".into(), type_val);
511 }
512
513 let core_fields = match typ {
515 Some("stdio") => vec!["type", "command", "args", "env", "cwd"],
516 Some("http") | Some("sse") => vec!["type", "url", "http_headers"],
517 _ => vec!["type"],
518 };
519
520 match typ {
522 Some("stdio") => {
523 if let Some(cmd) = entry_tbl.get("command").and_then(|v| v.as_str()) {
524 spec.insert("command".into(), json!(cmd));
525 }
526 if let Some(args) = entry_tbl.get("args").and_then(|v| v.as_array()) {
527 let arr = args
528 .iter()
529 .filter_map(|x| x.as_str())
530 .map(|s| json!(s))
531 .collect::<Vec<_>>();
532 if !arr.is_empty() {
533 spec.insert("args".into(), serde_json::Value::Array(arr));
534 }
535 }
536 if let Some(cwd) = entry_tbl.get("cwd").and_then(|v| v.as_str()) {
537 if !cwd.trim().is_empty() {
538 spec.insert("cwd".into(), json!(cwd));
539 }
540 }
541 if let Some(env_tbl) = entry_tbl.get("env").and_then(|v| v.as_table()) {
542 let mut env_json = serde_json::Map::new();
543 for (k, v) in env_tbl.iter() {
544 if let Some(sv) = v.as_str() {
545 env_json.insert(k.clone(), json!(sv));
546 }
547 }
548 if !env_json.is_empty() {
549 spec.insert("env".into(), serde_json::Value::Object(env_json));
550 }
551 }
552 }
553 Some("http") | Some("sse") => {
554 if let Some(url) = entry_tbl.get("url").and_then(|v| v.as_str()) {
555 spec.insert("url".into(), json!(url));
556 }
557 let headers_tbl = entry_tbl
559 .get("http_headers")
560 .and_then(|v| v.as_table())
561 .or_else(|| entry_tbl.get("headers").and_then(|v| v.as_table()));
562
563 if let Some(headers_tbl) = headers_tbl {
564 let mut headers_json = serde_json::Map::new();
565 for (k, v) in headers_tbl.iter() {
566 if let Some(sv) = v.as_str() {
567 headers_json.insert(k.clone(), json!(sv));
568 }
569 }
570 if !headers_json.is_empty() {
571 spec.insert("headers".into(), serde_json::Value::Object(headers_json));
572 }
573 }
574 }
575 _ => {}
576 }
577
578 for (key, toml_val) in entry_tbl.iter() {
580 if core_fields.contains(&key.as_str()) {
582 continue;
583 }
584
585 let json_val = toml_to_json(toml_val);
587
588 if let Some(val) = json_val {
589 spec.insert(key.clone(), val);
590 log::debug!("导入扩展字段 '{key}' = {toml_val:?}");
591 } else {
592 log::debug!("跳过复杂字段 '{key}' (TOML → JSON)");
593 }
594 }
595
596 let spec_v = serde_json::Value::Object(spec);
597
598 if let Err(e) = validate_server_spec(&spec_v) {
600 log::warn!("跳过无效 Codex MCP 项 '{id}': {e}");
601 continue;
602 }
603
604 if let Some(existing) = servers.get_mut(id) {
605 if !existing.apps.codex {
607 existing.apps.codex = true;
608 changed += 1;
609 log::info!("MCP 服务器 '{id}' 已启用 Codex 应用");
610 }
611 } else {
612 servers.insert(
614 id.clone(),
615 McpServer {
616 id: id.clone(),
617 name: id.clone(),
618 server: spec_v,
619 apps: McpApps {
620 claude: false,
621 codex: true,
622 gemini: false,
623 opencode: false,
624 openclaw: false,
625 hermes: false,
626 },
627 description: None,
628 homepage: None,
629 docs: None,
630 tags: Vec::new(),
631 },
632 );
633 changed += 1;
634 log::info!("导入新 MCP 服务器 '{id}'");
635 }
636 }
637 changed
638 };
639
640 if let Some(mcp_val) = root.get("mcp") {
642 if let Some(mcp_tbl) = mcp_val.as_table() {
643 if let Some(servers_val) = mcp_tbl.get("servers") {
644 if let Some(servers_tbl) = servers_val.as_table() {
645 changed_total += import_servers_tbl(servers_tbl);
646 }
647 }
648 }
649 }
650
651 if let Some(servers_val) = root.get("mcp_servers") {
653 if let Some(servers_tbl) = servers_val.as_table() {
654 changed_total += import_servers_tbl(servers_tbl);
655 }
656 }
657
658 Ok(changed_total)
659}
660
661pub fn read_codex_live_mcp_servers_map() -> Result<HashMap<String, Value>, AppError> {
667 let text = crate::codex_config::read_and_validate_codex_config_text()?;
668 if text.trim().is_empty() {
669 return Ok(HashMap::new());
670 }
671
672 let root: toml::Table = toml::from_str(&text)
673 .map_err(|e| AppError::McpValidation(format!("解析 ~/.codex/config.toml 失败: {e}")))?;
674
675 let mut servers = HashMap::new();
676
677 if let Some(servers_tbl) = root
678 .get("mcp")
679 .and_then(|mcp_val| mcp_val.as_table())
680 .and_then(|mcp_tbl| mcp_tbl.get("servers"))
681 .and_then(|servers_val| servers_val.as_table())
682 {
683 collect_codex_live_mcp_servers(servers_tbl, &mut servers);
684 }
685
686 if let Some(servers_tbl) = root.get("mcp_servers").and_then(|value| value.as_table()) {
687 collect_codex_live_mcp_servers(servers_tbl, &mut servers);
688 }
689
690 Ok(servers)
691}
692
693fn collect_codex_live_mcp_servers(
694 servers_tbl: &toml::value::Table,
695 servers: &mut HashMap<String, Value>,
696) {
697 for (id, entry_val) in servers_tbl.iter() {
698 let Some(entry_tbl) = entry_val.as_table() else {
699 continue;
700 };
701
702 let spec_v = codex_live_mcp_entry_to_json_spec(entry_tbl);
703 if let Err(e) = validate_server_spec(&spec_v) {
704 log::warn!("跳过无效 Codex MCP 项 '{id}': {e}");
705 continue;
706 }
707
708 servers.insert(id.clone(), spec_v);
709 }
710}
711
712fn toml_value_to_json(toml_val: &toml::Value) -> Option<Value> {
713 match toml_val {
714 toml::Value::String(s) => Some(json!(s)),
715 toml::Value::Integer(i) => Some(json!(i)),
716 toml::Value::Float(f) => Some(json!(f)),
717 toml::Value::Boolean(b) => Some(json!(b)),
718 toml::Value::Array(arr) => {
719 let json_arr: Vec<Value> = arr
720 .iter()
721 .filter_map(|item| match item {
722 toml::Value::String(s) => Some(json!(s)),
723 toml::Value::Integer(i) => Some(json!(i)),
724 toml::Value::Float(f) => Some(json!(f)),
725 toml::Value::Boolean(b) => Some(json!(b)),
726 _ => None,
727 })
728 .collect();
729 if json_arr.is_empty() {
730 None
731 } else {
732 Some(Value::Array(json_arr))
733 }
734 }
735 toml::Value::Table(tbl) => {
736 let mut json_obj = serde_json::Map::new();
737 for (k, v) in tbl.iter() {
738 if let Some(s) = v.as_str() {
739 json_obj.insert(k.clone(), json!(s));
740 }
741 }
742 if json_obj.is_empty() {
743 None
744 } else {
745 Some(Value::Object(json_obj))
746 }
747 }
748 toml::Value::Datetime(_) => None,
749 }
750}
751
752fn codex_live_mcp_entry_to_json_spec(entry_tbl: &toml::value::Table) -> Value {
753 let typ = if entry_tbl.contains_key("type") {
756 entry_tbl.get("type").and_then(|v| v.as_str())
757 } else {
758 entry_tbl
759 .get("url")
760 .and_then(|v| v.as_str())
761 .filter(|url| !url.trim().is_empty())
762 .map(|_| "http")
763 .or(Some("stdio"))
764 };
765
766 let mut spec = serde_json::Map::new();
767 if let Some(typ) = typ {
768 spec.insert("type".into(), json!(typ));
769 } else if let Some(type_val) = entry_tbl.get("type").and_then(toml_value_to_json) {
770 spec.insert("type".into(), type_val);
771 }
772
773 let core_fields = match typ {
774 Some("stdio") => vec!["type", "command", "args", "env", "cwd"],
775 Some("http") | Some("sse") => vec!["type", "url", "http_headers"],
776 _ => vec!["type"],
777 };
778
779 match typ {
780 Some("stdio") => {
781 if let Some(cmd) = entry_tbl.get("command").and_then(|v| v.as_str()) {
782 spec.insert("command".into(), json!(cmd));
783 }
784 if let Some(args) = entry_tbl.get("args").and_then(|v| v.as_array()) {
785 let arr = args
786 .iter()
787 .filter_map(|x| x.as_str())
788 .map(|s| json!(s))
789 .collect::<Vec<_>>();
790 if !arr.is_empty() {
791 spec.insert("args".into(), Value::Array(arr));
792 }
793 }
794 if let Some(cwd) = entry_tbl.get("cwd").and_then(|v| v.as_str()) {
795 if !cwd.trim().is_empty() {
796 spec.insert("cwd".into(), json!(cwd));
797 }
798 }
799 if let Some(env_tbl) = entry_tbl.get("env").and_then(|v| v.as_table()) {
800 let mut env_json = serde_json::Map::new();
801 for (k, v) in env_tbl.iter() {
802 if let Some(sv) = v.as_str() {
803 env_json.insert(k.clone(), json!(sv));
804 }
805 }
806 if !env_json.is_empty() {
807 spec.insert("env".into(), Value::Object(env_json));
808 }
809 }
810 }
811 Some("http") | Some("sse") => {
812 if let Some(url) = entry_tbl.get("url").and_then(|v| v.as_str()) {
813 spec.insert("url".into(), json!(url));
814 }
815 let headers_tbl = entry_tbl
817 .get("http_headers")
818 .and_then(|v| v.as_table())
819 .or_else(|| entry_tbl.get("headers").and_then(|v| v.as_table()));
820
821 if let Some(headers_tbl) = headers_tbl {
822 let mut headers_json = serde_json::Map::new();
823 for (k, v) in headers_tbl.iter() {
824 if let Some(sv) = v.as_str() {
825 headers_json.insert(k.clone(), json!(sv));
826 }
827 }
828 if !headers_json.is_empty() {
829 spec.insert("headers".into(), Value::Object(headers_json));
830 }
831 }
832 }
833 _ => {}
834 }
835
836 for (key, toml_val) in entry_tbl.iter() {
837 if core_fields.contains(&key.as_str()) {
838 continue;
839 }
840
841 if let Some(val) = toml_value_to_json(toml_val) {
842 spec.insert(key.clone(), val);
843 log::debug!("导入扩展字段 '{key}' = {toml_val:?}");
844 } else {
845 log::debug!("跳过复杂字段 '{key}' (TOML → JSON)");
846 }
847 }
848
849 Value::Object(spec)
850}
851
852pub fn sync_enabled_to_codex(config: &MultiAppConfig) -> Result<(), AppError> {
861 if !crate::sync_policy::should_sync_live(&AppType::Codex) {
862 return Ok(());
863 }
864 use toml_edit::{Item, Table};
865
866 let enabled = collect_enabled_servers(&config.mcp.codex);
868
869 let base_text = crate::codex_config::read_and_validate_codex_config_text()?;
871
872 let mut doc = if base_text.trim().is_empty() {
874 toml_edit::DocumentMut::default()
875 } else {
876 base_text
877 .parse::<toml_edit::DocumentMut>()
878 .map_err(|e| AppError::McpValidation(format!("解析 config.toml 失败: {e}")))?
879 };
880
881 if let Some(mcp_item) = doc.get_mut("mcp") {
883 if let Some(tbl) = mcp_item.as_table_like_mut() {
884 if tbl.contains_key("servers") {
885 log::warn!("检测到错误的 MCP 格式 [mcp.servers],正在清理并迁移到 [mcp_servers]");
886 tbl.remove("servers");
887 }
888 }
889 }
890
891 if enabled.is_empty() {
893 doc.as_table_mut().remove("mcp_servers");
895 } else {
896 let mut servers_tbl = Table::new();
898 let mut ids: Vec<_> = enabled.keys().cloned().collect();
899 ids.sort();
900 for id in ids {
901 let spec = enabled.get(&id).expect("spec must exist");
902 match json_server_to_toml_table(spec) {
904 Ok(table) => {
905 servers_tbl[&id[..]] = Item::Table(table);
906 }
907 Err(err) => {
908 log::error!("跳过无效的 MCP 服务器 '{id}': {err}");
909 }
910 }
911 }
912 doc["mcp_servers"] = Item::Table(servers_tbl);
914 }
915
916 let new_text = doc.to_string();
918 let path = crate::codex_config::get_codex_config_path();
919 crate::config::write_text_file(&path, &new_text)?;
920 Ok(())
921}
922
923pub fn sync_enabled_to_gemini(config: &MultiAppConfig) -> Result<(), AppError> {
925 if !crate::sync_policy::should_sync_live(&AppType::Gemini) {
926 return Ok(());
927 }
928 let enabled = collect_enabled_servers(&config.mcp.gemini);
929 crate::gemini_mcp::set_mcp_servers_map(&enabled)
930}
931
932pub fn import_from_gemini(config: &mut MultiAppConfig) -> Result<usize, AppError> {
935 use crate::app_config::{McpApps, McpServer};
936
937 let map = crate::gemini_mcp::read_mcp_servers_map()?;
938 if map.is_empty() {
939 return Ok(0);
940 }
941
942 if config.mcp.servers.is_none() {
944 config.mcp.servers = Some(HashMap::new());
945 }
946 let servers = config.mcp.servers.as_mut().unwrap();
947
948 let mut changed = 0;
949 let mut errors = Vec::new();
950
951 for (id, spec) in map.iter() {
952 if let Err(e) = validate_server_spec(spec) {
954 log::warn!("跳过无效 MCP 服务器 '{id}': {e}");
955 errors.push(format!("{id}: {e}"));
956 continue;
957 }
958
959 if let Some(existing) = servers.get_mut(id) {
960 if !existing.apps.gemini {
962 existing.apps.gemini = true;
963 changed += 1;
964 log::info!("MCP 服务器 '{id}' 已启用 Gemini 应用");
965 }
966 } else {
967 servers.insert(
969 id.clone(),
970 McpServer {
971 id: id.clone(),
972 name: id.clone(),
973 server: spec.clone(),
974 apps: McpApps {
975 claude: false,
976 codex: false,
977 gemini: true,
978 opencode: false,
979 openclaw: false,
980 hermes: false,
981 },
982 description: None,
983 homepage: None,
984 docs: None,
985 tags: Vec::new(),
986 },
987 );
988 changed += 1;
989 log::info!("导入新 MCP 服务器 '{id}'");
990 }
991 }
992
993 if !errors.is_empty() {
994 log::warn!("导入完成,但有 {} 项失败: {:?}", errors.len(), errors);
995 }
996
997 Ok(changed)
998}
999
1000fn convert_to_opencode_mcp_spec(spec: &Value) -> Result<Value, AppError> {
1002 let obj = spec
1003 .as_object()
1004 .ok_or_else(|| AppError::McpValidation("MCP spec must be a JSON object".into()))?;
1005
1006 let typ = obj.get("type").and_then(|v| v.as_str()).unwrap_or("stdio");
1007 let mut result = serde_json::Map::new();
1008
1009 match typ {
1010 "stdio" => {
1011 result.insert("type".into(), json!("local"));
1012
1013 let cmd = obj.get("command").and_then(|v| v.as_str()).unwrap_or("");
1014 let mut command = vec![json!(cmd)];
1015 if let Some(args) = obj.get("args").and_then(|v| v.as_array()) {
1016 command.extend(args.iter().cloned());
1017 }
1018 result.insert("command".into(), Value::Array(command));
1019
1020 if let Some(env) = obj.get("env") {
1021 if env.is_object() && !env.as_object().map(|o| o.is_empty()).unwrap_or(true) {
1022 result.insert("environment".into(), env.clone());
1023 }
1024 }
1025 result.insert("enabled".into(), json!(true));
1026 }
1027 "sse" | "http" => {
1028 result.insert("type".into(), json!("remote"));
1029 if let Some(url) = obj.get("url") {
1030 result.insert("url".into(), url.clone());
1031 }
1032 if let Some(headers) = obj.get("headers") {
1033 if headers.is_object() && !headers.as_object().map(|o| o.is_empty()).unwrap_or(true)
1034 {
1035 result.insert("headers".into(), headers.clone());
1036 }
1037 }
1038 result.insert("enabled".into(), json!(true));
1039 }
1040 other => {
1041 return Err(AppError::McpValidation(format!(
1042 "Unknown MCP type: {other}"
1043 )));
1044 }
1045 }
1046
1047 Ok(Value::Object(result))
1048}
1049
1050fn convert_from_opencode_mcp_spec(spec: &Value) -> Result<Value, AppError> {
1052 let obj = spec
1053 .as_object()
1054 .ok_or_else(|| AppError::McpValidation("OpenCode MCP spec must be a JSON object".into()))?;
1055
1056 let typ = obj.get("type").and_then(|v| v.as_str()).unwrap_or("local");
1057 let mut result = serde_json::Map::new();
1058
1059 match typ {
1060 "local" => {
1061 result.insert("type".into(), json!("stdio"));
1062 if let Some(command) = obj.get("command").and_then(|v| v.as_array()) {
1063 if let Some(cmd) = command.first().and_then(|v| v.as_str()) {
1064 result.insert("command".into(), json!(cmd));
1065 }
1066 if command.len() > 1 {
1067 result.insert("args".into(), Value::Array(command[1..].to_vec()));
1068 }
1069 }
1070 if let Some(env) = obj.get("environment") {
1071 if env.is_object() && !env.as_object().map(|o| o.is_empty()).unwrap_or(true) {
1072 result.insert("env".into(), env.clone());
1073 }
1074 }
1075 }
1076 "remote" => {
1077 result.insert("type".into(), json!("sse"));
1078 if let Some(url) = obj.get("url") {
1079 result.insert("url".into(), url.clone());
1080 }
1081 if let Some(headers) = obj.get("headers") {
1082 if headers.is_object() && !headers.as_object().map(|o| o.is_empty()).unwrap_or(true)
1083 {
1084 result.insert("headers".into(), headers.clone());
1085 }
1086 }
1087 }
1088 other => {
1089 return Err(AppError::McpValidation(format!(
1090 "Unknown OpenCode MCP type: {other}"
1091 )));
1092 }
1093 }
1094
1095 Ok(Value::Object(result))
1096}
1097
1098pub fn import_from_opencode(config: &mut MultiAppConfig) -> Result<usize, AppError> {
1100 use crate::app_config::{McpApps, McpServer};
1101
1102 let map = crate::opencode_config::get_mcp_servers()?;
1103 if map.is_empty() {
1104 return Ok(0);
1105 }
1106
1107 if config.mcp.servers.is_none() {
1108 config.mcp.servers = Some(HashMap::new());
1109 }
1110 let servers = config.mcp.servers.as_mut().unwrap();
1111
1112 let mut changed = 0;
1113 let mut errors = Vec::new();
1114
1115 for (id, spec) in map.iter() {
1116 let unified = match convert_from_opencode_mcp_spec(spec) {
1117 Ok(spec) => spec,
1118 Err(err) => {
1119 log::warn!("跳过无效 OpenCode MCP 服务器 '{id}': {err}");
1120 errors.push(format!("{id}: {err}"));
1121 continue;
1122 }
1123 };
1124
1125 if let Err(err) = validate_server_spec(&unified) {
1126 log::warn!("跳过无效 MCP 服务器 '{id}': {err}");
1127 errors.push(format!("{id}: {err}"));
1128 continue;
1129 }
1130
1131 if let Some(existing) = servers.get_mut(id) {
1132 if !existing.apps.opencode {
1133 existing.apps.opencode = true;
1134 changed += 1;
1135 log::info!("MCP 服务器 '{id}' 已启用 OpenCode 应用");
1136 }
1137 } else {
1138 servers.insert(
1139 id.clone(),
1140 McpServer {
1141 id: id.clone(),
1142 name: id.clone(),
1143 server: unified,
1144 apps: McpApps {
1145 claude: false,
1146 codex: false,
1147 gemini: false,
1148 opencode: true,
1149 openclaw: false,
1150 hermes: false,
1151 },
1152 description: None,
1153 homepage: None,
1154 docs: None,
1155 tags: Vec::new(),
1156 },
1157 );
1158 changed += 1;
1159 log::info!("导入新 OpenCode MCP 服务器 '{id}'");
1160 }
1161 }
1162
1163 if !errors.is_empty() {
1164 log::warn!("导入完成,但有 {} 项失败: {:?}", errors.len(), errors);
1165 }
1166
1167 Ok(changed)
1168}
1169
1170pub fn sync_single_server_to_claude(
1176 _config: &MultiAppConfig,
1177 id: &str,
1178 server_spec: &Value,
1179) -> Result<(), AppError> {
1180 if !crate::sync_policy::should_sync_live(&AppType::Claude) {
1181 return Ok(());
1182 }
1183 let current = crate::claude_mcp::read_mcp_servers_map()?;
1185
1186 let mut updated = current;
1188 updated.insert(id.to_string(), server_spec.clone());
1189
1190 crate::claude_mcp::set_mcp_servers_map(&updated)
1192}
1193
1194pub fn remove_server_from_claude(id: &str) -> Result<(), AppError> {
1196 if !crate::sync_policy::should_sync_live(&AppType::Claude) {
1197 return Ok(());
1198 }
1199 let mut current = crate::claude_mcp::read_mcp_servers_map()?;
1201
1202 current.remove(id);
1204
1205 crate::claude_mcp::set_mcp_servers_map(¤t)
1207}
1208
1209fn json_value_to_toml_item(value: &Value, field_name: &str) -> Option<toml_edit::Item> {
1224 use toml_edit::{Array, InlineTable, Item};
1225
1226 match value {
1227 Value::String(s) => Some(toml_edit::value(s.as_str())),
1228
1229 Value::Number(n) => {
1230 if let Some(i) = n.as_i64() {
1231 Some(toml_edit::value(i))
1232 } else if let Some(f) = n.as_f64() {
1233 Some(toml_edit::value(f))
1234 } else {
1235 log::warn!("跳过字段 '{field_name}': 无法转换的数字类型 {n}");
1236 None
1237 }
1238 }
1239
1240 Value::Bool(b) => Some(toml_edit::value(*b)),
1241
1242 Value::Array(arr) => {
1243 let mut toml_arr = Array::default();
1245 let mut all_same_type = true;
1246
1247 for item in arr {
1248 match item {
1249 Value::String(s) => toml_arr.push(s.as_str()),
1250 Value::Number(n) if n.is_i64() => toml_arr.push(n.as_i64().unwrap()),
1251 Value::Number(n) if n.is_f64() => toml_arr.push(n.as_f64().unwrap()),
1252 Value::Bool(b) => toml_arr.push(*b),
1253 _ => {
1254 all_same_type = false;
1255 break;
1256 }
1257 }
1258 }
1259
1260 if all_same_type && !toml_arr.is_empty() {
1261 Some(Item::Value(toml_edit::Value::Array(toml_arr)))
1262 } else {
1263 log::warn!("跳过字段 '{field_name}': 不支持的数组类型(混合类型或嵌套结构)");
1264 None
1265 }
1266 }
1267
1268 Value::Object(obj) => {
1269 let mut inline_table = InlineTable::new();
1271 let mut all_strings = true;
1272
1273 for (k, v) in obj {
1274 if let Some(s) = v.as_str() {
1275 inline_table.insert(k, s.into());
1277 } else {
1278 all_strings = false;
1279 break;
1280 }
1281 }
1282
1283 if all_strings && !inline_table.is_empty() {
1284 Some(Item::Value(toml_edit::Value::InlineTable(inline_table)))
1285 } else {
1286 log::warn!("跳过字段 '{field_name}': 对象值包含非字符串类型,建议使用子表语法");
1287 None
1288 }
1289 }
1290
1291 Value::Null => {
1292 log::debug!("跳过字段 '{field_name}': TOML 不支持 null 值");
1293 None
1294 }
1295 }
1296}
1297
1298fn json_server_to_toml_table(spec: &Value) -> Result<toml_edit::Table, AppError> {
1305 use toml_edit::{Array, Item, Table};
1306
1307 let mut t = Table::new();
1308 let typ = spec.get("type").and_then(|v| v.as_str()).unwrap_or("stdio");
1309 t["type"] = toml_edit::value(typ);
1310
1311 let core_fields = match typ {
1313 "stdio" => vec!["type", "command", "args", "env", "cwd"],
1314 "http" | "sse" => vec!["type", "url", "headers", "http_headers"],
1315 _ => vec!["type"],
1316 };
1317
1318 let extended_fields = [
1320 "timeout",
1322 "timeout_ms",
1323 "startup_timeout_ms",
1324 "startup_timeout_sec",
1325 "connection_timeout",
1326 "read_timeout",
1327 "debug",
1328 "log_level",
1329 "disabled",
1330 "shell",
1332 "encoding",
1333 "working_dir",
1334 "restart_on_exit",
1335 "max_restart_count",
1336 "retry_count",
1338 "max_retry_attempts",
1339 "retry_delay",
1340 "cache_tools_list",
1341 "verify_ssl",
1342 "insecure",
1343 "proxy",
1344 ];
1345
1346 match typ {
1348 "stdio" => {
1349 let cmd = spec.get("command").and_then(|v| v.as_str()).unwrap_or("");
1350 t["command"] = toml_edit::value(cmd);
1351
1352 if let Some(args) = spec.get("args").and_then(|v| v.as_array()) {
1353 let mut arr_v = Array::default();
1354 for a in args.iter().filter_map(|x| x.as_str()) {
1355 arr_v.push(a);
1356 }
1357 if !arr_v.is_empty() {
1358 t["args"] = Item::Value(toml_edit::Value::Array(arr_v));
1359 }
1360 }
1361
1362 if let Some(cwd) = spec.get("cwd").and_then(|v| v.as_str()) {
1363 if !cwd.trim().is_empty() {
1364 t["cwd"] = toml_edit::value(cwd);
1365 }
1366 }
1367
1368 if let Some(env) = spec.get("env").and_then(|v| v.as_object()) {
1369 let mut env_tbl = Table::new();
1370 for (k, v) in env.iter() {
1371 if let Some(s) = v.as_str() {
1372 env_tbl[&k[..]] = toml_edit::value(s);
1373 }
1374 }
1375 if !env_tbl.is_empty() {
1376 t["env"] = Item::Table(env_tbl);
1377 }
1378 }
1379 }
1380 "http" | "sse" => {
1381 let url = spec.get("url").and_then(|v| v.as_str()).unwrap_or("");
1382 t["url"] = toml_edit::value(url);
1383
1384 if let Some(headers) = spec.get("headers").and_then(|v| v.as_object()) {
1385 let mut h_tbl = Table::new();
1386 for (k, v) in headers.iter() {
1387 if let Some(s) = v.as_str() {
1388 h_tbl[&k[..]] = toml_edit::value(s);
1389 }
1390 }
1391 if !h_tbl.is_empty() {
1392 t["http_headers"] = Item::Table(h_tbl);
1393 }
1394 }
1395 }
1396 _ => {}
1397 }
1398
1399 if let Some(obj) = spec.as_object() {
1401 for (key, value) in obj {
1402 if core_fields.contains(&key.as_str()) {
1404 continue;
1405 }
1406
1407 if let Some(toml_item) = json_value_to_toml_item(value, key) {
1409 t[&key[..]] = toml_item;
1410
1411 if extended_fields.contains(&key.as_str()) {
1413 log::debug!("已转换扩展字段 '{key}' = {value:?}");
1414 } else {
1415 log::info!("已转换自定义字段 '{key}' = {value:?}");
1416 }
1417 }
1418 }
1419 }
1420
1421 Ok(t)
1422}
1423
1424pub fn sync_single_server_to_codex(
1427 _config: &MultiAppConfig,
1428 id: &str,
1429 server_spec: &Value,
1430) -> Result<(), AppError> {
1431 if !crate::sync_policy::should_sync_live(&AppType::Codex) {
1432 return Ok(());
1433 }
1434 use toml_edit::Item;
1435
1436 let config_path = crate::codex_config::get_codex_config_path();
1438
1439 let mut doc = if config_path.exists() {
1440 let content =
1441 std::fs::read_to_string(&config_path).map_err(|e| AppError::io(&config_path, e))?;
1442 match content.parse::<toml_edit::DocumentMut>() {
1444 Ok(doc) => doc,
1445 Err(e) => {
1446 log::warn!("解析 Codex config.toml 失败: {e},将创建新配置");
1447 toml_edit::DocumentMut::new()
1448 }
1449 }
1450 } else {
1451 toml_edit::DocumentMut::new()
1452 };
1453
1454 if let Some(mcp_item) = doc.get_mut("mcp") {
1456 if let Some(tbl) = mcp_item.as_table_like_mut() {
1457 if tbl.contains_key("servers") {
1458 log::warn!("检测到错误的 MCP 格式 [mcp.servers],正在清理并迁移到 [mcp_servers]");
1459 tbl.remove("servers");
1460 }
1461 }
1462 }
1463
1464 if !doc.contains_key("mcp_servers") {
1466 doc["mcp_servers"] = toml_edit::table();
1467 }
1468
1469 let toml_table = json_server_to_toml_table(server_spec)?;
1471
1472 doc["mcp_servers"][id] = Item::Table(toml_table);
1474
1475 let new_text = doc.to_string();
1477 crate::config::write_text_file(&config_path, &new_text)?;
1478
1479 Ok(())
1480}
1481
1482pub fn remove_server_from_codex(id: &str) -> Result<(), AppError> {
1485 if !crate::sync_policy::should_sync_live(&AppType::Codex) {
1486 return Ok(());
1487 }
1488 let config_path = crate::codex_config::get_codex_config_path();
1489
1490 if !config_path.exists() {
1491 return Ok(()); }
1493
1494 let content =
1495 std::fs::read_to_string(&config_path).map_err(|e| AppError::io(&config_path, e))?;
1496
1497 let mut doc = match content.parse::<toml_edit::DocumentMut>() {
1499 Ok(doc) => doc,
1500 Err(e) => {
1501 log::warn!("解析 Codex config.toml 失败: {e},跳过删除操作");
1502 return Ok(());
1503 }
1504 };
1505
1506 if let Some(mcp_servers) = doc.get_mut("mcp_servers").and_then(|s| s.as_table_mut()) {
1508 mcp_servers.remove(id);
1509 }
1510
1511 if let Some(mcp_table) = doc.get_mut("mcp").and_then(|t| t.as_table_mut()) {
1513 if let Some(servers) = mcp_table.get_mut("servers").and_then(|s| s.as_table_mut()) {
1514 if servers.remove(id).is_some() {
1515 log::warn!("从错误的 MCP 格式 [mcp.servers] 中清理了服务器 '{id}'");
1516 }
1517 }
1518 }
1519
1520 let new_text = doc.to_string();
1522 crate::config::write_text_file(&config_path, &new_text)?;
1523
1524 Ok(())
1525}
1526
1527pub fn sync_single_server_to_gemini(
1529 _config: &MultiAppConfig,
1530 id: &str,
1531 server_spec: &Value,
1532) -> Result<(), AppError> {
1533 if !crate::sync_policy::should_sync_live(&AppType::Gemini) {
1534 return Ok(());
1535 }
1536
1537 let current = crate::gemini_mcp::read_mcp_servers_map()?;
1539
1540 let mut updated = current;
1542 updated.insert(id.to_string(), server_spec.clone());
1543
1544 crate::gemini_mcp::set_mcp_servers_map(&updated)
1546}
1547
1548pub fn remove_server_from_gemini(id: &str) -> Result<(), AppError> {
1550 if !crate::sync_policy::should_sync_live(&AppType::Gemini) {
1551 return Ok(());
1552 }
1553
1554 let mut current = crate::gemini_mcp::read_mcp_servers_map()?;
1556
1557 current.remove(id);
1559
1560 crate::gemini_mcp::set_mcp_servers_map(¤t)
1562}
1563
1564pub fn sync_single_server_to_opencode(
1566 _config: &MultiAppConfig,
1567 id: &str,
1568 server_spec: &Value,
1569) -> Result<(), AppError> {
1570 if !crate::sync_policy::should_sync_live(&AppType::OpenCode) {
1571 return Ok(());
1572 }
1573
1574 let spec = convert_to_opencode_mcp_spec(server_spec)?;
1575 crate::opencode_config::set_mcp_server(id, spec)
1576}
1577
1578pub fn remove_server_from_opencode(id: &str) -> Result<(), AppError> {
1580 if !crate::sync_policy::should_sync_live(&AppType::OpenCode) {
1581 return Ok(());
1582 }
1583
1584 crate::opencode_config::remove_mcp_server(id)
1585}
1586
1587fn convert_to_openclaw_mcp_spec(spec: &Value) -> Result<Value, AppError> {
1592 let obj = spec
1593 .as_object()
1594 .ok_or_else(|| AppError::McpValidation("MCP spec must be a JSON object".into()))?;
1595 let typ = obj.get("type").and_then(|v| v.as_str()).unwrap_or("stdio");
1596 let mut result = serde_json::Map::new();
1597
1598 match typ {
1599 "stdio" => {
1600 if let Some(command) = obj.get("command") {
1601 result.insert("command".into(), command.clone());
1602 }
1603 if let Some(args) = obj.get("args") {
1604 if args.is_array() && !args.as_array().map(|a| a.is_empty()).unwrap_or(true) {
1605 result.insert("args".into(), args.clone());
1606 }
1607 }
1608 if let Some(env) = obj.get("env") {
1609 if env.is_object() && !env.as_object().map(|o| o.is_empty()).unwrap_or(true) {
1610 result.insert("env".into(), env.clone());
1611 }
1612 }
1613 for key in ["cwd", "workingDirectory"] {
1614 if let Some(value) = obj.get(key) {
1615 result.insert(key.to_string(), value.clone());
1616 }
1617 }
1618 }
1619 "sse" | "http" => {
1620 if let Some(url) = obj.get("url") {
1621 result.insert("url".into(), url.clone());
1622 }
1623 if typ == "http" {
1624 result.insert("transport".into(), json!("streamable-http"));
1625 } else if obj
1626 .get("transport")
1627 .and_then(|value| value.as_str())
1628 .is_some()
1629 {
1630 result.insert("transport".into(), json!("sse"));
1631 }
1632 if let Some(headers) = obj.get("headers") {
1633 if headers.is_object() && !headers.as_object().map(|o| o.is_empty()).unwrap_or(true)
1634 {
1635 result.insert("headers".into(), headers.clone());
1636 }
1637 }
1638 if let Some(timeout) = obj.get("connectionTimeoutMs") {
1639 result.insert("connectionTimeoutMs".into(), timeout.clone());
1640 }
1641 }
1642 _ => {
1643 return Err(AppError::McpValidation(format!("Unknown MCP type: {typ}")));
1644 }
1645 }
1646
1647 Ok(Value::Object(result))
1648}
1649
1650fn convert_from_openclaw_mcp_spec(id: &str, spec: &Value) -> Result<Value, AppError> {
1651 let obj = spec
1652 .as_object()
1653 .ok_or_else(|| AppError::McpValidation("OpenClaw MCP spec must be a JSON object".into()))?;
1654 let mut result = serde_json::Map::new();
1655
1656 if obj.contains_key("command") {
1657 result.insert("type".into(), json!("stdio"));
1658 for key in ["command", "args", "env", "cwd", "workingDirectory"] {
1659 if let Some(value) = obj.get(key) {
1660 result.insert(key.to_string(), value.clone());
1661 }
1662 }
1663 } else if obj.contains_key("url") {
1664 let transport = obj.get("transport").and_then(|value| value.as_str());
1665 let typ = match transport {
1666 Some("streamable-http") | Some("http") => "http",
1667 _ => "sse",
1668 };
1669 result.insert("type".into(), json!(typ));
1670 if let Some(url) = obj.get("url") {
1671 result.insert("url".into(), url.clone());
1672 }
1673 if let Some(headers) = obj.get("headers") {
1674 if headers.is_object() && !headers.as_object().map(|o| o.is_empty()).unwrap_or(true) {
1675 result.insert("headers".into(), headers.clone());
1676 }
1677 }
1678 if let Some(timeout) = obj.get("connectionTimeoutMs") {
1679 result.insert("connectionTimeoutMs".into(), timeout.clone());
1680 }
1681 } else {
1682 return Err(AppError::McpValidation(format!(
1683 "OpenClaw MCP server '{id}' has neither 'command' nor 'url' field"
1684 )));
1685 }
1686
1687 Ok(Value::Object(result))
1688}
1689
1690pub fn sync_single_server_to_openclaw(
1691 _config: &MultiAppConfig,
1692 id: &str,
1693 server_spec: &Value,
1694) -> Result<(), AppError> {
1695 if !crate::sync_policy::should_sync_live(&AppType::OpenClaw) {
1696 return Ok(());
1697 }
1698
1699 let spec = convert_to_openclaw_mcp_spec(server_spec)?;
1700 crate::openclaw_config::set_mcp_server(id, spec).map(|_| ())
1701}
1702
1703pub fn remove_server_from_openclaw(id: &str) -> Result<(), AppError> {
1704 if !crate::sync_policy::should_sync_live(&AppType::OpenClaw) {
1705 return Ok(());
1706 }
1707
1708 crate::openclaw_config::remove_mcp_server(id).map(|_| ())
1709}
1710
1711pub fn import_from_openclaw(config: &mut MultiAppConfig) -> Result<usize, AppError> {
1712 use crate::app_config::{McpApps, McpServer};
1713
1714 let map = crate::openclaw_config::get_mcp_servers()?;
1715 if map.is_empty() {
1716 return Ok(0);
1717 }
1718
1719 if config.mcp.servers.is_none() {
1720 config.mcp.servers = Some(HashMap::new());
1721 }
1722 let servers = config.mcp.servers.as_mut().unwrap();
1723
1724 let mut changed = 0;
1725 let mut errors = Vec::new();
1726
1727 for (id, spec) in map.iter() {
1728 let unified = match convert_from_openclaw_mcp_spec(id, spec) {
1729 Ok(spec) => spec,
1730 Err(err) => {
1731 log::warn!("Skip invalid OpenClaw MCP server '{id}': {err}");
1732 errors.push(format!("{id}: {err}"));
1733 continue;
1734 }
1735 };
1736
1737 if let Err(err) = validate_server_spec(&unified) {
1738 log::warn!("Skip invalid MCP server '{id}' after conversion: {err}");
1739 errors.push(format!("{id}: {err}"));
1740 continue;
1741 }
1742
1743 if let Some(existing) = servers.get_mut(id) {
1744 if !existing.apps.openclaw {
1745 existing.apps.openclaw = true;
1746 changed += 1;
1747 log::info!("MCP server '{id}' enabled for OpenClaw");
1748 }
1749 } else {
1750 servers.insert(
1751 id.clone(),
1752 McpServer {
1753 id: id.clone(),
1754 name: id.clone(),
1755 server: unified,
1756 apps: McpApps {
1757 claude: false,
1758 codex: false,
1759 gemini: false,
1760 opencode: false,
1761 openclaw: true,
1762 hermes: false,
1763 },
1764 description: None,
1765 homepage: None,
1766 docs: None,
1767 tags: Vec::new(),
1768 },
1769 );
1770 changed += 1;
1771 log::info!("Imported new MCP server '{id}' from OpenClaw");
1772 }
1773 }
1774
1775 if !errors.is_empty() {
1776 log::warn!(
1777 "Import completed with {} failures: {:?}",
1778 errors.len(),
1779 errors
1780 );
1781 }
1782
1783 Ok(changed)
1784}
1785
1786const HERMES_EXTRA_FIELDS: &[&str] = &[
1792 "enabled",
1793 "timeout",
1794 "connect_timeout",
1795 "tools",
1796 "sampling",
1797 "roots",
1798 "auth",
1799];
1800
1801fn should_sync_hermes_mcp() -> bool {
1802 crate::hermes_config::get_hermes_dir().exists()
1803}
1804
1805fn convert_to_hermes_format(spec: &Value) -> Result<Value, AppError> {
1807 let obj = spec
1808 .as_object()
1809 .ok_or_else(|| AppError::McpValidation("MCP spec must be a JSON object".into()))?;
1810
1811 let typ = obj.get("type").and_then(|v| v.as_str()).unwrap_or("stdio");
1812
1813 let mut result = serde_json::Map::new();
1814
1815 match typ {
1816 "stdio" => {
1817 if let Some(command) = obj.get("command") {
1818 result.insert("command".into(), command.clone());
1819 }
1820 if let Some(args) = obj.get("args") {
1821 if args.is_array() && !args.as_array().map(|a| a.is_empty()).unwrap_or(true) {
1822 result.insert("args".into(), args.clone());
1823 }
1824 }
1825 if let Some(env) = obj.get("env") {
1826 if env.is_object() && !env.as_object().map(|o| o.is_empty()).unwrap_or(true) {
1827 result.insert("env".into(), env.clone());
1828 }
1829 }
1830 }
1831 "sse" | "http" => {
1832 if let Some(url) = obj.get("url") {
1833 result.insert("url".into(), url.clone());
1834 }
1835 if let Some(headers) = obj.get("headers") {
1836 if headers.is_object() && !headers.as_object().map(|o| o.is_empty()).unwrap_or(true)
1837 {
1838 result.insert("headers".into(), headers.clone());
1839 }
1840 }
1841 }
1842 _ => {
1843 return Err(AppError::McpValidation(format!("Unknown MCP type: {typ}")));
1844 }
1845 }
1846
1847 result.insert("enabled".into(), json!(true));
1848
1849 Ok(Value::Object(result))
1850}
1851
1852fn convert_from_hermes_format(id: &str, spec: &Value) -> Result<Value, AppError> {
1854 let obj = spec
1855 .as_object()
1856 .ok_or_else(|| AppError::McpValidation("Hermes MCP spec must be a JSON object".into()))?;
1857
1858 let mut result = serde_json::Map::new();
1859
1860 if obj.contains_key("command") {
1861 result.insert("type".into(), json!("stdio"));
1862 if let Some(command) = obj.get("command") {
1863 result.insert("command".into(), command.clone());
1864 }
1865 if let Some(args) = obj.get("args") {
1866 if args.is_array() && !args.as_array().map(|a| a.is_empty()).unwrap_or(true) {
1867 result.insert("args".into(), args.clone());
1868 }
1869 }
1870 if let Some(env) = obj.get("env") {
1871 if env.is_object() && !env.as_object().map(|o| o.is_empty()).unwrap_or(true) {
1872 result.insert("env".into(), env.clone());
1873 }
1874 }
1875 } else if obj.contains_key("url") {
1876 result.insert("type".into(), json!("sse"));
1877 if let Some(url) = obj.get("url") {
1878 result.insert("url".into(), url.clone());
1879 }
1880 if let Some(headers) = obj.get("headers") {
1881 if headers.is_object() && !headers.as_object().map(|o| o.is_empty()).unwrap_or(true) {
1882 result.insert("headers".into(), headers.clone());
1883 }
1884 }
1885 } else {
1886 return Err(AppError::McpValidation(format!(
1887 "Hermes MCP server '{id}' has neither 'command' nor 'url' field"
1888 )));
1889 }
1890
1891 Ok(Value::Object(result))
1892}
1893
1894fn merge_hermes_spec(existing: &Value, new_spec: &Value) -> Value {
1896 let mut result = serde_json::Map::new();
1897
1898 if let Some(existing_obj) = existing.as_object() {
1899 for &field in HERMES_EXTRA_FIELDS {
1900 if let Some(val) = existing_obj.get(field) {
1901 result.insert(field.to_string(), val.clone());
1902 }
1903 }
1904 }
1905
1906 if let Some(new_obj) = new_spec.as_object() {
1907 for (key, val) in new_obj {
1908 if HERMES_EXTRA_FIELDS.contains(&key.as_str()) && result.contains_key(key) {
1909 continue;
1910 }
1911 result.insert(key.clone(), val.clone());
1912 }
1913 }
1914
1915 Value::Object(result)
1916}
1917
1918pub fn sync_single_server_to_hermes(
1920 _config: &MultiAppConfig,
1921 id: &str,
1922 server_spec: &Value,
1923) -> Result<(), AppError> {
1924 if !should_sync_hermes_mcp() {
1925 return Ok(());
1926 }
1927
1928 let hermes_spec = convert_to_hermes_format(server_spec)?;
1929 let id_owned = id.to_string();
1930
1931 crate::hermes_config::update_mcp_servers_yaml(|servers| {
1932 let id_yaml = serde_yaml::Value::String(id_owned.clone());
1933
1934 let merged_json = if let Some(existing_yaml) = servers.get(&id_yaml) {
1935 let existing_json = crate::hermes_config::yaml_to_json(existing_yaml)?;
1936 merge_hermes_spec(&existing_json, &hermes_spec)
1937 } else {
1938 hermes_spec.clone()
1939 };
1940
1941 let merged_yaml_value = crate::hermes_config::json_to_yaml(&merged_json)?;
1942 servers.insert(id_yaml, merged_yaml_value);
1943 Ok(())
1944 })
1945}
1946
1947pub fn remove_server_from_hermes(id: &str) -> Result<(), AppError> {
1949 if !should_sync_hermes_mcp() {
1950 return Ok(());
1951 }
1952
1953 let id_owned = id.to_string();
1954 crate::hermes_config::update_mcp_servers_yaml(|servers| {
1955 servers.remove(serde_yaml::Value::String(id_owned.clone()));
1956 Ok(())
1957 })
1958}
1959
1960pub fn import_from_hermes(config: &mut MultiAppConfig) -> Result<usize, AppError> {
1962 use crate::app_config::{McpApps, McpServer};
1963
1964 let yaml_map = crate::hermes_config::get_mcp_servers_yaml()?;
1965 if yaml_map.is_empty() {
1966 return Ok(0);
1967 }
1968
1969 if config.mcp.servers.is_none() {
1970 config.mcp.servers = Some(HashMap::new());
1971 }
1972 let servers = config.mcp.servers.as_mut().unwrap();
1973
1974 let mut changed = 0;
1975 let mut errors = Vec::new();
1976
1977 for (key, spec_yaml) in &yaml_map {
1978 let id = match key.as_str() {
1979 Some(s) => s.to_string(),
1980 None => {
1981 log::warn!("Skip Hermes MCP server with non-string key");
1982 continue;
1983 }
1984 };
1985
1986 let spec_json = match crate::hermes_config::yaml_to_json(spec_yaml) {
1987 Ok(j) => j,
1988 Err(e) => {
1989 log::warn!("Skip Hermes MCP server '{id}': failed to convert YAML to JSON: {e}");
1990 errors.push(format!("{id}: {e}"));
1991 continue;
1992 }
1993 };
1994
1995 let unified_spec = match convert_from_hermes_format(&id, &spec_json) {
1996 Ok(s) => s,
1997 Err(e) => {
1998 log::warn!("Skip invalid Hermes MCP server '{id}': {e}");
1999 errors.push(format!("{id}: {e}"));
2000 continue;
2001 }
2002 };
2003
2004 if let Err(e) = validate_server_spec(&unified_spec) {
2005 log::warn!("Skip invalid MCP server '{id}' after conversion: {e}");
2006 errors.push(format!("{id}: {e}"));
2007 continue;
2008 }
2009
2010 if let Some(existing) = servers.get_mut(&id) {
2011 if !existing.apps.hermes {
2012 existing.apps.hermes = true;
2013 changed += 1;
2014 log::info!("MCP server '{id}' enabled for Hermes");
2015 }
2016 } else {
2017 servers.insert(
2018 id.clone(),
2019 McpServer {
2020 id: id.clone(),
2021 name: id.clone(),
2022 server: unified_spec,
2023 apps: McpApps {
2024 claude: false,
2025 codex: false,
2026 gemini: false,
2027 opencode: false,
2028 openclaw: false,
2029 hermes: true,
2030 },
2031 description: None,
2032 homepage: None,
2033 docs: None,
2034 tags: Vec::new(),
2035 },
2036 );
2037 changed += 1;
2038 log::info!("Imported new MCP server '{id}' from Hermes");
2039 }
2040 }
2041
2042 if !errors.is_empty() {
2043 log::warn!(
2044 "Import completed with {} failures: {:?}",
2045 errors.len(),
2046 errors
2047 );
2048 }
2049
2050 Ok(changed)
2051}