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
//! MCP server registry - manages connections to multiple MCP servers.
use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use tokio::sync::{mpsc, RwLock};
use atomcode_telemetry::{Event as TelemetryEvent, McpErrorKind, McpTransport};
use super::client::{McpClient, McpToolInfo};
use super::config::{load_mcp_config, McpServerConfig};
use super::transport_http::HttpClient;
use super::transport_stdio::StdioClient;
use super::types::ServerStatus;
/// Connection status event sent to listeners when servers connect or fail.
#[derive(Debug, Clone)]
pub enum McpConnectEvent {
/// Server connected successfully.
Connected { name: String },
/// Server connection failed.
Failed { name: String, error: String },
/// Non-fatal warning (e.g. tools/list failed after connect).
Warning { name: String, message: String },
}
/// Registry of connected MCP servers.
pub struct McpRegistry {
servers: Arc<RwLock<BTreeMap<String, Arc<dyn McpClient>>>>,
server_timeouts_ms: Arc<RwLock<BTreeMap<String, u64>>>,
/// Channel for connection status events (used by TUI to display in scrollback).
connect_events: Option<mpsc::UnboundedSender<McpConnectEvent>>,
/// Signals when all initial background connections have completed (or failed).
initial_ready: Arc<tokio::sync::Notify>,
/// Telemetry handle for emitting McpConnect events.
telemetry: Option<Arc<atomcode_telemetry::Telemetry>>,
}
impl McpRegistry {
/// Create a new empty registry.
pub fn new() -> Self {
Self {
servers: Arc::new(RwLock::new(BTreeMap::new())),
server_timeouts_ms: Arc::new(RwLock::new(BTreeMap::new())),
connect_events: None,
initial_ready: Arc::new(tokio::sync::Notify::new()),
telemetry: None,
}
}
/// Set the telemetry handle for emitting McpConnect events.
pub fn with_telemetry(mut self, tel: Arc<atomcode_telemetry::Telemetry>) -> Self {
self.telemetry = Some(tel);
self
}
/// Create a registry with a channel for connection events.
pub fn with_event_channel() -> (Self, mpsc::UnboundedReceiver<McpConnectEvent>) {
let (tx, rx) = mpsc::unbounded_channel();
(
Self {
servers: Arc::new(RwLock::new(BTreeMap::new())),
server_timeouts_ms: Arc::new(RwLock::new(BTreeMap::new())),
connect_events: Some(tx),
initial_ready: Arc::new(tokio::sync::Notify::new()),
telemetry: None,
},
rx,
)
}
/// Get a clone of the event sender, if configured.
pub fn event_sender(&self) -> Option<mpsc::UnboundedSender<McpConnectEvent>> {
self.connect_events.clone()
}
/// Load MCP configuration and start connecting to servers in the background.
/// Returns immediately with an empty registry; servers are added as they connect.
/// Connection status events are sent through the internal channel if configured.
pub fn from_config_background(project_dir: &std::path::Path) -> Self {
Self::from_config_background_with_events(project_dir, None)
}
/// Load MCP configuration and start connecting to servers in the background,
/// with an external event channel for TUI status display.
pub fn from_config_background_with_events(
project_dir: &std::path::Path,
event_tx: Option<mpsc::UnboundedSender<McpConnectEvent>>,
) -> Self {
let mut registry = Self::new();
// Merge external channel with internal one
let combined_tx = event_tx.or(registry.connect_events.clone());
registry.connect_events = combined_tx.clone();
let configs = match load_mcp_config(project_dir) {
Ok(c) => c,
Err(e) => {
if let Some(tx) = &combined_tx {
let _ = tx.send(McpConnectEvent::Failed {
name: "config".to_string(),
error: format!("Failed to load config: {}", e),
});
}
return registry;
}
};
if !configs.is_empty() {
let servers = registry.servers.clone();
let server_timeouts_ms = registry.server_timeouts_ms.clone();
let initial_ready = registry.initial_ready.clone();
let telemetry = registry.telemetry.clone();
tokio::spawn(async move {
// Connect servers in parallel
let tasks: Vec<_> = configs
.into_iter()
.map(|config| {
let servers = servers.clone();
let server_timeouts_ms = server_timeouts_ms.clone();
let tx = combined_tx.clone();
let telemetry = telemetry.clone();
async move {
let name = config.name.clone();
let timeout_ms = config.timeout_ms();
let config_source = config.source;
let transport = match &config.config {
super::config::McpTransportConfig::Stdio { .. } => McpTransport::Stdio,
super::config::McpTransportConfig::Http { .. } => McpTransport::StreamableHttp,
};
let start = std::time::Instant::now();
let mut client: Box<dyn McpClient> = match &config.config {
super::config::McpTransportConfig::Stdio {
command,
args,
env,
timeout_ms,
} => Box::new(StdioClient::new(
name.clone(),
command.clone(),
args.clone(),
env.clone(),
*timeout_ms,
)),
super::config::McpTransportConfig::Http {
url,
headers,
auth,
timeout_ms,
} => Box::new(HttpClient::new(
name.clone(),
url.clone(),
headers.clone(),
auth.clone(),
*timeout_ms,
)),
};
match client.initialize().await {
Ok(_result) => {
let duration_ms = start.elapsed().as_millis() as u32;
let mut servers = servers.write().await;
servers.insert(name.clone(), Arc::from(client));
drop(servers);
let mut timeouts = server_timeouts_ms.write().await;
timeouts.insert(name.clone(), timeout_ms);
if let Some(tx) = tx {
let _ = tx.send(McpConnectEvent::Connected {
name: name.clone(),
});
}
if let Some(tel) = &telemetry {
tel.track(TelemetryEvent::McpConnect {
server_name: name.clone(),
transport,
success: true,
duration_ms: Some(duration_ms),
error_kind: None,
error_data: Some(serde_json::json!({
"server_name": name,
"transport": match transport { McpTransport::Stdio => "stdio", McpTransport::Sse => "sse", McpTransport::StreamableHttp => "streamable_http" },
"duration_ms": duration_ms,
"tool_count": 0, // will be populated when tools are listed
"config_source": config_source.as_str(),
}).to_string()),
});
}
}
Err(e) => {
let duration_ms = start.elapsed().as_millis() as u32;
let error_str = format!("{}", e);
if let Some(tx) = tx {
let _ = tx.send(McpConnectEvent::Failed {
name: name.clone(),
error: error_str.clone(),
});
}
if let Some(tel) = &telemetry {
let error_kind = classify_mcp_error(&error_str);
tel.track(TelemetryEvent::McpConnect {
server_name: name.clone(),
transport,
success: false,
duration_ms: Some(duration_ms),
error_kind: Some(error_kind),
error_data: Some(serde_json::json!({
"server_name": name,
"transport": match transport { McpTransport::Stdio => "stdio", McpTransport::Sse => "sse", McpTransport::StreamableHttp => "streamable_http" },
"duration_ms": duration_ms,
"message": atomcode_telemetry::scrub::truncate_head(&error_str, 200),
"config_source": config_source.as_str(),
}).to_string()),
});
}
}
}
}
})
.collect();
// Wait for all connections to complete (each has its own timeout)
futures::future::join_all(tasks).await;
// Signal that initial connections are done
initial_ready.notify_waiters();
});
} else {
// No servers configured — signal immediately
registry.initial_ready.notify_waiters();
}
registry
}
/// Load MCP configuration and connect to all servers (blocking).
/// Prefer `from_config_background` for non-blocking startup.
pub async fn from_config(project_dir: &std::path::Path) -> Self {
let registry = Self::new();
let configs = match load_mcp_config(project_dir) {
Ok(c) => c,
Err(e) => {
eprintln!("[mcp] Failed to load config: {}", e);
return registry;
}
};
for config in configs {
if let Err(e) = registry.add_server(config).await {
eprintln!("[mcp] Failed to connect server: {}", e);
}
}
registry
}
/// Add a server to the registry.
pub async fn add_server(&self, config: McpServerConfig) -> Result<()> {
let mut client: Box<dyn McpClient> = match &config.config {
super::config::McpTransportConfig::Stdio {
command,
args,
env,
timeout_ms,
} => Box::new(StdioClient::new(
config.name.clone(),
command.clone(),
args.clone(),
env.clone(),
*timeout_ms,
)),
super::config::McpTransportConfig::Http {
url,
headers,
auth,
timeout_ms,
} => Box::new(HttpClient::new(
config.name.clone(),
url.clone(),
headers.clone(),
auth.clone(),
*timeout_ms,
)),
};
client.initialize().await?;
let mut servers = self.servers.write().await;
servers.insert(config.name.clone(), Arc::from(client));
drop(servers);
let mut timeouts = self.server_timeouts_ms.write().await;
timeouts.insert(config.name.clone(), config.timeout_ms());
Ok(())
}
/// Timeout budget for a slow tools/list operation on a connected server.
///
/// The transport already has its own request timeout. This outer budget adds
/// a small grace period so TUI background tasks do not cancel a request right
/// before the transport timeout/error can surface.
pub async fn list_tools_timeout(&self, server_name: &str) -> Duration {
let configured_ms = {
let timeouts = self.server_timeouts_ms.read().await;
timeouts.get(server_name).copied().unwrap_or(30_000)
};
Duration::from_millis(configured_ms.saturating_add(5_000))
}
/// Get all available tools from all connected servers.
pub async fn list_all_tools(&self) -> Vec<McpToolInfo> {
// Never hold the registry lock across an .await: list_tools can be slow and
// status/reload should remain responsive.
let server_snapshot: Vec<(String, Arc<dyn McpClient>)> = {
let servers = self.servers.read().await;
servers
.iter()
.map(|(name, client)| (name.clone(), Arc::clone(client)))
.collect()
};
let mut all_tools = Vec::new();
for (server_name, client) in server_snapshot {
match client.list_tools().await {
Ok(result) => {
for tool in result.tools {
all_tools.push(McpToolInfo {
server_name: server_name.clone(),
tool_name: tool.name,
description: tool.description,
input_schema: tool.input_schema,
});
}
}
Err(e) => {
if let Some(tx) = &self.connect_events {
let _ = tx.send(McpConnectEvent::Warning {
name: server_name.clone(),
message: format!("tools/list failed: {}", e),
});
} else {
eprintln!("[mcp] Failed to list tools from {}: {}", server_name, e);
}
}
}
}
all_tools
}
/// Get tools from a single connected server.
pub async fn list_tools_for_server(&self, server_name: &str) -> Vec<McpToolInfo> {
let client = {
let servers = self.servers.read().await;
servers.get(server_name).map(Arc::clone)
};
let Some(client) = client else {
if let Some(tx) = &self.connect_events {
let _ = tx.send(McpConnectEvent::Warning {
name: server_name.to_string(),
message: "tools/list skipped: server not found".to_string(),
});
}
return Vec::new();
};
match client.list_tools().await {
Ok(result) => result
.tools
.into_iter()
.map(|tool| McpToolInfo {
server_name: server_name.to_string(),
tool_name: tool.name,
description: tool.description,
input_schema: tool.input_schema,
})
.collect(),
Err(e) => {
if let Some(tx) = &self.connect_events {
let _ = tx.send(McpConnectEvent::Warning {
name: server_name.to_string(),
message: format!("tools/list failed: {}", e),
});
} else {
eprintln!("[mcp] Failed to list tools from {}: {}", server_name, e);
}
Vec::new()
}
}
}
/// Call a tool on a specific server.
pub async fn call_tool(
&self,
server_name: &str,
tool_name: &str,
arguments: serde_json::Value,
) -> Result<String> {
let servers = self.servers.read().await;
let client = servers
.get(server_name)
.ok_or_else(|| anyhow::anyhow!("MCP server '{}' not found", server_name))?;
let result = client.call_tool(tool_name, arguments).await?;
// Extract text from content blocks
let output = result
.content
.into_iter()
.filter_map(|c| match c {
super::types::ContentBlock::Text { text } => Some(text),
_ => None,
})
.collect::<Vec<_>>()
.join("\n");
if result.is_error {
anyhow::bail!("MCP tool error: {}", output);
}
Ok(output)
}
/// Get the status of all servers.
pub async fn server_statuses(&self) -> Vec<(String, ServerStatus)> {
let servers = self.servers.read().await;
servers
.iter()
.map(|(name, client)| (name.clone(), client.status()))
.collect()
}
/// Wait for initial background connections to complete (or timeout).
/// Returns immediately if no background connections are pending.
pub async fn wait_for_initial_connections(&self, timeout: Duration) {
let _ = tokio::time::timeout(timeout, self.initial_ready.notified()).await;
}
/// Get an Arc clone for sharing across threads.
pub fn share(&self) -> Arc<Self> {
Arc::new(Self {
servers: self.servers.clone(),
server_timeouts_ms: self.server_timeouts_ms.clone(),
connect_events: self.connect_events.clone(),
initial_ready: self.initial_ready.clone(),
telemetry: self.telemetry.clone(),
})
}
}
/// Classify an MCP connection error string into a telemetry `McpErrorKind`.
fn classify_mcp_error(error: &str) -> McpErrorKind {
let e = error.to_lowercase();
if e.contains("connection refused") || e.contains("dns") || e.contains("network") {
McpErrorKind::NetworkError
} else if e.contains("401") || e.contains("403") || e.contains("unauthorized") || e.contains("oauth") {
McpErrorKind::AuthError
} else if e.contains("not found") || e.contains("no such") || e.contains("path") || e.contains("spawn") {
McpErrorKind::ExecutionFailed
} else if e.contains("timeout") || e.contains("timed out") {
McpErrorKind::Timeout
} else if e.contains("server") || e.contains("-326") || e.contains("mcp error") {
McpErrorKind::ServerError
} else {
McpErrorKind::Other
}
}
impl McpServerConfig {
fn timeout_ms(&self) -> u64 {
match &self.config {
super::config::McpTransportConfig::Stdio { timeout_ms, .. }
| super::config::McpTransportConfig::Http { timeout_ms, .. } => {
timeout_ms.unwrap_or(30_000)
}
}
}
}
impl Default for McpRegistry {
fn default() -> Self {
Self::new()
}
}