anveesa 0.7.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/main.rs DELETED
@@ -1,4 +0,0 @@
1
- #[tokio::main]
2
- async fn main() -> anyhow::Result<()> {
3
- anveesa::run_anveesa().await
4
- }
package/src/mcp.rs DELETED
@@ -1,243 +0,0 @@
1
- //! MCP (Model Context Protocol) client — connects to external tool servers
2
- //! over JSON-RPC / stdio, discovers their tools, and routes calls to them.
3
-
4
- use std::collections::BTreeMap;
5
-
6
- use anyhow::{Context, Result, bail};
7
- use serde_json::{Value, json};
8
- use tokio::{
9
- io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
10
- process::Child,
11
- sync::Mutex,
12
- };
13
-
14
- use crate::config::McpServerConfig;
15
-
16
- // ── Tool definition exposed to the rest of anveesa ───────────────────────────
17
-
18
- #[derive(Debug, Clone)]
19
- pub struct McpTool {
20
- /// Namespaced as mcp__{server}__{original_name}
21
- pub name: String,
22
- pub description: String,
23
- pub input_schema: Value,
24
- pub server: String,
25
- pub original_name: String,
26
- }
27
-
28
- impl McpTool {
29
- /// Convert to an OpenAI-compatible function definition.
30
- pub fn to_definition(&self) -> Value {
31
- json!({
32
- "type": "function",
33
- "function": {
34
- "name": self.name,
35
- "description": format!("[MCP:{}] {}", self.server, self.description),
36
- "parameters": self.input_schema,
37
- }
38
- })
39
- }
40
- }
41
-
42
- // ── Single MCP server connection ──────────────────────────────────────────────
43
-
44
- struct McpServer {
45
- name: String,
46
- stdin: Mutex<tokio::process::ChildStdin>,
47
- stdout: Mutex<BufReader<tokio::process::ChildStdout>>,
48
- next_id: Mutex<u64>,
49
- _child: Child,
50
- }
51
-
52
- impl McpServer {
53
- async fn connect(name: &str, cfg: &McpServerConfig) -> Result<(Self, Vec<McpTool>)> {
54
- let mut child = tokio::process::Command::new(&cfg.command)
55
- .args(&cfg.args)
56
- .envs(&cfg.env)
57
- .stdin(std::process::Stdio::piped())
58
- .stdout(std::process::Stdio::piped())
59
- .stderr(std::process::Stdio::null())
60
- .kill_on_drop(true)
61
- .spawn()
62
- .with_context(|| format!("failed to start MCP server '{name}' ({})", cfg.command))?;
63
-
64
- let stdin = child.stdin.take().context("MCP server has no stdin")?;
65
- let stdout = BufReader::new(child.stdout.take().context("MCP server has no stdout")?);
66
-
67
- let server = Self {
68
- name: name.to_string(),
69
- stdin: Mutex::new(stdin),
70
- stdout: Mutex::new(stdout),
71
- next_id: Mutex::new(1),
72
- _child: child,
73
- };
74
-
75
- server.initialize().await?;
76
- let tools = server.list_tools().await?;
77
- Ok((server, tools))
78
- }
79
-
80
- async fn send_msg(&self, msg: Value) -> Result<()> {
81
- let line = serde_json::to_string(&msg)? + "\n";
82
- let mut stdin = self.stdin.lock().await;
83
- stdin.write_all(line.as_bytes()).await?;
84
- stdin.flush().await?;
85
- Ok(())
86
- }
87
-
88
- async fn recv_msg(&self) -> Result<Value> {
89
- let mut stdout = self.stdout.lock().await;
90
- let mut line = String::new();
91
- stdout.read_line(&mut line).await.context("MCP server closed")?;
92
- if line.is_empty() { bail!("MCP server closed connection"); }
93
- Ok(serde_json::from_str(line.trim())?)
94
- }
95
-
96
- async fn request(&self, method: &str, params: Value) -> Result<Value> {
97
- let id = {
98
- let mut n = self.next_id.lock().await;
99
- let v = *n;
100
- *n += 1;
101
- v
102
- };
103
- self.send_msg(json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params })).await?;
104
-
105
- // Wait for our response with a timeout
106
- let timeout = tokio::time::Duration::from_secs(30);
107
- let result = tokio::time::timeout(timeout, async {
108
- loop {
109
- let resp = self.recv_msg().await?;
110
- if resp.get("id").and_then(|v| v.as_u64()) == Some(id) {
111
- if let Some(err) = resp.get("error") {
112
- anyhow::bail!("MCP error from '{}': {}", self.name, err);
113
- }
114
- return Ok(resp["result"].clone());
115
- }
116
- // Drop unmatched messages (notifications, other ids)
117
- }
118
- })
119
- .await
120
- .context(format!("MCP request to '{}' timed out after 30s", self.name))??;
121
- Ok(result)
122
- }
123
-
124
- async fn notify(&self, method: &str, params: Value) -> Result<()> {
125
- self.send_msg(json!({ "jsonrpc": "2.0", "method": method, "params": params })).await
126
- }
127
-
128
- async fn initialize(&self) -> Result<()> {
129
- self.request("initialize", json!({
130
- "protocolVersion": "2024-11-05",
131
- "capabilities": {},
132
- "clientInfo": { "name": "anveesa", "version": env!("CARGO_PKG_VERSION") }
133
- })).await?;
134
- self.notify("notifications/initialized", json!({})).await?;
135
- Ok(())
136
- }
137
-
138
- async fn list_tools(&self) -> Result<Vec<McpTool>> {
139
- let result = self.request("tools/list", json!({})).await?;
140
- let raw = result["tools"].as_array().cloned().unwrap_or_default();
141
- Ok(raw.into_iter().filter_map(|t| {
142
- let original_name = t["name"].as_str()?.to_string();
143
- let description = t["description"].as_str().unwrap_or("").to_string();
144
- let input_schema = t.get("inputSchema").cloned().unwrap_or(json!({"type":"object","properties":{}}));
145
- let safe_server = self.name.replace('-', "_").replace('.', "_");
146
- Some(McpTool {
147
- name: format!("mcp__{safe_server}__{original_name}"),
148
- description,
149
- input_schema,
150
- server: self.name.clone(),
151
- original_name,
152
- })
153
- }).collect())
154
- }
155
-
156
- async fn call_tool(&self, original_name: &str, arguments: Value) -> Result<String> {
157
- let result = self.request("tools/call", json!({
158
- "name": original_name,
159
- "arguments": arguments,
160
- })).await?;
161
-
162
- // MCP returns content as an array of typed blocks
163
- let content = result["content"].as_array().cloned().unwrap_or_default();
164
- let text = content.iter()
165
- .filter_map(|c| {
166
- match c["type"].as_str() {
167
- Some("text") => c["text"].as_str().map(str::to_string),
168
- _ => None,
169
- }
170
- })
171
- .collect::<Vec<_>>()
172
- .join("\n");
173
-
174
- let is_error = result["isError"].as_bool().unwrap_or(false);
175
- Ok(json!({ "ok": !is_error, "result": text }).to_string())
176
- }
177
- }
178
-
179
- // ── McpManager — holds all connected servers ──────────────────────────────────
180
-
181
- pub struct McpManager {
182
- servers: Vec<(McpServer, Vec<McpTool>)>,
183
- }
184
-
185
- impl std::fmt::Debug for McpManager {
186
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
187
- let names: Vec<&str> = self.servers.iter().map(|(s, _)| s.name.as_str()).collect();
188
- write!(f, "McpManager {{ servers: {:?} }}", names)
189
- }
190
- }
191
-
192
- impl McpManager {
193
- /// Connect to all configured MCP servers. Errors for individual servers are
194
- /// logged and skipped so one broken server doesn't block startup.
195
- pub async fn connect(configs: &BTreeMap<String, McpServerConfig>) -> Self {
196
- let mut servers = Vec::new();
197
- for (name, cfg) in configs {
198
- match McpServer::connect(name, cfg).await {
199
- Ok(pair) => {
200
- eprintln!("\x1b[2m MCP: connected to '{name}' ({} tools)\x1b[0m",
201
- pair.1.len());
202
- servers.push(pair);
203
- }
204
- Err(e) => {
205
- eprintln!("\x1b[33m MCP: failed to connect to '{name}': {e:#}\x1b[0m");
206
- }
207
- }
208
- }
209
- Self { servers }
210
- }
211
-
212
- /// All tool definitions from all connected servers.
213
- pub fn tool_definitions(&self) -> Vec<Value> {
214
- self.servers.iter()
215
- .flat_map(|(_, tools)| tools.iter().map(|t| t.to_definition()))
216
- .collect()
217
- }
218
-
219
- /// All tool names from all connected servers.
220
- pub fn tool_names(&self) -> Vec<String> {
221
- self.servers.iter()
222
- .flat_map(|(_, tools)| tools.iter().map(|t| t.name.clone()))
223
- .collect()
224
- }
225
-
226
- /// Dispatch a call to the appropriate MCP server.
227
- pub async fn call(&self, tool_name: &str, arguments: &str) -> Option<String> {
228
- let args: Value = serde_json::from_str(arguments).unwrap_or(json!({}));
229
- for (server, tools) in &self.servers {
230
- if let Some(tool) = tools.iter().find(|t| t.name == tool_name) {
231
- return Some(match server.call_tool(&tool.original_name, args).await {
232
- Ok(r) => r,
233
- Err(e) => json!({ "ok": false, "error": e.to_string() }).to_string(),
234
- });
235
- }
236
- }
237
- None
238
- }
239
-
240
- pub fn is_empty(&self) -> bool {
241
- self.servers.is_empty()
242
- }
243
- }