Skip to main content

tiny_agent_rs/schemas/
validator.rs

1use crate::{AgentError, Result};
2use serde::de::DeserializeOwned;
3use serde_json::Value;
4use std::collections::HashMap;
5
6/// Validation strategies for tool parameters
7#[derive(Debug, Clone)]
8pub enum Validator {
9    /// Fast validation using serde
10    SerdeFirst,
11    /// Strict validation using JSON Schema
12    Strict(StrictValidator),
13}
14
15impl Validator {
16    /// Validate and deserialize parameters into type T
17    pub fn validate<T: DeserializeOwned>(&self, params: Value) -> Result<T> {
18        match self {
19            Validator::SerdeFirst => serde_first_validate(params),
20            Validator::Strict(validator) => validator.validate(params),
21        }
22    }
23}
24
25/// Fast serde-first validator
26fn serde_first_validate<T: DeserializeOwned>(params: Value) -> Result<T> {
27    serde_path_to_error::deserialize(params).map_err(|e| {
28        AgentError::Validation(format!(
29            "Parameter validation failed at {}: {}",
30            e.path(),
31            e
32        ))
33    })
34}
35
36/// Strict JSON Schema validator
37#[derive(Debug, Clone)]
38pub struct StrictValidator {
39    schemas: HashMap<String, Value>,
40}
41
42impl StrictValidator {
43    /// Create a new strict validator
44    pub fn new() -> Self {
45        Self {
46            schemas: HashMap::new(),
47        }
48    }
49
50    /// Register a schema for a tool
51    pub fn register_schema(&mut self, tool_name: &str, schema: Value) {
52        self.schemas.insert(tool_name.to_string(), schema);
53    }
54
55    /// Validate parameters against registered schema
56    pub fn validate<T: DeserializeOwned>(&self, params: Value) -> Result<T> {
57        // For now, fall back to serde validation
58        // In a production implementation, you would use jsonschema crate
59        serde_first_validate(params)
60    }
61}
62
63impl Default for StrictValidator {
64    fn default() -> Self {
65        Self::new()
66    }
67}