alou 0.1.0

High-performance Rust implementation of Alou AI agent with MCP tool integration and DeepSeek API support
Documentation
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
798
799
800
801
use crate::types::*;
use crate::mcp_tool::{DiscoveredMcpTool, McpToolFactory};
use crate::types::McpServerConfig;
use crate::tool_registry::ToolRegistry;
use crate::workspace_context::WorkspaceContext;
use crate::prompt_registry::PromptRegistry;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use anyhow::Result;
use serde_json;
use tracing::{info, warn, error};
use std::time::Duration;
use tokio::time::timeout;

// 使用rmcp官方API
use rmcp::{
    transport::TokioChildProcess,
    ServiceExt,
};
use tokio::process::Command;

/// MCP默认超时时间(毫秒)
pub const MCP_DEFAULT_TIMEOUT_MSEC: u64 = 10 * 1000; // 10秒,用于更快的启动

/// MCP服务器状态枚举
#[derive(Debug, Clone, PartialEq)]
pub enum McpServerStatus {
    /// 服务器已断开连接或出现错误
    Disconnected,
    /// 服务器正在连接中
    Connecting,
    /// 服务器已连接并准备使用
    Connected,
}

/// MCP发现状态枚举
#[derive(Debug, Clone, PartialEq)]
pub enum McpDiscoveryState {
    /// 发现尚未开始
    NotStarted,
    /// 发现正在进行中
    InProgress,
    /// 发现已完成(无论是否有错误)
    Completed,
}

/// 发现的MCP提示
#[derive(Debug, Clone)]
pub struct DiscoveredMcpPrompt {
    pub name: String,
    pub description: Option<String>,
    pub arguments: Option<Vec<serde_json::Value>>,
    pub server_name: String,
}

/// MCP客户端
#[derive(Clone)]
pub struct McpClient {
    name: String,
    version: String,
    server_name: String,
    status: McpServerStatus,
    // 存储传输层和客户端状态
    transport: Option<Arc<dyn std::any::Any + Send + Sync>>,
}

impl McpClient {
    /// 创建新的MCP客户端
    pub fn new(name: String, version: String, server_name: String) -> Self {
        Self {
            name,
            version,
            server_name,
            status: McpServerStatus::Disconnected,
            transport: None,
        }
    }

    /// 连接到MCP服务器
    pub async fn connect(&mut self, server_config: &McpServerConfig) -> Result<()> {
        info!("连接到MCP服务器: {}", self.server_name);
        self.status = McpServerStatus::Connecting;

        // 根据服务器配置创建传输层
        let transport = self.create_transport(server_config).await?;
        self.transport = Some(Arc::new(transport));

        self.status = McpServerStatus::Connected;
        info!("MCP客户端连接成功: {}", self.server_name);
        Ok(())
    }

    /// 创建传输层
    async fn create_transport(&self, server_config: &McpServerConfig) -> Result<Box<dyn std::any::Any + Send + Sync>> {
        // 根据配置判断传输类型
        if server_config.command.is_some() {
            // child_process传输
            let command = server_config.command.as_ref()
                .ok_or_else(|| anyhow::anyhow!("child_process传输需要command配置"))?;
            let args = server_config.args.clone().unwrap_or_default();
            let env = server_config.env.clone().unwrap_or_default();
            let cwd = server_config.cwd.clone();
            
            info!("创建child_process传输: {} {:?}", command, args);
            info!("环境变量: {:?}", env);
            info!("工作目录: {:?}", cwd);
            
            // 使用rmcp库的TokioChildProcess
            // 在Windows上,对于npx等命令,可能需要特殊处理
            let mut cmd = if cfg!(target_os = "windows") && command == "npx" {
                let mut cmd = Command::new("cmd");
                cmd.args(&["/c", "npx"]);
                cmd.args(&args);
                cmd
            } else {
                let mut cmd = Command::new(command);
                cmd.args(&args);
                cmd
            };
            
            // 设置环境变量
            for (key, value) in env {
                cmd.env(key, value);
            }
            
            // 设置工作目录
            if let Some(work_dir) = cwd {
                cmd.current_dir(work_dir);
            }
            
            // 添加详细的错误信息
            info!("正在创建child_process传输...");
            
            // 使用spawn来创建非阻塞的传输层
            let transport = tokio::task::spawn_blocking(move || {
                TokioChildProcess::new(cmd)
            }).await
            .map_err(|e| anyhow::anyhow!("创建child_process传输任务失败: {}", e))?
            .map_err(|e| {
                error!("创建child_process传输失败 - 命令: {} 参数: {:?} 错误: {}", command, args, e);
                anyhow::anyhow!("创建child_process传输失败: {}", e)
            })?;
            
            info!("child_process传输创建成功");
            
            info!("成功创建child_process传输");
            Ok(Box::new(transport))
        } else if server_config.url.is_some() {
            // HTTP/SSE传输 - 暂时不支持,因为需要不同的API
            let url = server_config.url.as_ref().unwrap();
            Err(anyhow::anyhow!("HTTP/SSE传输暂时不支持,URL: {}", url))
        } else {
            Err(anyhow::anyhow!("无效的MCP服务器配置:需要command或url"))
        }
    }

