ai-agents-tools 1.0.5

Tool system for AI Agents framework
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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
//! MCP wrapper tool — presents an MCP server as a single builtin Tool.
//!
//! Each instance wraps one MCP server connection and presents ALL of the
//! server's functions through a single tool with a `function` discriminator
//! field, matching the pattern used by `datetime`, `math`, `json`, etc.

use async_trait::async_trait;
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::HashMap;

use rmcp::model as mcp_model;
use rmcp::service::{Peer, RunningService};
use rmcp::{RoleClient, ServiceExt};

use ai_agents_core::{Tool, ToolExecutionContext, ToolPolicyBindings, ToolResult};

/// A discovered function from an MCP server (name, description, schema).
#[derive(Debug, Clone)]
pub(crate) struct DiscoveredFunction {
    /// Original function name as reported by the MCP server.
    pub(crate) name: String,
    /// Human-readable description of the function.
    pub(crate) description: String,
    /// JSON Schema for the function's parameters.
    pub(crate) input_schema: Value,
}

/// Configuration for the MCP wrapper tool, deserialized from YAML.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPWrapperConfig {
    /// Display name for this tool (also used as the tool ID).
    pub name: String,

    /// Transport configuration (stdio, http, or sse).
    #[serde(flatten)]
    pub transport: MCPWrapperTransport,

    /// Environment variables passed to the server process.
    #[serde(default)]
    pub env: HashMap<String, String>,

    /// Startup timeout in milliseconds.
    #[serde(default = "default_startup_timeout")]
    pub startup_timeout_ms: u64,

    /// Security settings for function-level blocking and HITL.
    #[serde(default)]
    pub security: MCPWrapperSecurity,

    /// Optional custom description override.
    /// If not set, auto-generated from discovered functions.
    #[serde(default)]
    pub description: Option<String>,

    /// Named views: subsets of this server's functions registered as separate tools.
    #[serde(default)]
    pub views: HashMap<String, MCPViewConfig>,
}

fn default_startup_timeout() -> u64 {
    30_000
}

/// Transport configuration for connecting to an MCP server.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "transport", rename_all = "lowercase")]
pub enum MCPWrapperTransport {
    Stdio {
        command: String,
        #[serde(default)]
        args: Vec<String>,
    },
    Http {
        url: String,
        #[serde(default)]
        headers: HashMap<String, String>,
    },
    #[serde(alias = "sse")]
    Sse {
        url: String,
        #[serde(default)]
        headers: HashMap<String, String>,
    },
}

/// Security settings for the MCP wrapper tool.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct MCPWrapperSecurity {
    /// Functions that should never be exposed to the LLM.
    #[serde(default)]
    pub blocked_functions: Vec<String>,

    /// Functions that require HITL approval before execution.
    #[serde(default)]
    pub hitl_functions: Vec<String>,
}

/// Configuration for a single MCP view (a named function subset).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPViewConfig {
    /// Whitelist of function names to include in this view.
    pub functions: Vec<String>,
    /// Optional custom description for this view tool.
    #[serde(default)]
    pub description: Option<String>,
}

/// An MCP server exposed as a single builtin Tool.
///
/// Connects to an MCP server at initialization, discovers available functions
/// via `peer.list_tools()`, and builds a dynamic `input_schema()` with
/// `function` as an enum of discovered names and `params` as per-function
/// parameters. Uses two-phase construction: `new()` then `initialized()`.
pub struct MCPWrapperTool {
    config: MCPWrapperConfig,
    /// Immutable after `initialized()` — tool description shown to the LLM.
    description: String,
    /// Immutable after `initialized()` — JSON Schema for the tool's input.
    schema: Value,
    /// Running service handle — kept alive so the background task is not dropped.
    _running: RwLock<Option<RunningService<RoleClient, ()>>>,
    /// Peer for issuing MCP requests.
    peer: RwLock<Option<Peer<RoleClient>>>,
    /// Discovered functions from the MCP server (populated after init).
    functions: Vec<DiscoveredFunction>,
}

