brainwires-mcp-client 0.11.0

MCP client, transport, and protocol types for the Brainwires Agent 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
use anyhow::{Context, Result};
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use tokio::sync::{RwLock, mpsc};

use crate::config::McpServerConfig;
use crate::transport::{StdioTransport, Transport};
use crate::types::*;

/// MCP Client - manages connections to MCP servers
pub struct McpClient {
    connections: Arc<RwLock<HashMap<String, McpConnection>>>,
    request_id: Arc<AtomicU64>,
    client_name: String,
    client_version: String,
}

/// Active connection to an MCP server
struct McpConnection {
    #[allow(dead_code)]
    server_name: String,
    transport: Transport,
    server_info: ServerInfo,
    capabilities: ServerCapabilities,
    /// Channel for forwarding notifications received during requests
    _notification_tx: Option<mpsc::UnboundedSender<JsonRpcNotification>>,
}

impl McpClient {
    /// Create a new MCP client with the given name and version.
    pub fn new(client_name: impl Into<String>, client_version: impl Into<String>) -> Self {
        Self {
            connections: Arc::new(RwLock::new(HashMap::new())),
            request_id: Arc::new(AtomicU64::new(1)),
            client_name: client_name.into(),
            client_version: client_version.into(),
        }
    }

    /// Connect to an MCP server
    pub async fn connect(&self, config: &McpServerConfig) -> Result<()> {
        // Spawn server process
        let transport = StdioTransport::new(&config.command, &config.args).await?;
        let mut transport = Transport::Stdio(transport);

        // Send initialize request
        let init_result = self.initialize(&mut transport).await?;

        // Create connection
        let connection = McpConnection {
            server_name: config.name.clone(),
            transport,
            server_info: init_result.server_info,
            capabilities: init_result.capabilities,
            _notification_tx: None,
        };

        // Store connection
        self.connections
            .write()
            .await
            .insert(config.name.clone(), connection);

        Ok(())
    }

    /// Disconnect from an MCP server
    pub async fn disconnect(&self, server_name: &str) -> Result<()> {
        let mut connections = self.connections.write().await;
        if let Some(mut connection) = connections.remove(server_name) {
            connection.transport.close().await?;
        }
        Ok(())
    }

    /// Check if connected to a server
    pub async fn is_connected(&self, server_name: &str) -> bool {
        self.connections.read().await.contains_key(server_name)
    }

    /// Get list of connected servers
    pub async fn list_connected(&self) -> Vec<String> {
        self.connections.read().await.keys().cloned().collect()
    }

    /// Initialize handshake with server
    async fn initialize(&self, transport: &mut Transport) -> Result<InitializeResult> {
        let request = JsonRpcRequest::new(
            self.next_request_id(),
            "initialize".to_string(),
            Some(InitializeParams {
                protocol_version: "2024-11-05".to_string(),
                capabilities: ClientCapabilities::default(),
                client_info: ClientInfo {
                    name: self.client_name.clone(),
                    version: self.client_version.clone(),
                },
            }),
        )
        .context("Failed to serialize initialize params")?;

        transport.send_request(&request).await?;
        let response = transport.receive_response().await?;

        if let Some(error) = response.error {
            anyhow::bail!(
                "Initialize failed: {} (code: {})",
                error.message,
                error.code
            );
        }

        let result: InitializeResult = serde_json::from_value(
            response
                .result
                .context("Missing result in initialize response")?,
        )
        .context("Failed to parse initialize result")?;

        // Send initialized notification
        transport
            .send_request(&JsonRpcRequest {
                jsonrpc: "2.0".to_string(),
                id: serde_json::Value::Null,
                method: "notifications/initialized".to_string(),
                params: None,
            })
            .await?;

        Ok(result)
    }

    /// List available tools from a server
    pub async fn list_tools(&self, server_name: &str) -> Result<Vec<McpTool>> {
        let mut connections = self.connections.write().await;
        let connection = connections
            .get_mut(server_name)
            .context(format!("Not connected to server: {}", server_name))?;

        let request =
            JsonRpcRequest::new(self.next_request_id(), "tools/list".to_string(), None::<()>)
                .context("Failed to serialize tools/list params")?;

        connection.transport.send_request(&request).await?;
        let response = connection.transport.receive_response().await?;

        if let Some(error) = response.error {
            anyhow::bail!(
                "tools/list failed: {} (code: {})",
                error.message,
                error.code
            );
        }

        let result: ListToolsResult =
            serde_json::from_value(response.result.context("Missing result")?)?;

        Ok(result.tools)
    }

