coderlib 0.1.0

A Rust library for AI-powered code assistance and agentic system
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
//! Calculator tool demonstrating enhanced tool patterns
//!
//! This tool showcases the new enhanced tool system with structured parameters,
//! JSON Schema support, and improved error handling.

use async_trait::async_trait;
use serde::Deserialize;
#[cfg(feature = "mcp-server")]
use schemars::JsonSchema;
use serde_json::Value as JsonValue;

use crate::integration::HostIntegration;
use super::router::{EnhancedTool, CallToolResult, Content, Parameters};
use super::{Permission, ToolError};

/// Parameters for basic arithmetic operations
#[derive(Debug, Deserialize)]
#[cfg_attr(feature = "mcp-server", derive(JsonSchema))]
pub struct ArithmeticParams {
    /// First number
    pub a: f64,
    /// Second number
    pub b: f64,
}

/// Parameters for advanced mathematical operations
#[derive(Debug, Deserialize)]
#[cfg_attr(feature = "mcp-server", derive(JsonSchema))]
pub struct AdvancedMathParams {
    /// The number to operate on
    pub value: f64,
    /// Optional precision for rounding (default: 2 decimal places)
    pub precision: Option<u32>,
}

/// Parameters for expression evaluation
#[derive(Debug, Deserialize)]
#[cfg_attr(feature = "mcp-server", derive(JsonSchema))]
pub struct ExpressionParams {
    /// Mathematical expression to evaluate (e.g., "2 + 3 * 4")
    pub expression: String,
}

/// Calculator tool that demonstrates enhanced tool patterns
#[derive(Clone)]
pub struct CalculatorTool {
    name: String,
}

impl CalculatorTool {
    /// Create a new calculator tool
    pub fn new() -> Self {
        Self {
            name: "calculator".to_string(),
        }
    }

    /// Add two numbers
    async fn add(&self, params: ArithmeticParams) -> Result<CallToolResult, ToolError> {
        let result = params.a + params.b;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "{} + {} = {}",
            params.a, params.b, result
        ))]))
    }

    /// Subtract two numbers
    async fn subtract(&self, params: ArithmeticParams) -> Result<CallToolResult, ToolError> {
        let result = params.a - params.b;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "{} - {} = {}",
            params.a, params.b, result
        ))]))
    }

    /// Multiply two numbers
    async fn multiply(&self, params: ArithmeticParams) -> Result<CallToolResult, ToolError> {
        let result = params.a * params.b;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "{} × {} = {}",
            params.a, params.b, result
        ))]))
    }

    /// Divide two numbers
    async fn divide(&self, params: ArithmeticParams) -> Result<CallToolResult, ToolError> {
        if params.b == 0.0 {
            return Ok(CallToolResult::error("Division by zero is not allowed".to_string()));
        }
        let result = params.a / params.b;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "{} ÷ {} = {}",
            params.a, params.b, result
        ))]))
    }

    /// Calculate square root
    async fn sqrt(&self, params: AdvancedMathParams) -> Result<CallToolResult, ToolError> {
        if params.value < 0.0 {
            return Ok(CallToolResult::error("Cannot calculate square root of negative number".to_string()));
        }
        let result = params.value.sqrt();
        let precision = params.precision.unwrap_or(2);
        let formatted_result = format!("{:.precision$}", result, precision = precision as usize);
        Ok(CallToolResult::success(vec![Content::text(format!(
            "√{} = {}",
            params.value, formatted_result
        ))]))
    }

    /// Calculate power
    async fn power(&self, params: ArithmeticParams) -> Result<CallToolResult, ToolError> {
        let result = params.a.powf(params.b);
        Ok(CallToolResult::success(vec![Content::text(format!(
            "{}^{} = {}",
            params.a, params.b, result
        ))]))
    }

    /// Evaluate a mathematical expression
    async fn evaluate(&self, params: ExpressionParams) -> Result<CallToolResult, ToolError> {
        // Simple expression evaluator (for demonstration)
        // In a real implementation, you'd use a proper expression parser
        let expression = params.expression.trim();
        
        // Handle simple operations for demonstration
        if let Some(result) = self.evaluate_simple_expression(expression) {
            Ok(CallToolResult::success(vec![Content::text(format!(
                "{} = {}",
                expression, result
            ))]))
        } else {
            Ok(CallToolResult::error(format!(
                "Unable to evaluate expression: {}. Supported operations: +, -, *, /, sqrt(), ^",
                expression
            )))
        }
    }

    /// Simple expression evaluator for basic operations
    fn evaluate_simple_expression(&self, expr: &str) -> Option<f64> {
        // Very basic implementation for demonstration
        // This would be replaced with a proper expression parser in production
        
        if expr.contains('+') {
            let parts: Vec<&str> = expr.split('+').collect();
            if parts.len() == 2 {
                let a = parts[0].trim().parse::<f64>().ok()?;
                let b = parts[1].trim().parse::<f64>().ok()?;
                return Some(a + b);
            }
        }
        
        if expr.contains('-') && !expr.starts_with('-') {
            let parts: Vec<&str> = expr.split('-').collect();
            if parts.len() == 2 {
                let a = parts[0].trim().parse::<f64>().ok()?;
                let b = parts[1].trim().parse::<f64>().ok()?;
                return Some(a - b);
            }
        }
        
        if expr.contains('*') {
            let parts: Vec<&str> = expr.split('*').collect();
            if parts.len() == 2 {
                let a = parts[0].trim().parse::<f64>().ok()?;
                let b = parts[1].trim().parse::<f64>().ok()?;
                return Some(a * b);
            }
        }
        
        if expr.contains('/') {
            let parts: Vec<&str> = expr.split('/').collect();
            if parts.len() == 2 {
                let a = parts[0].trim().parse::<f64>().ok()?;
                let b = parts[1].trim().parse::<f64>().ok()?;
                if b != 0.0 {
                    return Some(a / b);
                }
            }
        }
        
        // Try to parse as a single number
        expr.parse::<f64>().ok()
    }
}

