paladin-ai 0.4.2

Enterprise AI orchestration framework with multi-agent coordination patterns
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
//! Model Context Protocol (MCP) implementation
//!
//! This module implements the JSON-RPC 2.0 based MCP protocol for communicating
//! with tool servers. It provides message types, a transport abstraction, and
//! a client for tool discovery and invocation.
//!
//! # Protocol Overview
//!
//! MCP uses JSON-RPC 2.0 for message exchange:
//! - **Request**: Client sends method call (e.g., `tools/list`, `tools/call`)
//! - **Response**: Server returns result or error
//! - **Notification**: One-way messages (not used in current implementation)
//!
//! # Example
//!
//! ```no_run
//! use paladin::infrastructure::adapters::arsenal::mcp_protocol::{MCPClient, MCPRequest};
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # let transport: Box<dyn paladin::infrastructure::adapters::arsenal::mcp_protocol::MCPTransport> = todo!();
//! let client = MCPClient::new(transport);
//! let tools = client.discover_tools().await?;
//! println!("Available tools: {:?}", tools);
//! # Ok(())
//! # }
//! ```

use crate::core::platform::container::arsenal::{Armament, ArsenalError};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
use uuid::Uuid;

/// JSON-RPC 2.0 message types
#[doc(hidden)]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MCPMessage {
    /// Request message from client to server
    Request(MCPRequest),
    /// Response message from server to client
    Response(MCPResponse),
    /// Notification message (one-way, no response expected)
    Notification(MCPNotification),
}

/// JSON-RPC 2.0 request message
///
/// Represents a client request to invoke a method on the server.
#[doc(hidden)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPRequest {
    /// JSON-RPC protocol version (always "2.0")
    pub jsonrpc: String,
    /// Unique identifier for this request
    pub id: Value,
    /// Method name to invoke (e.g., "tools/list", "tools/call")
    pub method: String,
    /// Optional parameters for the method
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<Value>,
}

impl MCPRequest {
    /// Creates a new MCP request with a UUID identifier
    ///
    /// # Arguments
    ///
    /// * `method` - The method name to invoke
    /// * `params` - Optional parameters for the method
    ///
    /// # Example
    ///
    /// ```
    /// use paladin::infrastructure::adapters::arsenal::mcp_protocol::MCPRequest;
    /// use serde_json::json;
    ///
    /// let request = MCPRequest::new("tools/list", Some(json!({})));
    /// assert_eq!(request.method, "tools/list");
    /// ```
    pub fn new(method: impl Into<String>, params: Option<Value>) -> Self {
        Self {
            jsonrpc: "2.0".to_string(),
            id: Value::String(Uuid::new_v4().to_string()),
            method: method.into(),
            params,
        }
    }
}

/// JSON-RPC 2.0 response message
///
/// Represents a server response to a client request.
#[doc(hidden)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPResponse {
    /// JSON-RPC protocol version (always "2.0")
    pub jsonrpc: String,
    /// Request ID this response corresponds to
    pub id: Value,
    /// Success result (mutually exclusive with error)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<Value>,
    /// Error result (mutually exclusive with result)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<MCPError>,
}

/// JSON-RPC 2.0 error object
///
/// Represents an error that occurred during request processing.
#[doc(hidden)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPError {
    /// Error code (standard JSON-RPC codes or application-specific)
    pub code: i64,
    /// Human-readable error message
    pub message: String,
    /// Optional additional error data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,
}

impl MCPError {
    /// Standard JSON-RPC error codes
    pub const PARSE_ERROR: i64 = -32700;
    pub const INVALID_REQUEST: i64 = -32600;
    pub const METHOD_NOT_FOUND: i64 = -32601;
    pub const INVALID_PARAMS: i64 = -32602;
    pub const INTERNAL_ERROR: i64 = -32603;