    /// 列出可用工具(真实实现)
    pub async fn list_tools(&self) -> Result<Vec<MockTool>> {
        // 检查是否有传输层
        if self.transport.is_none() {
            warn!("MCP客户端 {} 未连接,无法发现工具", self.server_name);
            return Ok(vec![]);
        }

        info!("开始从MCP服务器 {} 发现工具", self.server_name);
        
        // 实现真正的rmcp工具发现
        // 使用rmcp库的客户端API调用tools/list方法
        match self.discover_real_tools().await {
            Ok(real_tools) => {
                info!("从MCP服务器 {} 发现 {} 个真实工具", self.server_name, real_tools.len());
                Ok(real_tools)
            }
            Err(e) => {
                warn!("从MCP服务器 {} 发现真实工具失败: {},返回空列表", self.server_name, e);
                Ok(vec![])
            }
        }
    }

    /// 发现真实工具
    async fn discover_real_tools(&self) -> Result<Vec<MockTool>> {
        // 实现真正的MCP工具发现
        // 使用rmcp库的客户端API调用tools/list方法
        
        // 获取传输层
        let transport = self.transport.as_ref()
            .ok_or_else(|| anyhow::anyhow!("传输层未初始化"))?;
        
        info!("尝试从MCP服务器 {} 发现真实工具", self.server_name);
        
        // 尝试使用真正的rmcp客户端进行工具发现
        match self.try_real_mcp_discovery(transport).await {
            Ok(real_tools) => {
                if !real_tools.is_empty() {
                    info!("从MCP服务器 {} 发现 {} 个真实工具", self.server_name, real_tools.len());
                    return Ok(real_tools);
                }
            }
            Err(e) => {
                warn!("真实MCP工具发现失败: {},回退到模拟工具", e);
            }
        }
        
        // 回退到空列表,因为我们已经删除了模拟工具
        warn!("从MCP服务器 {} 未发现任何工具", self.server_name);
        Ok(vec![])
    }
    
    /// 尝试真正的MCP工具发现
    async fn try_real_mcp_discovery(&self, transport: &Arc<dyn std::any::Any + Send + Sync>) -> Result<Vec<MockTool>> {
        // 实现真正的MCP工具发现
        // 使用直接的JSON-RPC通信
        
        info!("开始真正的MCP工具发现流程");
        
        // 尝试从transport中获取实际的传输层
        // 这里需要将Arc<dyn Any>转换为具体的传输类型
        // 由于rmcp的复杂性,我们使用一个简化的方法
        
        // 创建一个新的进程来直接与MCP服务器通信
        let tools = self.discover_tools_via_process().await?;
        
        if !tools.is_empty() {
            info!("通过进程通信发现 {} 个工具", tools.len());
            return Ok(tools);
        }
        
        warn!("真正的MCP工具发现失败,返回空列表");
        Ok(vec![])
    }

