-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathmcp.rs
More file actions
797 lines (707 loc) · 27 KB
/
mcp.rs
File metadata and controls
797 lines (707 loc) · 27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
use anyhow::{Context, Result};
use chrono::Utc;
use dirs;
use log::{error, info};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use tauri::AppHandle;
/// Helper function to create a std::process::Command with proper environment variables
/// This ensures commands like Claude can find Node.js and other dependencies
fn create_command_with_env(program: &str) -> Command {
crate::claude_binary::create_command_with_env(program)
}
/// Finds the full path to the claude binary
/// This is necessary because macOS apps have a limited PATH environment
fn find_claude_binary(app_handle: &AppHandle) -> Result<String> {
crate::claude_binary::find_claude_binary(app_handle).map_err(|e| anyhow::anyhow!(e))
}
/// Represents an MCP server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPServer {
/// Server name/identifier
pub name: String,
/// Transport type: "stdio" or "sse"
pub transport: String,
/// Command to execute (for stdio)
pub command: Option<String>,
/// Command arguments (for stdio)
pub args: Vec<String>,
/// Environment variables
pub env: HashMap<String, String>,
/// URL endpoint (for SSE)
pub url: Option<String>,
/// Configuration scope: "local", "project", or "user"
pub scope: String,
/// Whether the server is currently active
pub is_active: bool,
/// Server status
pub status: ServerStatus,
}
/// Server status information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerStatus {
/// Whether the server is running
pub running: bool,
/// Last error message if any
pub error: Option<String>,
/// Last checked timestamp
pub last_checked: Option<u64>,
}
/// MCP configuration for project scope (.mcp.json)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPProjectConfig {
#[serde(rename = "mcpServers")]
pub mcp_servers: HashMap<String, MCPServerConfig>,
}
/// Individual server configuration in .mcp.json
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPServerConfig {
pub command: String,
#[serde(default)]
pub args: Vec<String>,
#[serde(default)]
pub env: HashMap<String, String>,
}
/// Result of adding a server
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AddServerResult {
pub success: bool,
pub message: String,
pub server_name: Option<String>,
}
/// Import result for multiple servers
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImportResult {
pub imported_count: u32,
pub failed_count: u32,
pub servers: Vec<ImportServerResult>,
}
/// Result for individual server import
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImportServerResult {
pub name: String,
pub success: bool,
pub error: Option<String>,
}
/// Executes a claude mcp command
fn execute_claude_mcp_command(app_handle: &AppHandle, args: Vec<&str>) -> Result<String> {
info!("Executing claude mcp command with args: {:?}", args);
let claude_path = find_claude_binary(app_handle)?;
let mut cmd = create_command_with_env(&claude_path);
cmd.arg("mcp");
for arg in args {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to execute claude command")?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stdout).to_string())
} else {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
Err(anyhow::anyhow!("Command failed: {}", stderr))
}
}
/// Adds a new MCP server
#[tauri::command]
pub async fn mcp_add(
app: AppHandle,
name: String,
transport: String,
command: Option<String>,
args: Vec<String>,
env: HashMap<String, String>,
url: Option<String>,
scope: String,
) -> Result<AddServerResult, String> {
info!("Adding MCP server: {} with transport: {}", name, transport);
// Prepare owned strings for environment variables
let env_args: Vec<String> = env
.iter()
.map(|(key, value)| format!("{}={}", key, value))
.collect();
let mut cmd_args = vec!["add"];
// Add scope flag
cmd_args.push("-s");
cmd_args.push(&scope);
// Add transport flag for SSE
if transport == "sse" {
cmd_args.push("--transport");
cmd_args.push("sse");
}
// Add environment variables
for (i, _) in env.iter().enumerate() {
cmd_args.push("-e");
cmd_args.push(&env_args[i]);
}
// Add name
cmd_args.push(&name);
// Add command/URL based on transport
if transport == "stdio" {
if let Some(cmd) = &command {
// Add "--" separator before command to prevent argument parsing issues
if !args.is_empty() || cmd.contains('-') {
cmd_args.push("--");
}
cmd_args.push(cmd);
// Add arguments
for arg in &args {
cmd_args.push(arg);
}
} else {
return Ok(AddServerResult {
success: false,
message: "Command is required for stdio transport".to_string(),
server_name: None,
});
}
} else if transport == "sse" {
if let Some(url_str) = &url {
cmd_args.push(url_str);
} else {
return Ok(AddServerResult {
success: false,
message: "URL is required for SSE transport".to_string(),
server_name: None,
});
}
}
match execute_claude_mcp_command(&app, cmd_args) {
Ok(output) => {
info!("Successfully added MCP server: {}", name);
Ok(AddServerResult {
success: true,
message: output.trim().to_string(),
server_name: Some(name),
})
}
Err(e) => {
error!("Failed to add MCP server: {}", e);
Ok(AddServerResult {
success: false,
message: e.to_string(),
server_name: None,
})
}
}
}
/// Lists all configured MCP servers
#[tauri::command]
pub async fn mcp_list(app: AppHandle) -> Result<Vec<MCPServer>, String> {
info!("Listing MCP servers");
match execute_claude_mcp_command(&app, vec!["list"]) {
Ok(output) => {
info!("Raw output from 'claude mcp list': {:?}", output);
let trimmed = output.trim();
info!("Trimmed output: {:?}", trimmed);
// Check if no servers are configured
if trimmed.contains("No MCP servers configured") || trimmed.is_empty() {
info!("No servers found - empty or 'No MCP servers' message");
return Ok(vec![]);
}
// Parse the text output, handling multi-line commands
let mut servers = Vec::new();
let lines: Vec<&str> = trimmed.lines().collect();
info!("Total lines in output: {}", lines.len());
for (idx, line) in lines.iter().enumerate() {
info!("Line {}: {:?}", idx, line);
}
let mut i = 0;
while i < lines.len() {
let line = lines[i];
info!("Processing line {}: {:?}", i, line);
// Check if this line starts a new server entry
if let Some(colon_pos) = line.find(':') {
info!("Found colon at position {} in line: {:?}", colon_pos, line);
// Make sure this is a server name line (not part of a path)
// Server names typically don't contain '/' or '\'
let potential_name = line[..colon_pos].trim();
info!("Potential server name: {:?}", potential_name);
if !potential_name.contains('/') && !potential_name.contains('\\') {
info!("Valid server name detected: {:?}", potential_name);
let name = potential_name.to_string();
let mut command_parts = vec![line[colon_pos + 1..].trim().to_string()];
info!("Initial command part: {:?}", command_parts[0]);
// Check if command continues on next lines
i += 1;
while i < lines.len() {
let next_line = lines[i];
info!("Checking next line {} for continuation: {:?}", i, next_line);
// If the next line starts with a server name pattern, break
if next_line.contains(':') {
let potential_next_name =
next_line.split(':').next().unwrap_or("").trim();
info!(
"Found colon in next line, potential name: {:?}",
potential_next_name
);
if !potential_next_name.is_empty()
&& !potential_next_name.contains('/')
&& !potential_next_name.contains('\\')
{
info!("Next line is a new server, breaking");
break;
}
}
// Otherwise, this line is a continuation of the command
info!("Line {} is a continuation", i);
command_parts.push(next_line.trim().to_string());
i += 1;
}
// Join all command parts
let full_command = command_parts.join(" ");
info!("Full command for server '{}': {:?}", name, full_command);
// For now, we'll create a basic server entry
servers.push(MCPServer {
name: name.clone(),
transport: "stdio".to_string(), // Default assumption
command: Some(full_command),
args: vec![],
env: HashMap::new(),
url: None,
scope: "local".to_string(), // Default assumption
is_active: false,
status: ServerStatus {
running: false,
error: None,
last_checked: None,
},
});
info!("Added server: {:?}", name);
continue;
} else {
info!("Skipping line - name contains path separators");
}
} else {
info!("No colon found in line {}", i);
}
i += 1;
}
info!("Found {} MCP servers total", servers.len());
for (idx, server) in servers.iter().enumerate() {
info!(
"Server {}: name='{}', command={:?}",
idx, server.name, server.command
);
}
Ok(servers)
}
Err(e) => {
error!("Failed to list MCP servers: {}", e);
Err(e.to_string())
}
}
}
/// Gets details for a specific MCP server
#[tauri::command]
pub async fn mcp_get(app: AppHandle, name: String) -> Result<MCPServer, String> {
info!("Getting MCP server details for: {}", name);
match execute_claude_mcp_command(&app, vec!["get", &name]) {
Ok(output) => {
// Parse the structured text output
let mut scope = "local".to_string();
let mut transport = "stdio".to_string();
let mut command = None;
let mut args = vec![];
let env = HashMap::new();
let mut url = None;
for line in output.lines() {
let line = line.trim();
if line.starts_with("Scope:") {
let scope_part = line.replace("Scope:", "").trim().to_string();
if scope_part.to_lowercase().contains("local") {
scope = "local".to_string();
} else if scope_part.to_lowercase().contains("project") {
scope = "project".to_string();
} else if scope_part.to_lowercase().contains("user")
|| scope_part.to_lowercase().contains("global")
{
scope = "user".to_string();
}
} else if line.starts_with("Type:") {
transport = line.replace("Type:", "").trim().to_string();
} else if line.starts_with("Command:") {
command = Some(line.replace("Command:", "").trim().to_string());
} else if line.starts_with("Args:") {
let args_str = line.replace("Args:", "").trim().to_string();
if !args_str.is_empty() {
args = args_str.split_whitespace().map(|s| s.to_string()).collect();
}
} else if line.starts_with("URL:") {
url = Some(line.replace("URL:", "").trim().to_string());
} else if line.starts_with("Environment:") {
// TODO: Parse environment variables if they're listed
// For now, we'll leave it empty
}
}
Ok(MCPServer {
name,
transport,
command,
args,
env,
url,
scope,
is_active: false,
status: ServerStatus {
running: false,
error: None,
last_checked: None,
},
})
}
Err(e) => {
error!("Failed to get MCP server: {}", e);
Err(e.to_string())
}
}
}
/// Removes an MCP server
#[tauri::command]
pub async fn mcp_remove(app: AppHandle, name: String) -> Result<String, String> {
info!("Removing MCP server: {}", name);
match execute_claude_mcp_command(&app, vec!["remove", &name]) {
Ok(output) => {
info!("Successfully removed MCP server: {}", name);
Ok(output.trim().to_string())
}
Err(e) => {
error!("Failed to remove MCP server: {}", e);
Err(e.to_string())
}
}
}
/// Adds an MCP server from JSON configuration
#[tauri::command]
pub async fn mcp_add_json(
app: AppHandle,
name: String,
json_config: String,
scope: String,
) -> Result<AddServerResult, String> {
info!(
"Adding MCP server from JSON: {} with scope: {}",
name, scope
);
// Build command args
let mut cmd_args = vec!["add-json", &name, &json_config];
// Add scope flag
let scope_flag = "-s";
cmd_args.push(scope_flag);
cmd_args.push(&scope);
match execute_claude_mcp_command(&app, cmd_args) {
Ok(output) => {
info!("Successfully added MCP server from JSON: {}", name);
Ok(AddServerResult {
success: true,
message: output.trim().to_string(),
server_name: Some(name),
})
}
Err(e) => {
error!("Failed to add MCP server from JSON: {}", e);
Ok(AddServerResult {
success: false,
message: e.to_string(),
server_name: None,
})
}
}
}
/// Imports MCP servers from Claude Desktop
#[tauri::command]
pub async fn mcp_add_from_claude_desktop(
app: AppHandle,
scope: String,
) -> Result<ImportResult, String> {
info!(
"Importing MCP servers from Claude Desktop with scope: {}",
scope
);
// Get Claude Desktop config path based on platform
let config_path = if cfg!(target_os = "macos") {
dirs::home_dir()
.ok_or_else(|| "Could not find home directory".to_string())?
.join("Library")
.join("Application Support")
.join("Claude")
.join("claude_desktop_config.json")
} else if cfg!(target_os = "linux") {
// For WSL/Linux, check common locations
dirs::config_dir()
.ok_or_else(|| "Could not find config directory".to_string())?
.join("Claude")
.join("claude_desktop_config.json")
} else {
return Err(
"Import from Claude Desktop is only supported on macOS and Linux/WSL".to_string(),
);
};
// Check if config file exists
if !config_path.exists() {
return Err(
"Claude Desktop configuration not found. Make sure Claude Desktop is installed."
.to_string(),
);
}
// Read and parse the config file
let config_content = fs::read_to_string(&config_path)
.map_err(|e| format!("Failed to read Claude Desktop config: {}", e))?;
let config: serde_json::Value = serde_json::from_str(&config_content)
.map_err(|e| format!("Failed to parse Claude Desktop config: {}", e))?;
// Extract MCP servers
let mcp_servers = config
.get("mcpServers")
.and_then(|v| v.as_object())
.ok_or_else(|| "No MCP servers found in Claude Desktop config".to_string())?;
let mut imported_count = 0;
let mut failed_count = 0;
let mut server_results = Vec::new();
// Import each server using add-json
for (name, server_config) in mcp_servers {
info!("Importing server: {}", name);
// Convert Claude Desktop format to add-json format
let mut json_config = serde_json::Map::new();
// All Claude Desktop servers are stdio type
json_config.insert(
"type".to_string(),
serde_json::Value::String("stdio".to_string()),
);
// Add command
if let Some(command) = server_config.get("command").and_then(|v| v.as_str()) {
json_config.insert(
"command".to_string(),
serde_json::Value::String(command.to_string()),
);
} else {
failed_count += 1;
server_results.push(ImportServerResult {
name: name.clone(),
success: false,
error: Some("Missing command field".to_string()),
});
continue;
}
// Add args if present
if let Some(args) = server_config.get("args").and_then(|v| v.as_array()) {
json_config.insert("args".to_string(), args.clone().into());
} else {
json_config.insert("args".to_string(), serde_json::Value::Array(vec![]));
}
// Add env if present
if let Some(env) = server_config.get("env").and_then(|v| v.as_object()) {
json_config.insert("env".to_string(), env.clone().into());
} else {
json_config.insert(
"env".to_string(),
serde_json::Value::Object(serde_json::Map::new()),
);
}
// Convert to JSON string
let json_str = serde_json::to_string(&json_config)
.map_err(|e| format!("Failed to serialize config for {}: {}", name, e))?;
// Call add-json command
match mcp_add_json(app.clone(), name.clone(), json_str, scope.clone()).await {
Ok(result) => {
if result.success {
imported_count += 1;
server_results.push(ImportServerResult {
name: name.clone(),
success: true,
error: None,
});
info!("Successfully imported server: {}", name);
} else {
failed_count += 1;
let error_msg = result.message.clone();
server_results.push(ImportServerResult {
name: name.clone(),
success: false,
error: Some(result.message),
});
error!("Failed to import server {}: {}", name, error_msg);
}
}
Err(e) => {
failed_count += 1;
let error_msg = e.clone();
server_results.push(ImportServerResult {
name: name.clone(),
success: false,
error: Some(e),
});
error!("Error importing server {}: {}", name, error_msg);
}
}
}
info!(
"Import complete: {} imported, {} failed",
imported_count, failed_count
);
Ok(ImportResult {
imported_count,
failed_count,
servers: server_results,
})
}
/// Starts Claude Code as an MCP server
#[tauri::command]
pub async fn mcp_serve(
app: AppHandle,
registry: tauri::State<'_, crate::process::ProcessRegistryState>,
) -> Result<String, String> {
info!("Starting Claude Code as MCP server");
// Start the server in a separate process
let claude_path = match find_claude_binary(&app) {
Ok(path) => path,
Err(e) => {
error!("Failed to find claude binary: {}", e);
return Err(e.to_string());
}
};
let mut cmd = create_command_with_env(&claude_path);
cmd.arg("mcp").arg("serve");
match cmd.spawn() {
Ok(child) => {
let pid = child.id();
if pid == 0 {
error!("MCP server started but PID is unavailable");
return Err("MCP server started but PID is unavailable".to_string());
}
// Intentionally drop the child handle - MCP server runs as detached process.
// We track it by PID only, allowing it to outlive the parent process.
std::mem::forget(child);
// Register atomically - will fail if another instance already exists
match registry.0.register_mcp_serve_process(pid) {
Ok(_run_id) => {
info!("Successfully started Claude Code MCP server (PID: {})", pid);
Ok(format!("Claude Code MCP server started (PID: {})", pid))
}
Err(e) => {
// Registration failed (likely already running) - kill the process we just started
error!("Failed to register MCP server process: {}", e);
#[cfg(unix)]
{
use std::process::Command;
let _ = Command::new("kill").arg(pid.to_string()).spawn();
}
#[cfg(windows)]
{
use std::process::Command;
let _ = Command::new("taskkill")
.args(["/PID", &pid.to_string(), "/F"])
.spawn();
}
Err(e)
}
}
}
Err(e) => {
error!("Failed to start MCP server: {}", e);
Err(e.to_string())
}
}
}
/// Stops Claude Code MCP server if running
#[tauri::command]
pub async fn mcp_stop(
registry: tauri::State<'_, crate::process::ProcessRegistryState>,
) -> Result<String, String> {
if let Ok(Some(proc_info)) = registry.0.get_running_mcp_serve() {
let run_id = proc_info.run_id;
let pid = proc_info.pid;
registry
.0
.kill_process(run_id)
.await
.map_err(|e| format!("Failed to stop MCP server (PID: {}): {}", pid, e))?;
Ok(format!("Claude Code MCP server stopped (PID: {})", pid))
} else {
Ok("Claude Code MCP server is not running".to_string())
}
}
/// Tests connection to an MCP server
#[tauri::command]
pub async fn mcp_test_connection(app: AppHandle, name: String) -> Result<String, String> {
info!("Testing connection to MCP server: {}", name);
// For now, we'll use the get command to test if the server exists
match execute_claude_mcp_command(&app, vec!["get", &name]) {
Ok(_) => Ok(format!("Connection to {} successful", name)),
Err(e) => Err(e.to_string()),
}
}
/// Resets project-scoped server approval choices
#[tauri::command]
pub async fn mcp_reset_project_choices(app: AppHandle) -> Result<String, String> {
info!("Resetting MCP project choices");
match execute_claude_mcp_command(&app, vec!["reset-project-choices"]) {
Ok(output) => {
info!("Successfully reset MCP project choices");
Ok(output.trim().to_string())
}
Err(e) => {
error!("Failed to reset project choices: {}", e);
Err(e.to_string())
}
}
}
/// Gets the status of MCP servers
#[tauri::command]
pub async fn mcp_get_server_status(
registry: tauri::State<'_, crate::process::ProcessRegistryState>,
) -> Result<HashMap<String, ServerStatus>, String> {
info!("Getting MCP server status");
let mut status_map = HashMap::new();
if let Ok(Some(proc_info)) = registry.0.get_running_mcp_serve() {
status_map.insert(
"claude-code".to_string(),
ServerStatus {
running: true,
error: None,
last_checked: Some(Utc::now().timestamp() as u64),
},
);
// Also include PID in the log for debugging
info!("MCP serve running with PID: {}", proc_info.pid);
}
Ok(status_map)
}
/// Reads .mcp.json from the current project
#[tauri::command]
pub async fn mcp_read_project_config(project_path: String) -> Result<MCPProjectConfig, String> {
info!("Reading .mcp.json from project: {}", project_path);
let mcp_json_path = PathBuf::from(&project_path).join(".mcp.json");
if !mcp_json_path.exists() {
return Ok(MCPProjectConfig {
mcp_servers: HashMap::new(),
});
}
match fs::read_to_string(&mcp_json_path) {
Ok(content) => match serde_json::from_str::<MCPProjectConfig>(&content) {
Ok(config) => Ok(config),
Err(e) => {
error!("Failed to parse .mcp.json: {}", e);
Err(format!("Failed to parse .mcp.json: {}", e))
}
},
Err(e) => {
error!("Failed to read .mcp.json: {}", e);
Err(format!("Failed to read .mcp.json: {}", e))
}
}
}
/// Saves .mcp.json to the current project
#[tauri::command]
pub async fn mcp_save_project_config(
project_path: String,
config: MCPProjectConfig,
) -> Result<String, String> {
info!("Saving .mcp.json to project: {}", project_path);
let mcp_json_path = PathBuf::from(&project_path).join(".mcp.json");
let json_content = serde_json::to_string_pretty(&config)
.map_err(|e| format!("Failed to serialize config: {}", e))?;
fs::write(&mcp_json_path, json_content)
.map_err(|e| format!("Failed to write .mcp.json: {}", e))?;
Ok("Project MCP configuration saved".to_string())
}