    /// Creates a new MCP error
    pub fn new(code: i64, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            data: None,
        }
    }

    /// Creates a new MCP error with additional data
    pub fn with_data(code: i64, message: impl Into<String>, data: Value) -> Self {
        Self {
            code,
            message: message.into(),
            data: Some(data),
        }
    }
}

/// JSON-RPC 2.0 notification message
///
/// One-way message that doesn't expect a response.
#[doc(hidden)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPNotification {
    /// JSON-RPC protocol version (always "2.0")
    pub jsonrpc: String,
    /// Method name
    pub method: String,
    /// Optional parameters
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<Value>,
}

/// MCP server capabilities
///
/// Describes what features and tools the server supports.
#[doc(hidden)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPCapabilities {
    /// Server name and version
    #[serde(skip_serializing_if = "Option::is_none")]
    pub server_info: Option<ServerInfo>,
    /// List of supported tools
    #[serde(default)]
    pub tools: Vec<ToolInfo>,
    /// Additional capability flags
    #[serde(flatten)]
    pub extensions: HashMap<String, Value>,
}

/// Server information
#[doc(hidden)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerInfo {
    /// Server name
    pub name: String,
    /// Server version
    pub version: String,
}

/// Tool information from MCP server
#[doc(hidden)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolInfo {
    /// Tool name
    pub name: String,
    /// Tool description
    pub description: String,
    /// Input schema (JSON Schema)
    #[serde(rename = "inputSchema")]
    pub input_schema: Value,
}

/// Transport abstraction for MCP communication
///
/// Implementations handle the actual communication mechanism (STDIO, SSE, etc.)
#[async_trait]
pub trait MCPTransport: Send + Sync {
    /// Sends a message to the server
    ///
    /// # Errors
    ///
    /// Returns `ArsenalError::TransportError` if sending fails
    async fn send(&mut self, message: &MCPMessage) -> Result<(), ArsenalError>;

    /// Receives a message from the server
    ///
    /// # Errors
    ///
    /// Returns `ArsenalError::TransportError` if receiving fails
    async fn receive(&mut self) -> Result<MCPMessage, ArsenalError>;
}

/// MCP client for interacting with tool servers
///
/// Provides high-level methods for tool discovery and invocation.
#[doc(hidden)]
pub struct MCPClient {
    /// Transport implementation (STDIO, SSE, etc.)
    transport: Arc<tokio::sync::Mutex<Box<dyn MCPTransport>>>,
    /// Server capabilities (populated after connection)
    #[allow(dead_code)]
    capabilities: Option<MCPCapabilities>,
}

impl MCPClient {
    /// Creates a new MCP client with the given transport
    ///
    /// # Arguments
    ///
    /// * `transport` - Transport implementation for communication
    ///
    /// # Example
    ///
    /// ```no_run
    /// use paladin::infrastructure::adapters::arsenal::mcp_protocol::MCPClient;
    /// use std::sync::Arc;
    /// # async fn example() {
    /// # let transport: Box<dyn paladin::infrastructure::adapters::arsenal::mcp_protocol::MCPTransport> = todo!();
    /// let client = MCPClient::new(transport);
    /// # }
    /// ```
    pub fn new(transport: Box<dyn MCPTransport>) -> Self {
        Self {
            transport: Arc::new(tokio::sync::Mutex::new(transport)),
            capabilities: None,
        }
    }

    /// Discovers available tools from the server
    ///
    /// Sends a `tools/list` request and parses the response.
    ///
    /// # Errors
    ///
    /// Returns `ArsenalError` if:
    /// - Communication fails
    /// - Server returns an error
    /// - Response format is invalid
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use paladin::infrastructure::adapters::arsenal::mcp_protocol::MCPClient;
    /// # async fn example(client: MCPClient) -> Result<(), Box<dyn std::error::Error>> {
    /// let tools = client.discover_tools().await?;
    /// for tool in tools {
    ///     println!("Found tool: {}", tool.name);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn discover_tools(&self) -> Result<Vec<Armament>, ArsenalError> {
        let request = MCPRequest::new("tools/list", Some(serde_json::json!({})));
        let response = self.send_request(request).await?;