    /// 通过进程通信发现工具
    async fn discover_tools_via_process(&self) -> Result<Vec<MockTool>> {
        use std::process::{Command, Stdio};
        use std::io::{Write, BufRead, BufReader};
        use serde_json::{json, Value};
        use tokio::time::{sleep, Duration};
        
        // 根据服务器名称确定命令和参数
        let (command, args) = match self.server_name.as_str() {
            "filesystem" => ("npx", vec!["@modelcontextprotocol/server-filesystem", "."]),
            "memory" => ("npx", vec!["-y", "@modelcontextprotocol/server-memory"]),
            "payment" => ("python", vec!["-m", "blockchain_payment_mcp.server"]),
            _ => {
                warn!("未知的服务器类型: {}", self.server_name);
                return Ok(vec![]);
            }
        };
        
        info!("启动MCP服务器进程: {} {:?}", command, args);
        
        let mut child = if cfg!(target_os = "windows") && command == "npx" {
            Command::new("cmd")
                .args(&["/c", "npx"])
                .args(&args)
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .spawn()?
        } else {
            Command::new(command)
                .args(&args)
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .spawn()?
        };
        
        let stdin = child.stdin.as_mut().unwrap();
        let stdout = child.stdout.take().unwrap();
        
        // 等待服务器启动
        sleep(Duration::from_millis(2000)).await;
        
        // 发送初始化请求
        let init_request = json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "protocolVersion": "2024-11-05",
                "capabilities": {
                    "tools": {}
                },
                "clientInfo": {
                    "name": "alou-mcp-client",
                    "version": "0.1.0"
                }
            }
        });
        
        writeln!(stdin, "{}", init_request)?;
        stdin.flush()?;
        
        // 等待响应
        sleep(Duration::from_millis(1000)).await;
        
        // 发送tools/list请求
        let tools_request = json!({
            "jsonrpc": "2.0",
            "id": 2,
            "method": "tools/list"
        });
        
        writeln!(stdin, "{}", tools_request)?;
        stdin.flush()?;
        
        // 读取响应
        let reader = BufReader::new(stdout);
        let mut tools = Vec::new();
        
        for line in reader.lines() {
            let line = line?;
            
            // 尝试解析JSON响应
            if let Ok(json) = serde_json::from_str::<Value>(&line) {
                if let Some(result) = json.get("result") {
                    if let Some(tools_array) = result.get("tools") {
                        if let Some(tools_list) = tools_array.as_array() {
                            for tool_json in tools_list {
                                if let Some(tool) = self.parse_mcp_tool(tool_json) {
                                    tools.push(tool);
                                }
                            }
                            break; // 找到工具列表后退出
                        }
                    }
                }
            }
        }
        
        // 清理进程
        let _ = child.kill();
        
        Ok(tools)
    }
    
    /// 解析MCP工具JSON为MockTool
    fn parse_mcp_tool(&self, tool_json: &serde_json::Value) -> Option<MockTool> {
        let name = tool_json.get("name")?.as_str()?.to_string();
        let description = tool_json.get("description").and_then(|d| d.as_str()).map(|s| s.to_string());
        let input_schema = tool_json.get("inputSchema").cloned();
        
        Some(MockTool {
            name,
            description,
            input_schema,
        })
    }

  

    /// 关闭连接
    pub async fn close(&mut self) -> Result<()> {
        info!("关闭MCP客户端连接: {}", self.server_name);
        self.transport = None;
        self.status = McpServerStatus::Disconnected;
        Ok(())
    }

    /// 获取服务器状态
    pub fn get_status(&self) -> &McpServerStatus {
        &self.status
    }

    /// 获取服务器名称
    pub fn get_server_name(&self) -> &str {
        &self.server_name
    }

    /// 列出可用提示(模拟实现)
    pub async fn list_prompts(&self) -> Result<Vec<MockPrompt>> {
        // 暂时返回空列表
        // TODO: 实现真正的rmcp提示发现
        Ok(vec![])
    }

    /// 获取提示(模拟实现)
    pub async fn get_prompt(&self, name: &str, arguments: HashMap<String, serde_json::Value>) -> Result<MockPromptResult> {
        // 暂时返回模拟响应
        // TODO: 实现真正的rmcp提示获取
        Ok(MockPromptResult {
            description: Some(format!("模拟提示: {}", name)),
            messages: vec![],
        })
    }

    /// 调用工具(模拟实现)
    pub async fn call_tool(&self, name: &str, arguments: HashMap<String, serde_json::Value>) -> Result<MockToolResult> {
        // 暂时返回模拟响应
        // TODO: 实现真正的rmcp工具调用
        Ok(MockToolResult {
            content: format!("模拟调用工具: {} 参数: {:?}", name, arguments),
            is_error: false,
        })
    }

}