impl MCPWrapperTool {
    /// Create a new wrapper tool from configuration.
    /// The tool is NOT connected yet — call `initialized()` to connect and discover.
    pub fn new(config: MCPWrapperConfig) -> Self {
        let desc = config
            .description
            .clone()
            .unwrap_or_else(|| format!("{} operations via MCP", config.name));
        Self {
            config,
            description: desc,
            schema: json!({"type": "object"}),
            _running: RwLock::new(None),
            peer: RwLock::new(None),
            functions: Vec::new(),
        }
    }

    /// Connect to the MCP server, discover functions, and build schema/description.
    /// Returns a new `MCPWrapperTool` with the discovered state baked in.
    pub async fn initialized(mut self) -> Result<Self, String> {
        let running = match &self.config.transport {
            MCPWrapperTransport::Stdio { command, args } => {
                Self::connect_stdio(command, args, &self.config.env, &self.config.name).await?
            }
            MCPWrapperTransport::Http { url, headers }
            | MCPWrapperTransport::Sse { url, headers } => {
                Self::connect_http(url, headers, &self.config.name).await?
            }
        };

        let peer = running.peer().clone();

        // Discover functions from the MCP server
        let tool_list = peer
            .list_all_tools()
            .await
            .map_err(|e| format!("Failed to list tools from '{}': {}", self.config.name, e))?;

        let mut functions = Vec::new();
        for tool in &tool_list {
            let name = tool.name.to_string();

            // Skip blocked functions
            if self.config.security.blocked_functions.contains(&name) {
                tracing::debug!(
                    server = %self.config.name,
                    function = %name,
                    "Skipping blocked MCP function"
                );
                continue;
            }

            let description = tool
                .description
                .as_ref()
                .map(|d| d.to_string())
                .unwrap_or_default();

            let input_schema = Value::Object(tool.input_schema.as_ref().clone());

            functions.push(DiscoveredFunction {
                name,
                description,
                input_schema,
            });
        }

        tracing::info!(
            server = %self.config.name,
            functions = functions.len(),
            "MCP wrapper tool initialized"
        );

        // Build immutable schema and description
        self.schema = Self::build_schema(&self.config.name, &functions);
        self.description = Self::build_description(
            &self.config.name,
            self.config.description.as_deref(),
            &functions,
        );
        self.functions = functions;
        *self.peer.write() = Some(peer);
        *self._running.write() = Some(running);

        Ok(self)
    }

    /// Build the dynamic input schema from discovered functions.
    pub(crate) fn build_schema(server_name: &str, functions: &[DiscoveredFunction]) -> Value {
        let function_names: Vec<Value> = functions
            .iter()
            .map(|f| Value::String(f.name.clone()))
            .collect();

        // Build per-function parameter hints for the LLM
        let mut params_description =
            String::from("Parameters for the selected function. See function list for details.");

        if functions.len() <= 30 {
            params_description = String::from("Parameters for the selected function:\n");
            for f in functions {
                if let Some(props) = f.input_schema.get("properties") {
                    let prop_names: Vec<&str> = props
                        .as_object()
                        .map(|obj| obj.keys().map(|k| k.as_str()).collect())
                        .unwrap_or_default();
                    if !prop_names.is_empty() {
                        params_description.push_str(&format!(
                            "  - {}: {{{}}}\n",
                            f.name,
                            prop_names.join(", ")
                        ));
                    } else {
                        params_description.push_str(&format!("  - {}: (no parameters)\n", f.name));
                    }
                }
            }
        }

        json!({
            "type": "object",
            "required": ["function"],
            "properties": {
                "function": {
                    "type": "string",
                    "description": format!("The function to call inside the '{}' tool. Pass this as arguments.function, NOT as the tool name.", server_name),
                    "enum": function_names
                },
                "params": {
                    "type": "object",
                    "description": params_description,
                    "additionalProperties": true
                }
            }
        })
    }