#[async_trait]
impl EnhancedTool for CalculatorTool {
    async fn execute_enhanced(
        &self,
        parameters: JsonValue,
        _host: &dyn HostIntegration,
    ) -> Result<CallToolResult, ToolError> {
        // Extract operation from parameters
        let operation = parameters.get("operation")
            .and_then(|v| v.as_str())
            .ok_or_else(|| ToolError::InvalidParameters("Missing 'operation' parameter".to_string()))?;

        match operation {
            "add" => {
                let params: Parameters<ArithmeticParams> = Parameters::from_json(parameters)?;
                self.add(params.0).await
            }
            "subtract" => {
                let params: Parameters<ArithmeticParams> = Parameters::from_json(parameters)?;
                self.subtract(params.0).await
            }
            "multiply" => {
                let params: Parameters<ArithmeticParams> = Parameters::from_json(parameters)?;
                self.multiply(params.0).await
            }
            "divide" => {
                let params: Parameters<ArithmeticParams> = Parameters::from_json(parameters)?;
                self.divide(params.0).await
            }
            "sqrt" => {
                let params: Parameters<AdvancedMathParams> = Parameters::from_json(parameters)?;
                self.sqrt(params.0).await
            }
            "power" => {
                let params: Parameters<ArithmeticParams> = Parameters::from_json(parameters)?;
                self.power(params.0).await
            }
            "evaluate" => {
                let params: Parameters<ExpressionParams> = Parameters::from_json(parameters)?;
                self.evaluate(params.0).await
            }
            _ => Ok(CallToolResult::error(format!(
                "Unknown operation: {}. Supported operations: add, subtract, multiply, divide, sqrt, power, evaluate",
                operation
            )))
        }
    }

    fn name(&self) -> &str {
        &self.name
    }

    fn description(&self) -> &str {
        "Advanced calculator tool supporting arithmetic operations, square root, power, and expression evaluation"
    }