/// 模拟工具结构
#[derive(Debug, Clone)]
pub struct MockTool {
    pub name: String,
    pub description: Option<String>,
    pub input_schema: Option<serde_json::Value>,
}

/// 模拟工具结果
#[derive(Debug, Clone)]
pub struct MockToolResult {
    pub content: String,
    pub is_error: bool,
}

/// 模拟提示结构
#[derive(Debug, Clone)]
pub struct MockPrompt {
    pub name: String,
    pub description: Option<String>,
    pub arguments: Option<Vec<serde_json::Value>>,
}

/// 模拟提示结果
#[derive(Debug, Clone)]
pub struct MockPromptResult {
    pub description: Option<String>,
    pub messages: Vec<serde_json::Value>,
}

/// MCP客户端管理器
pub struct McpClientManager {
    clients: Arc<RwLock<HashMap<String, Arc<RwLock<McpClient>>>>>,
    server_statuses: Arc<RwLock<HashMap<String, McpServerStatus>>>,
    discovery_state: Arc<RwLock<McpDiscoveryState>>,
}

impl McpClientManager {
    /// 创建新的MCP客户端管理器
    pub fn new() -> Self {
        Self {
            clients: Arc::new(RwLock::new(HashMap::new())),
            server_statuses: Arc::new(RwLock::new(HashMap::new())),
            discovery_state: Arc::new(RwLock::new(McpDiscoveryState::NotStarted)),
        }
    }

    /// 发现所有MCP服务器的工具
    pub async fn discover_mcp_tools(
        &self,
        mcp_servers: HashMap<String, McpServerConfig>,
        tool_registry: Arc<ToolRegistry>,
        prompt_registry: Arc<PromptRegistry>,
        debug_mode: bool,
        workspace_context: Arc<dyn WorkspaceContext + Send + Sync>,
    ) -> Result<()> {
        let mut discovery_state = self.discovery_state.write().await;
        *discovery_state = McpDiscoveryState::InProgress;
        drop(discovery_state);

        let discovery_promises = mcp_servers.into_iter().map(|(server_name, server_config)| {
            self.connect_and_discover(
                server_name,
                server_config,
                tool_registry.clone(),
                prompt_registry.clone(),
                debug_mode,
                workspace_context.clone(),
            )
        });

        // 等待所有发现任务完成
        let results = futures::future::join_all(discovery_promises).await;
        
        // 检查结果
        let mut success_count = 0;
        for result in results {
            if result.is_ok() {
                success_count += 1;
            }
        }

        let mut discovery_state = self.discovery_state.write().await;
        *discovery_state = McpDiscoveryState::Completed;
        
        info!("MCP工具发现完成,成功连接 {} 个服务器", success_count);
        Ok(())
    }