    /// Build a rich description listing all available functions.
    pub(crate) fn build_description(
        server_name: &str,
        custom: Option<&str>,
        functions: &[DiscoveredFunction],
    ) -> String {
        let mut desc = match custom {
            Some(c) if !c.is_empty() => c.to_string(),
            _ => format!("{} operations via MCP.", server_name),
        };

        if !functions.is_empty() {
            // Clarify the dispatch pattern: the tool name is server_name,
            // function names go inside arguments.function.
            desc.push_str(&format!(
                " Use tool '{}' with arguments.function set to one of: ",
                server_name
            ));
            let names: Vec<&str> = functions.iter().map(|f| f.name.as_str()).collect();
            desc.push_str(&names.join(", "));
            desc.push('.');

            // Add per-function descriptions for smaller function sets
            if functions.len() <= 20 {
                desc.push_str("\n\nFunction details:");
                for f in functions {
                    if !f.description.is_empty() {
                        desc.push_str(&format!("\n- {}: {}", f.name, f.description));
                    } else {
                        desc.push_str(&format!("\n- {}", f.name));
                    }
                }
            }
        }

        desc
    }

    /// Execute a function call on the MCP server.
    pub(crate) async fn call_function(&self, function: &str, params: Value) -> ToolResult {
        // Validate that the function exists
        if !self.functions.iter().any(|f| f.name == function) {
            let available: Vec<&str> = self.functions.iter().map(|f| f.name.as_str()).collect();
            return ToolResult::error(format!(
                "Unknown function '{}'. Available functions: {}",
                function,
                available.join(", ")
            ));
        }

        let peer = {
            let peer_guard = self.peer.read();
            match peer_guard.as_ref() {
                Some(p) => p.clone(),
                None => {
                    return ToolResult::error(format!(
                        "MCP server '{}' not initialized",
                        self.config.name
                    ));
                }
            }
        };

        let mut call_params = mcp_model::CallToolRequestParams::new(function.to_string());
        if let Value::Object(map) = params {
            call_params.arguments = Some(map.into_iter().collect());
        }

        match peer.call_tool(call_params).await {
            Ok(result) => {
                let output = result
                    .content
                    .iter()
                    .filter_map(|c| match &c.raw {
                        mcp_model::RawContent::Text(t) => Some(t.text.as_str()),
                        _ => None,
                    })
                    .collect::<Vec<_>>()
                    .join("\n");

                if result.is_error.unwrap_or(false) {
                    ToolResult::error(output)
                } else {
                    ToolResult::ok(output)
                }
            }
            Err(e) => ToolResult::error(format!("MCP function '{}' failed: {}", function, e)),
        }
    }

    /// Return the subset of discovered functions matching the given names.
    pub(crate) fn get_functions_filtered(&self, names: &[String]) -> Vec<DiscoveredFunction> {
        self.functions
            .iter()
            .filter(|f| names.iter().any(|n| n == &f.name))
            .cloned()
            .collect()
    }

    /// Connect to an MCP server via stdio transport.
    async fn connect_stdio(
        command: &str,
        args: &[String],
        env: &HashMap<String, String>,
        server_name: &str,
    ) -> Result<RunningService<RoleClient, ()>, String> {
        use rmcp::transport::TokioChildProcess;
        use tokio::process::Command;

        let mut cmd = Command::new(command);
        cmd.args(args);
        for (key, value) in env {
            cmd.env(key, value);
        }

        let transport = TokioChildProcess::new(cmd)
            .map_err(|e| format!("Failed to spawn '{}': {}", command, e))?;

        let running: RunningService<RoleClient, ()> = ()
            .serve(transport)
            .await
            .map_err(|e| format!("Failed MCP handshake with '{}': {}", server_name, e))?;

        Ok(running)
    }