    /// Call a tool on a server
    pub async fn call_tool(
        &self,
        server_name: &str,
        tool_name: &str,
        arguments: Option<serde_json::Value>,
    ) -> Result<CallToolResult> {
        self.call_tool_with_notifications(server_name, tool_name, arguments, None)
            .await
    }

    /// Call a tool on a server with notification forwarding
    /// If notification_tx is provided, any notifications received while waiting for the response
    /// will be forwarded through that channel
    pub async fn call_tool_with_notifications(
        &self,
        server_name: &str,
        tool_name: &str,
        arguments: Option<serde_json::Value>,
        notification_tx: Option<mpsc::UnboundedSender<JsonRpcNotification>>,
    ) -> Result<CallToolResult> {
        let mut connections = self.connections.write().await;
        let connection = connections
            .get_mut(server_name)
            .context(format!("Not connected to server: {}", server_name))?;

        // Convert Value to JsonObject (Map<String, Value>) as required by rmcp
        let arguments_obj = arguments.and_then(|v| {
            if let serde_json::Value::Object(map) = v {
                Some(map)
            } else {
                None
            }
        });

        let request_id = self.next_request_id();
        let request = JsonRpcRequest::new(
            request_id,
            "tools/call".to_string(),
            Some({
                let mut params = CallToolParams::new(tool_name.to_string());
                params.arguments = arguments_obj;
                params
            }),
        )
        .context("Failed to serialize tools/call params")?;

        connection.transport.send_request(&request).await?;

        // Wait for response, forwarding any notifications that arrive
        loop {
            let message = connection.transport.receive_message().await?;

            match message {
                JsonRpcMessage::Response(response) => {
                    // Check if this is the response we're waiting for
                    // (in a simple single-request-at-a-time model, it should be)
                    if let Some(error) = response.error {
                        anyhow::bail!(
                            "tools/call failed: {} (code: {})",
                            error.message,
                            error.code
                        );
                    }

                    let result: CallToolResult =
                        serde_json::from_value(response.result.context("Missing result")?)?;

                    return Ok(result);
                }
                JsonRpcMessage::Notification(notification) => {
                    // Forward notification to caller if they provided a channel
                    if let Some(ref tx) = notification_tx {
                        let _ = tx.send(notification);
                    }
                    // Continue waiting for the response
                }
            }
        }
    }

    /// List available resources from a server
    pub async fn list_resources(&self, server_name: &str) -> Result<Vec<McpResource>> {
        let mut connections = self.connections.write().await;
        let connection = connections
            .get_mut(server_name)
            .context(format!("Not connected to server: {}", server_name))?;

        let request = JsonRpcRequest::new(
            self.next_request_id(),
            "resources/list".to_string(),
            None::<()>,
        )
        .context("Failed to serialize resources/list params")?;

        connection.transport.send_request(&request).await?;
        let response = connection.transport.receive_response().await?;

        if let Some(error) = response.error {
            anyhow::bail!(
                "resources/list failed: {} (code: {})",
                error.message,
                error.code
            );
        }

        let result: ListResourcesResult =
            serde_json::from_value(response.result.context("Missing result")?)?;

        Ok(result.resources)
    }

    /// Read a resource from a server
    pub async fn read_resource(&self, server_name: &str, uri: &str) -> Result<ReadResourceResult> {
        let mut connections = self.connections.write().await;
        let connection = connections
            .get_mut(server_name)
            .context(format!("Not connected to server: {}", server_name))?;

        let request = JsonRpcRequest::new(
            self.next_request_id(),
            "resources/read".to_string(),
            Some(ReadResourceParams {
                uri: uri.to_string(),
            }),
        )
        .context("Failed to serialize resources/read params")?;

        connection.transport.send_request(&request).await?;
        let response = connection.transport.receive_response().await?;

        if let Some(error) = response.error {
            anyhow::bail!(
                "resources/read failed: {} (code: {})",
                error.message,
                error.code
            );
        }

        let result: ReadResourceResult =
            serde_json::from_value(response.result.context("Missing result")?)?;

        Ok(result)
    }

