Skip to main content

infinity_agent_core/tools/
config.rs

1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3
4/// Configuration for a single toolset server entry.
5#[derive(Debug, Clone, Deserialize, Serialize)]
6#[serde(tag = "type", rename_all = "snake_case")]
7pub enum ToolSetConfig {
8    /// RAP toolset server — tools are loaded via `.well-known/rap-toolset`.
9    ToolsetServer {
10        server_url: String,
11        #[serde(default, skip_serializing_if = "Option::is_none")]
12        id: Option<String>,
13    },
14    /// RAP toolset server launched via a CLI command.
15    /// The command is spawned with `RAP_EMBEDDED=1` and must emit a JSON
16    /// object on stdout containing `{ "port": <u16> }` once it is ready.
17    ToolsetCommand {
18        command: String,
19        #[serde(default, skip_serializing_if = "Option::is_none")]
20        id: Option<String>,
21        #[serde(default, skip_serializing_if = "Option::is_none")]
22        crate_name: Option<String>,
23        #[serde(default, skip_serializing_if = "Option::is_none")]
24        git: Option<String>,
25        #[serde(default, skip_serializing_if = "Option::is_none")]
26        path: Option<String>,
27    },
28    /// MCP server proxied behind RAP. The CLI spawns the command as a stdio
29    /// subprocess and runs an in-process RAP server that translates between
30    /// the two protocols.
31    McpServer {
32        name: String,
33        command: Vec<String>,
34        #[serde(default)]
35        env: HashMap<String, String>,
36        #[serde(default, skip_serializing_if = "Option::is_none")]
37        id: Option<String>,
38    },
39    /// Remote MCP server over HTTP, proxied behind RAP.
40    HttpMcpServer {
41        name: String,
42        url: String,
43        #[serde(default)]
44        headers: HashMap<String, String>,
45        #[serde(default, skip_serializing_if = "Option::is_none")]
46        id: Option<String>,
47    },
48}
49
50impl ToolSetConfig {
51    /// Optional identifier used for deduplication during config merging.
52    pub fn id(&self) -> Option<&str> {
53        match self {
54            ToolSetConfig::ToolsetServer { id, .. }
55            | ToolSetConfig::ToolsetCommand { id, .. }
56            | ToolSetConfig::McpServer { id, .. }
57            | ToolSetConfig::HttpMcpServer { id, .. } => id.as_deref(),
58        }
59    }
60}
61
62/// JSON object emitted on stdout by a command-based RAP server at startup.
63#[derive(Debug, Deserialize)]
64pub struct CommandServerReady {
65    pub port: u16,
66}
67
68#[derive(Debug, Clone, Deserialize, Serialize)]
69pub struct ToolsConfig {
70    pub tool_sets: Vec<ToolSetConfig>,
71}
72
73impl ToolsConfig {
74    pub fn empty() -> Self {
75        Self {
76            tool_sets: Vec::new(),
77        }
78    }
79
80    pub fn merge(&mut self, other: ToolsConfig) {
81        let existing_ids: std::collections::HashSet<String> = self
82            .tool_sets
83            .iter()
84            .filter_map(|ts| ts.id().map(|s| s.to_owned()))
85            .collect();
86        for ts in other.tool_sets {
87            if let Some(id) = ts.id()
88                && existing_ids.contains(id)
89            {
90                continue;
91            }
92            self.tool_sets.push(ts);
93        }
94    }
95
96    pub fn add_installed_command(
97        &mut self,
98        command: String,
99        crate_name: String,
100        git: Option<String>,
101        path: Option<String>,
102    ) {
103        self.tool_sets.push(ToolSetConfig::ToolsetCommand {
104            id: Some(crate_name.clone()),
105            command,
106            crate_name: Some(crate_name),
107            git,
108            path,
109        });
110    }
111
112    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
113        serde_json::from_str(json)
114    }
115
116    pub fn from_env() -> Result<Self, Box<dyn std::error::Error>> {
117        let config_str = std::env::var("TOOLS_CONFIG")?;
118        let config = serde_json::from_str(&config_str)?;
119        Ok(config)
120    }
121
122    pub fn from_file(
123        path: impl AsRef<std::path::Path>,
124    ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
125        let content = std::fs::read_to_string(path)?;
126        let config = serde_json::from_str(&content)?;
127        Ok(config)
128    }
129
130    /// Extract server URLs from entries that already have a URL: (url, id).
131    pub fn toolset_server_urls(&self) -> Vec<(String, Option<String>)> {
132        self.tool_sets
133            .iter()
134            .filter_map(|ts| match ts {
135                ToolSetConfig::ToolsetServer { server_url, id, .. } => {
136                    Some((server_url.clone(), id.clone()))
137                }
138                _ => None,
139            })
140            .collect()
141    }
142
143    /// Return toolset commands that have installation source info (for `rap update`).
144    pub fn installable_commands(&self) -> Vec<(String, String, Option<String>, Option<String>)> {
145        self.tool_sets
146            .iter()
147            .filter_map(|ts| match ts {
148                ToolSetConfig::ToolsetCommand {
149                    command,
150                    crate_name: Some(cn),
151                    git,
152                    path,
153                    ..
154                } => Some((command.clone(), cn.clone(), git.clone(), path.clone())),
155                _ => None,
156            })
157            .collect()
158    }
159}