    /// Connect to an MCP server via HTTP/SSE transport.
    async fn connect_http(
        url: &str,
        headers: &HashMap<String, String>,
        server_name: &str,
    ) -> Result<RunningService<RoleClient, ()>, String> {
        use rmcp::transport::streamable_http_client::{
            StreamableHttpClientTransport, StreamableHttpClientTransportConfig,
        };

        if headers.is_empty() {
            let transport = StreamableHttpClientTransport::from_uri(url);
            let running: RunningService<RoleClient, ()> = ()
                .serve(transport)
                .await
                .map_err(|e| format!("Failed HTTP MCP connection to '{}': {}", server_name, e))?;
            Ok(running)
        } else {
            use reqwest::header::{HeaderName, HeaderValue};

            let mut custom_headers = HashMap::new();
            for (key, value) in headers {
                let header_name = HeaderName::try_from(key.as_str())
                    .map_err(|e| format!("Invalid header name '{}': {}", key, e))?;
                let header_value = HeaderValue::try_from(value.as_str())
                    .map_err(|e| format!("Invalid header value for '{}': {}", key, e))?;
                custom_headers.insert(header_name, header_value);
            }

            let config =
                StreamableHttpClientTransportConfig::with_uri(url).custom_headers(custom_headers);
            let transport = StreamableHttpClientTransport::from_config(config);

            let running: RunningService<RoleClient, ()> = ()
                .serve(transport)
                .await
                .map_err(|e| format!("Failed HTTP MCP connection to '{}': {}", server_name, e))?;
            Ok(running)
        }
    }

    /// Gracefully shut down the MCP server connection.
    pub async fn shutdown(&self) {
        let running = self._running.write().take();
        if let Some(r) = running {
            let _ = r.cancel().await;
        }
        self.peer.write().take();
    }

    /// Check if a specific function requires HITL approval.
    pub fn requires_hitl(&self, function_name: &str) -> bool {
        self.config
            .security
            .hitl_functions
            .iter()
            .any(|f| f == function_name)
    }

    /// Get the number of discovered functions.
    pub fn function_count(&self) -> usize {
        self.functions.len()
    }

    /// Get the list of discovered function names.
    pub fn function_names(&self) -> Vec<&str> {
        self.functions.iter().map(|f| f.name.as_str()).collect()
    }
}

#[async_trait]
impl Tool for MCPWrapperTool {
    fn id(&self) -> &str {
        &self.config.name
    }

    fn name(&self) -> &str {
        &self.config.name
    }

    fn description(&self) -> &str {
        &self.description
    }

    fn input_schema(&self) -> Value {
        self.schema.clone()
    }

    fn policy_bindings(&self) -> ToolPolicyBindings {
        ToolPolicyBindings {
            operation_fields: vec!["function".to_string()],
            ..Default::default()
        }
    }