    /// 连接到MCP服务器并发现工具
    async fn connect_and_discover(
        &self,
        server_name: String,
        server_config: McpServerConfig,
        tool_registry: Arc<ToolRegistry>,
        prompt_registry: Arc<PromptRegistry>,
        debug_mode: bool,
        _workspace_context: Arc<dyn WorkspaceContext + Send + Sync>,
    ) -> Result<()> {
        info!("连接MCP服务器: {}", server_name);
        
        // 更新服务器状态
        {
            let mut statuses = self.server_statuses.write().await;
            statuses.insert(server_name.clone(), McpServerStatus::Connecting);
        }

        let mut mcp_client = McpClient::new(
            "alou-mcp-client".to_string(),
            "0.1.0".to_string(),
            server_name.clone(),
        );

        // 设置超时
        let timeout_duration = Duration::from_millis(server_config.timeout.unwrap_or(MCP_DEFAULT_TIMEOUT_MSEC));
        
        let connect_result = timeout(timeout_duration, mcp_client.connect(&server_config)).await;
        
        match connect_result {
            Ok(Ok(())) => {
                info!("已连接到MCP服务器: {}", server_name);
            }
            Ok(Err(e)) => {
                error!("连接MCP服务器 '{}' 失败: {}", server_name, e);
                error!("服务器配置: command={:?}, args={:?}", server_config.command, server_config.args);
                let mut statuses = self.server_statuses.write().await;
                statuses.insert(server_name, McpServerStatus::Disconnected);
                return Err(e);
            }
            Err(_) => {
                error!("连接MCP服务器 '{}' 超时 ({}秒)", server_name, timeout_duration.as_secs());
                error!("服务器配置: command={:?}, args={:?}", server_config.command, server_config.args);
                let mut statuses = self.server_statuses.write().await;
                statuses.insert(server_name, McpServerStatus::Disconnected);
                return Err(anyhow::anyhow!("连接超时"));
            }
        }

        // 发现提示和工具
        // 暂时跳过提示发现,因为需要可变借用
        let prompts: Vec<DiscoveredMcpPrompt> = Vec::new(); // self.discover_prompts(&server_name, &mcp_client, &prompt_registry).await?;
        let tools = self.discover_tools(&server_name, &server_config, &mcp_client).await?;
        
        info!("发现 {} 个工具和 {} 个提示", tools.len(), prompts.len());

        // 如果没有发现任何工具或提示,认为发现失败
        if tools.is_empty() && prompts.is_empty() {
            return Err(anyhow::anyhow!("服务器上未发现任何工具或提示"));
        }

        // 更新服务器状态为已连接
        {
            let mut statuses = self.server_statuses.write().await;
            statuses.insert(server_name.clone(), McpServerStatus::Connected);
        }

        // 注册发现的工具
        for tool in tools {
            info!("注册工具: {}", tool.name());
            tool_registry.register_mcp_tool(Box::new(tool)).await?;
        }

        // 存储客户端
        {
            let mut clients = self.clients.write().await;
            clients.insert(server_name.clone(), Arc::new(RwLock::new(mcp_client)));
        }

        info!("完成连接到MCP服务器: {}", server_name);
        Ok(())
    }


    /// 发现工具
    async fn discover_tools(
        &self,
        server_name: &str,
        server_config: &McpServerConfig,
        mcp_client: &McpClient,
    ) -> Result<Vec<DiscoveredMcpTool>> {
        let tools = mcp_client.list_tools().await?;
        let mut discovered_tools = Vec::new();

        for tool in tools {
            if !self.is_enabled(&tool, server_name, server_config) {
                continue;
            }

            if !self.has_valid_types(&tool) {
                warn!(
                    "跳过工具 '{}' 从MCP服务器 '{}',因为其参数模式中缺少类型。请向MCP服务器的所有者提交问题。",
                    tool.name, server_name
                );
                continue;
            }

            // 创建MCP工具
            let discovered_tool = McpToolFactory::create_discovered_tool(
                Arc::new(RwLock::new(mcp_client.clone())),
                server_name.to_string(),
                tool.name.clone(),
                tool.description.unwrap_or_default(),
                tool.input_schema.unwrap_or_else(|| serde_json::json!({"type": "object", "properties": {}})),
                server_config.timeout,
                server_config.trust,
            );

            discovered_tools.push(discovered_tool);
        }

        Ok(discovered_tools)
    }

    /// 发现提示
    async fn discover_prompts(
        &self,
        server_name: &str,
        mcp_client: &McpClient,
        prompt_registry: &mut PromptRegistry,
    ) -> Result<Vec<DiscoveredMcpPrompt>> {
        let prompts = mcp_client.list_prompts().await?;
        let mut discovered_prompts = Vec::new();

        for prompt in prompts {
            let discovered_prompt = DiscoveredMcpPrompt {
                name: prompt.name.clone(),
                description: prompt.description,
                arguments: prompt.arguments,
                server_name: server_name.to_string(),
            };

            // 创建prompt_registry兼容的提示
            let registry_prompt = crate::prompt_registry::DiscoveredMcpPrompt {
                name: discovered_prompt.name.clone(),
                description: discovered_prompt.description.clone(),
                arguments: discovered_prompt.arguments.clone(),
                server_name: discovered_prompt.server_name.clone(),
                invoke: Box::new(|_args| {
                    Ok(crate::prompt_registry::GetPromptResult {
                        description: Some("Mock prompt result".to_string()),
                        messages: vec![],
                    })
                }),
            };

            // 注册提示到提示注册表
            prompt_registry.register_prompt(registry_prompt);
            discovered_prompts.push(discovered_prompt);
        }

        Ok(discovered_prompts)
    }