    fn parameter_schema(&self) -> JsonValue {
        serde_json::json!({
            "type": "object",
            "properties": {
                "operation": {
                    "type": "string",
                    "enum": ["add", "subtract", "multiply", "divide", "sqrt", "power", "evaluate"],
                    "description": "The mathematical operation to perform"
                },
                "a": {
                    "type": "number",
                    "description": "First number (for arithmetic operations)"
                },
                "b": {
                    "type": "number", 
                    "description": "Second number (for arithmetic operations)"
                },
                "value": {
                    "type": "number",
                    "description": "Input value (for single-value operations like sqrt)"
                },
                "precision": {
                    "type": "integer",
                    "description": "Number of decimal places for rounding (optional, default: 2)"
                },
                "expression": {
                    "type": "string",
                    "description": "Mathematical expression to evaluate (for evaluate operation)"
                }
            },
            "required": ["operation"],
            "oneOf": [
                {
                    "properties": {
                        "operation": {"const": "add"},
                        "a": {"type": "number"},
                        "b": {"type": "number"}
                    },
                    "required": ["operation", "a", "b"]
                },
                {
                    "properties": {
                        "operation": {"const": "subtract"},
                        "a": {"type": "number"},
                        "b": {"type": "number"}
                    },
                    "required": ["operation", "a", "b"]
                },
                {
                    "properties": {
                        "operation": {"const": "multiply"},
                        "a": {"type": "number"},
                        "b": {"type": "number"}
                    },
                    "required": ["operation", "a", "b"]
                },
                {
                    "properties": {
                        "operation": {"const": "divide"},
                        "a": {"type": "number"},
                        "b": {"type": "number"}
                    },
                    "required": ["operation", "a", "b"]
                },
                {
                    "properties": {
                        "operation": {"const": "sqrt"},
                        "value": {"type": "number"},
                        "precision": {"type": "integer"}
                    },
                    "required": ["operation", "value"]
                },
                {
                    "properties": {
                        "operation": {"const": "power"},
                        "a": {"type": "number"},
                        "b": {"type": "number"}
                    },
                    "required": ["operation", "a", "b"]
                },
                {
                    "properties": {
                        "operation": {"const": "evaluate"},
                        "expression": {"type": "string"}
                    },
                    "required": ["operation", "expression"]
                }
            ]
        })
    }

    fn requires_permission(&self) -> Permission {
        Permission::None
    }

    fn clone_enhanced(&self) -> Box<dyn EnhancedTool> {
        Box::new(self.clone())
    }
}

impl Default for CalculatorTool {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[tokio::test]
    async fn test_calculator_add() {
        let calc = CalculatorTool::new();
        let params = json!({
            "operation": "add",
            "a": 5.0,
            "b": 3.0
        });

        // We can't test execute_enhanced directly without a HostIntegration mock
        // But we can test the individual operations
        let arithmetic_params = ArithmeticParams { a: 5.0, b: 3.0 };
        let result = calc.add(arithmetic_params).await.unwrap();
        assert!(!result.is_error);
        assert_eq!(result.content.len(), 1);
    }

    #[tokio::test]
    async fn test_calculator_divide_by_zero() {
        let calc = CalculatorTool::new();
        let arithmetic_params = ArithmeticParams { a: 5.0, b: 0.0 };
        let result = calc.divide(arithmetic_params).await.unwrap();
        assert!(result.is_error);
    }

    #[tokio::test]
    async fn test_calculator_sqrt_negative() {
        let calc = CalculatorTool::new();
        let math_params = AdvancedMathParams { value: -4.0, precision: None };
        let result = calc.sqrt(math_params).await.unwrap();
        assert!(result.is_error);
    }

    #[test]
    fn test_simple_expression_evaluation() {
        let calc = CalculatorTool::new();
        assert_eq!(calc.evaluate_simple_expression("2 + 3"), Some(5.0));
        assert_eq!(calc.evaluate_simple_expression("10 - 4"), Some(6.0));
        assert_eq!(calc.evaluate_simple_expression("3 * 4"), Some(12.0));
        assert_eq!(calc.evaluate_simple_expression("8 / 2"), Some(4.0));
        assert_eq!(calc.evaluate_simple_expression("42"), Some(42.0));
    }

    #[test]
    fn test_tool_metadata() {
        let calc = CalculatorTool::new();
        assert_eq!(calc.name(), "calculator");
        assert!(!calc.description().is_empty());
        assert_eq!(calc.requires_permission(), Permission::None);
        
        let schema = calc.parameter_schema();
        assert!(schema.is_object());
        assert!(schema.get("properties").is_some());
    }
}