    async fn execute(&self, args: Value, ctx: ToolExecutionContext) -> ToolResult {
        // Extract the `function` field from input
        let function = match args.get("function").and_then(|v| v.as_str()) {
            Some(f) => f.to_string(),
            None => {
                let available: Vec<&str> = self.functions.iter().map(|f| f.name.as_str()).collect();
                return ToolResult::error(format!(
                    "'function' is required. Available functions: {}",
                    available.join(", ")
                ));
            }
        };

        // Extract optional `params` field (defaults to empty object)
        let params = args.get("params").cloned().unwrap_or_else(|| json!({}));

        // Per-function HITL: signal the runtime via metadata if approval is needed.
        // The runtime's HITL engine sees the tool ID ("github"), not the function.
        // For per-function granularity, we return metadata that the runtime can inspect.
        if self.requires_hitl(&function) {
            return ToolResult::ok_with_metadata(
                format!(
                    "Function '{}' on MCP server '{}' requires approval before execution.",
                    function, self.config.name
                ),
                HashMap::from([
                    ("_hitl_required".to_string(), json!(true)),
                    ("_hitl_function".to_string(), json!(function)),
                    ("_hitl_params".to_string(), params.clone()),
                    ("_hitl_tool".to_string(), json!(self.config.name)),
                ]),
            );
        }

        let mut result = self.call_function(&function, params).await;
        let metadata = result.metadata.get_or_insert_with(HashMap::new);
        metadata.insert("mcp_parent_id".to_string(), json!(ctx.canonical_id));
        metadata.insert("mcp_function".to_string(), json!(function));
        result
    }
}

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

    #[test]
    fn test_mcp_wrapper_config_deserialize_stdio() {
        let yaml = r#"
name: github
type: mcp
transport: stdio
command: npx
args: ["-y", "@modelcontextprotocol/server-github"]
env:
  GITHUB_TOKEN: "test-token"
startup_timeout_ms: 15000
security:
  blocked_functions: [delete_repo]
  hitl_functions: [create_issue]
"#;
        let config: MCPWrapperConfig = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.name, "github");
        assert_eq!(config.startup_timeout_ms, 15000);
        assert_eq!(config.security.blocked_functions, vec!["delete_repo"]);
        assert_eq!(config.security.hitl_functions, vec!["create_issue"]);
    }

    #[test]
    fn test_mcp_wrapper_config_deserialize_http() {
        let yaml = r#"
name: custom_api
type: mcp
transport: http
url: "http://localhost:3000/mcp"
headers:
  Authorization: "Bearer test"
"#;
        let config: MCPWrapperConfig = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.name, "custom_api");
    }

    #[test]
    fn test_build_schema() {
        let functions = vec![
            DiscoveredFunction {
                name: "create_issue".to_string(),
                description: "Create a new issue".to_string(),
                input_schema: json!({
                    "type": "object",
                    "properties": {
                        "repo": {"type": "string"},
                        "title": {"type": "string"},
                        "body": {"type": "string"}
                    },
                    "required": ["repo", "title"]
                }),
            },
            DiscoveredFunction {
                name: "list_repos".to_string(),
                description: "List repositories".to_string(),
                input_schema: json!({
                    "type": "object",
                    "properties": {
                        "org": {"type": "string"}
                    }
                }),
            },
        ];

        let schema = MCPWrapperTool::build_schema("github", &functions);

        assert_eq!(schema["type"], "object");
        assert!(
            schema["required"]
                .as_array()
                .unwrap()
                .contains(&json!("function"))
        );
        let func_enum = &schema["properties"]["function"]["enum"];
        assert!(
            func_enum
                .as_array()
                .unwrap()
                .contains(&json!("create_issue"))
        );
        assert!(func_enum.as_array().unwrap().contains(&json!("list_repos")));
    }

    #[test]
    fn test_build_description() {
        let functions = vec![
            DiscoveredFunction {
                name: "create_issue".to_string(),
                description: "Create a new issue".to_string(),
                input_schema: json!({}),
            },
            DiscoveredFunction {
                name: "list_repos".to_string(),
                description: "List repositories".to_string(),
                input_schema: json!({}),
            },
        ];

        let desc = MCPWrapperTool::build_description("github", None, &functions);

        assert!(desc.contains("github operations via MCP"));
        assert!(desc.contains("Use tool 'github'"));
        assert!(desc.contains("create_issue"));
        assert!(desc.contains("list_repos"));
        assert!(desc.contains("Create a new issue"));
    }

    #[test]
    fn test_requires_hitl() {
        let config = MCPWrapperConfig {
            name: "github".to_string(),
            transport: MCPWrapperTransport::Stdio {
                command: "npx".to_string(),
                args: vec![],
            },
            env: HashMap::new(),
            startup_timeout_ms: 30000,
            security: MCPWrapperSecurity {
                blocked_functions: vec![],
                hitl_functions: vec!["create_issue".to_string()],
            },
            description: None,
            views: HashMap::new(),
        };
        let tool = MCPWrapperTool::new(config);

        assert!(tool.requires_hitl("create_issue"));
        assert!(!tool.requires_hitl("list_repos"));
    }

    #[test]
    fn test_default_description() {
        let config = MCPWrapperConfig {
            name: "github".to_string(),
            transport: MCPWrapperTransport::Stdio {
                command: "npx".to_string(),
                args: vec![],
            },
            env: HashMap::new(),
            startup_timeout_ms: 30000,
            security: MCPWrapperSecurity::default(),
            description: None,
            views: HashMap::new(),
        };
        let tool = MCPWrapperTool::new(config);
        assert_eq!(tool.description(), "github operations via MCP");
    }

    #[test]
    fn test_custom_description() {
        let config = MCPWrapperConfig {
            name: "github".to_string(),
            transport: MCPWrapperTransport::Stdio {
                command: "npx".to_string(),
                args: vec![],
            },
            env: HashMap::new(),
            startup_timeout_ms: 30000,
            security: MCPWrapperSecurity::default(),
            description: Some("GitHub integration for DevOps".to_string()),
            views: HashMap::new(),
        };
        let tool = MCPWrapperTool::new(config);
        assert_eq!(tool.description(), "GitHub integration for DevOps");
    }

    #[test]
    fn test_view_config_deserialize() {
        let yaml = r#"
functions: [create_issue, list_issues]
description: "Issue management"
"#;
        let config: MCPViewConfig = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.functions, vec!["create_issue", "list_issues"]);
        assert_eq!(config.description.as_deref(), Some("Issue management"));
    }

    #[test]
    fn test_view_config_no_description() {
        let yaml = r#"
functions: [search_code, get_pull_request]
"#;
        let config: MCPViewConfig = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.functions, vec!["search_code", "get_pull_request"]);
        assert!(config.description.is_none());
    }

    #[test]
    fn test_mcp_config_with_views() {
        let yaml = r#"
name: github
type: mcp
transport: stdio
command: npx
args: ["-y", "@modelcontextprotocol/server-github"]
views:
  github_issues:
    functions: [create_issue, list_issues]
  github_code:
    functions: [search_code]
    description: "Code search"
"#;
        let config: MCPWrapperConfig = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.views.len(), 2);
        assert_eq!(
            config.views["github_issues"].functions,
            vec!["create_issue", "list_issues"]
        );
        assert_eq!(
            config.views["github_code"].description.as_deref(),
            Some("Code search")
        );
    }

    #[test]
    fn test_mcp_config_without_views() {
        let yaml = r#"
name: github
type: mcp
transport: stdio
command: npx
args: ["-y", "@modelcontextprotocol/server-github"]
"#;
        let config: MCPWrapperConfig = serde_yaml::from_str(yaml).unwrap();
        assert!(config.views.is_empty());
    }

    #[test]
    fn test_tool_entry_mcp_with_views() {
        let yaml = r#"
name: github
type: mcp
transport: stdio
command: npx
args: ["-y", "@modelcontextprotocol/server-github"]
env:
  GITHUB_TOKEN: "test"
views:
  github_issues:
    functions: [create_issue, list_issues]
  github_code:
    functions: [search_code]
    description: "Code search"
"#;
        let config: MCPWrapperConfig = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.views.len(), 2);
        assert_eq!(
            config.views["github_issues"].functions,
            vec!["create_issue", "list_issues"]
        );
    }

    #[test]
    fn test_view_schema_filtered() {
        let functions = vec![
            DiscoveredFunction {
                name: "create_issue".to_string(),
                description: "Create a new issue".to_string(),
                input_schema: json!({
                    "type": "object",
                    "properties": {
                        "repo": {"type": "string"},
                        "title": {"type": "string"}
                    }
                }),
            },
            DiscoveredFunction {
                name: "list_issues".to_string(),
                description: "List issues".to_string(),
                input_schema: json!({
                    "type": "object",
                    "properties": {
                        "repo": {"type": "string"}
                    }
                }),
            },
        ];

        let schema = MCPWrapperTool::build_schema("github_issues", &functions);
        let func_enum = schema["properties"]["function"]["enum"].as_array().unwrap();
        assert_eq!(func_enum.len(), 2);
        assert!(func_enum.contains(&json!("create_issue")));
        assert!(func_enum.contains(&json!("list_issues")));
    }

    #[test]
    fn test_view_description_custom() {
        let functions = vec![DiscoveredFunction {
            name: "create_issue".to_string(),
            description: "Create a new issue".to_string(),
            input_schema: json!({}),
        }];

        let desc = MCPWrapperTool::build_description(
            "github_issues",
            Some("Issue management"),
            &functions,
        );
        assert!(desc.starts_with("Issue management"));
        assert!(desc.contains("create_issue"));
    }
}