        // Parse tools from response
        let tools_array = response
            .get("tools")
            .and_then(|v| v.as_array())
            .ok_or_else(|| {
                ArsenalError::ProtocolError("Invalid tools/list response format".to_string())
            })?;

        let mut armaments = Vec::new();
        for tool_value in tools_array {
            let tool_info: ToolInfo = serde_json::from_value(tool_value.clone()).map_err(|e| {
                ArsenalError::ProtocolError(format!("Failed to parse tool info: {}", e))
            })?;

            // Extract required parameters from schema
            let required_params = tool_info
                .input_schema
                .get("required")
                .and_then(|r| r.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(String::from))
                        .collect()
                })
                .unwrap_or_default();

            armaments.push(Armament {
                name: tool_info.name,
                description: tool_info.description,
                parameters: tool_info.input_schema,
                required_params,
            });
        }

        Ok(armaments)
    }

    /// Invokes a tool on the server
    ///
    /// Sends a `tools/call` request with the specified tool name and arguments.
    ///
    /// # Arguments
    ///
    /// * `tool_name` - Name of the tool to invoke
    /// * `arguments` - Tool arguments as a HashMap
    ///
    /// # Errors
    ///
    /// Returns `ArsenalError` if:
    /// - Communication fails
    /// - Server returns an error
    /// - Tool execution fails
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use paladin::infrastructure::adapters::arsenal::mcp_protocol::MCPClient;
    /// # use std::collections::HashMap;
    /// # use serde_json::Value;
    /// # async fn example(client: MCPClient) -> Result<(), Box<dyn std::error::Error>> {
    /// let mut args = HashMap::new();
    /// args.insert("query".to_string(), Value::String("Rust".to_string()));
    /// let result = client.invoke_tool("web_search", args).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn invoke_tool(
        &self,
        tool_name: &str,
        arguments: HashMap<String, Value>,
    ) -> Result<Value, ArsenalError> {
        let params = serde_json::json!({
            "name": tool_name,
            "arguments": arguments,
        });

        let request = MCPRequest::new("tools/call", Some(params));
        let response = self.send_request(request).await?;

        // Extract result from response
        response
            .get("content")
            .cloned()
            .ok_or_else(|| ArsenalError::ProtocolError("Missing content in response".to_string()))
    }

    /// Sends a request and waits for response
    ///
    /// Internal helper method for request/response pattern.
    async fn send_request(&self, request: MCPRequest) -> Result<Value, ArsenalError> {
        let mut transport = self.transport.lock().await;

        // Send request
        transport.send(&MCPMessage::Request(request)).await?;

        // Receive response
        let response_msg = transport.receive().await?;

        match response_msg {
            MCPMessage::Response(response) => {
                if let Some(error) = response.error {
                    return Err(ArsenalError::ProtocolError(format!(
                        "MCP error {}: {}",
                        error.code, error.message
                    )));
                }

                response.result.ok_or_else(|| {
                    ArsenalError::ProtocolError(
                        "Response missing both result and error".to_string(),
                    )
                })
            }
            _ => Err(ArsenalError::ProtocolError(
                "Expected response, got different message type".to_string(),
            )),
        }
    }
}

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

    #[test]
    fn test_mcp_request_creation() {
        let request = MCPRequest::new("test/method", Some(serde_json::json!({"key": "value"})));
        assert_eq!(request.jsonrpc, "2.0");
        assert_eq!(request.method, "test/method");
        assert!(request.params.is_some());
    }

    #[test]
    fn test_mcp_error_codes() {
        assert_eq!(MCPError::PARSE_ERROR, -32700);
        assert_eq!(MCPError::INVALID_REQUEST, -32600);
        assert_eq!(MCPError::METHOD_NOT_FOUND, -32601);
    }
}