    /// 检查工具是否启用
    fn is_enabled(&self, tool: &MockTool, server_name: &str, server_config: &McpServerConfig) -> bool {
        let include_tools = &server_config.include_tools;
        let exclude_tools = &server_config.exclude_tools;

        // excludeTools优先于includeTools
        if let Some(exclude_list) = exclude_tools {
            if exclude_list.contains(&tool.name) {
                return false;
            }
        }

        match include_tools {
            Some(include_list) => {
                include_list.iter().any(|tool_name| {
                    tool_name == &tool.name || tool_name.starts_with(&format!("{}(", tool.name))
                })
            }
            None => true, // 如果没有include列表,默认启用所有工具
        }
    }

    /// 检查模式是否有有效类型
    fn has_valid_types(&self, tool: &MockTool) -> bool {
        if let Some(schema) = &tool.input_schema {
            self.validate_schema_types(schema)
        } else {
            false
        }
    }

    /// 递归验证JSON模式类型
    fn validate_schema_types(&self, schema: &serde_json::Value) -> bool {
        if let Some(obj) = schema.as_object() {
            if obj.contains_key("type") {
                return true;
            }
            
            // 检查是否有子模式
            for keyword in &["anyOf", "allOf", "oneOf"] {
                if let Some(array) = obj.get(&keyword.to_string()).and_then(|v| v.as_array()) {
                    return array.iter().all(|sub_schema| self.validate_schema_types(sub_schema));
                }
            }
        }
        
        false
    }

    /// 获取服务器状态
    pub async fn get_server_status(&self, server_name: &str) -> McpServerStatus {
        let statuses = self.server_statuses.read().await;
        statuses.get(server_name).cloned().unwrap_or(McpServerStatus::Disconnected)
    }

    /// 获取所有服务器状态
    pub async fn get_all_server_statuses(&self) -> HashMap<String, McpServerStatus> {
        let statuses = self.server_statuses.read().await;
        statuses.clone()
    }

    /// 获取发现状态
    pub async fn get_discovery_state(&self) -> McpDiscoveryState {
        let state = self.discovery_state.read().await;
        state.clone()
    }

    /// 获取客户端
    pub async fn get_client(&self, server_name: &str) -> Option<Arc<RwLock<McpClient>>> {
        let clients = self.clients.read().await;
        clients.get(server_name).cloned()
    }

    /// 关闭所有连接
    pub async fn close_all(&self) -> Result<()> {
        let mut clients = self.clients.write().await;
        for (server_name, client) in clients.iter_mut() {
            if let Ok(mut client_guard) = client.try_write() {
                if let Err(e) = client_guard.close().await {
                    error!("关闭MCP客户端 '{}' 失败: {}", server_name, e);
                }
            }
        }
        clients.clear();
        
        let mut statuses = self.server_statuses.write().await;
        statuses.clear();
        
        let mut discovery_state = self.discovery_state.write().await;
        *discovery_state = McpDiscoveryState::NotStarted;
        
        Ok(())
    }
}

impl Default for McpClientManager {
    fn default() -> Self {
        Self::new()
    }
}

/// 错误消息提取
fn get_error_message(error: &dyn std::error::Error) -> String {
    error.to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_mcp_client_creation() {
        let client = McpClient::new("test-client".to_string(), "1.0.0".to_string(), "test-server".to_string());
        assert_eq!(client.name, "test-client");
        assert_eq!(client.version, "1.0.0");
        assert_eq!(client.server_name, "test-server");
    }

    #[tokio::test]
    async fn test_mcp_client_manager_creation() {
        let manager = McpClientManager::new();
        let state = manager.get_discovery_state().await;
        assert_eq!(state, McpDiscoveryState::NotStarted);
    }

    #[test]
    fn test_validate_schema_types() {
        let manager = McpClientManager::new();
        
        let valid_schema = serde_json::json!({
            "type": "object",
            "properties": {
                "name": {"type": "string"}
            }
        });
        
        assert!(manager.validate_schema_types(&valid_schema));
        
        let invalid_schema = serde_json::json!({
            "properties": {
                "name": {"type": "string"}
            }
        });
        
        assert!(!manager.validate_schema_types(&invalid_schema));
    }
}