    /// List available prompts from a server
    pub async fn list_prompts(&self, server_name: &str) -> Result<Vec<McpPrompt>> {
        let mut connections = self.connections.write().await;
        let connection = connections
            .get_mut(server_name)
            .context(format!("Not connected to server: {}", server_name))?;

        let request = JsonRpcRequest::new(
            self.next_request_id(),
            "prompts/list".to_string(),
            None::<()>,
        )
        .context("Failed to serialize prompts/list params")?;

        connection.transport.send_request(&request).await?;
        let response = connection.transport.receive_response().await?;

        if let Some(error) = response.error {
            anyhow::bail!(
                "prompts/list failed: {} (code: {})",
                error.message,
                error.code
            );
        }

        let result: ListPromptsResult =
            serde_json::from_value(response.result.context("Missing result")?)?;

        Ok(result.prompts)
    }

    /// Get a prompt from a server
    pub async fn get_prompt(
        &self,
        server_name: &str,
        prompt_name: &str,
        arguments: Option<serde_json::Value>,
    ) -> Result<GetPromptResult> {
        let mut connections = self.connections.write().await;
        let connection = connections
            .get_mut(server_name)
            .context(format!("Not connected to server: {}", server_name))?;

        let request = JsonRpcRequest::new(
            self.next_request_id(),
            "prompts/get".to_string(),
            Some(GetPromptParams {
                name: prompt_name.to_string(),
                arguments,
            }),
        )
        .context("Failed to serialize prompts/get params")?;

        connection.transport.send_request(&request).await?;
        let response = connection.transport.receive_response().await?;

        if let Some(error) = response.error {
            anyhow::bail!(
                "prompts/get failed: {} (code: {})",
                error.message,
                error.code
            );
        }

        let result: GetPromptResult =
            serde_json::from_value(response.result.context("Missing result")?)?;

        Ok(result)
    }

    /// Get server info for a connection
    pub async fn get_server_info(&self, server_name: &str) -> Result<ServerInfo> {
        let connections = self.connections.read().await;
        let connection = connections
            .get(server_name)
            .context(format!("Not connected to server: {}", server_name))?;

        Ok(connection.server_info.clone())
    }

    /// Get server capabilities for a connection
    pub async fn get_capabilities(&self, server_name: &str) -> Result<ServerCapabilities> {
        let connections = self.connections.read().await;
        let connection = connections
            .get(server_name)
            .context(format!("Not connected to server: {}", server_name))?;

        Ok(connection.capabilities.clone())
    }

    /// Get next request ID
    fn next_request_id(&self) -> u64 {
        self.request_id.fetch_add(1, Ordering::SeqCst)
    }

    /// Send a cancellation request to the MCP server
    /// This follows the JSON-RPC 2.0 cancellation protocol using `$/cancelRequest`
    pub async fn cancel_request(&self, server_name: &str, request_id: u64) -> Result<()> {
        let mut connections = self.connections.write().await;
        let connection = connections
            .get_mut(server_name)
            .context(format!("Not connected to server: {}", server_name))?;

        // Send cancellation notification (no id since it's a notification)
        let cancel_notification = JsonRpcNotification::new(
            "$/cancelRequest",
            Some(serde_json::json!({ "id": request_id })),
        )
        .context("Failed to serialize cancel request params")?;

        // Convert to JsonRpcRequest for sending (with null id for notification)
        let request = JsonRpcRequest {
            jsonrpc: "2.0".to_string(),
            id: serde_json::Value::Null,
            method: cancel_notification.method,
            params: cancel_notification.params,
        };

        connection.transport.send_request(&request).await?;

        Ok(())
    }
}

impl Default for McpClient {
    fn default() -> Self {
        Self::new("brainwires", env!("CARGO_PKG_VERSION"))
    }
}

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

    #[test]
    fn test_client_creation() {
        let client = McpClient::new("test", "0.1.0");
        assert_eq!(client.request_id.load(Ordering::SeqCst), 1);
        assert_eq!(client.client_name, "test");
        assert_eq!(client.client_version, "0.1.0");
    }

    #[test]
    fn test_request_id_increment() {
        let client = McpClient::new("test", "0.1.0");
        assert_eq!(client.next_request_id(), 1);
        assert_eq!(client.next_request_id(), 2);
        assert_eq!(client.next_request_id(), 3);
    }
}