agnix-core 0.22.1

Core validation engine for agent configurations
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
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
//! MCP (Model Context Protocol) schema definitions

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Known MCP tool annotation hint keys from spec.
pub const VALID_MCP_ANNOTATION_HINTS: &[&str] = &[
    "readOnlyHint",
    "destructiveHint",
    "idempotentHint",
    "openWorldHint",
    "title",
];

/// Known MCP capability keys from spec.
pub const VALID_MCP_CAPABILITY_KEYS: &[&str] = &[
    "tools",
    "resources",
    "prompts",
    "logging",
    "roots",
    "sampling",
    "elicitation",
    "completions",
    "experimental",
];

/// MCP tool definition schema
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpToolSchema {
    /// Required: tool name
    pub name: Option<String>,

    /// Optional: human-readable display name
    pub title: Option<String>,

    /// Required: tool description
    pub description: Option<String>,

    /// Required: JSON Schema for input parameters
    #[serde(rename = "inputSchema")]
    pub input_schema: Option<serde_json::Value>,

    /// Optional: JSON Schema for structured outputs
    #[serde(rename = "outputSchema")]
    pub output_schema: Option<serde_json::Value>,

    /// Optional: icon metadata (tooling-specific representation)
    pub icons: Option<serde_json::Value>,

    /// Optional: annotations (should be treated as untrusted)
    #[serde(default)]
    pub annotations: Option<HashMap<String, serde_json::Value>>,

    /// Optional: requires user approval before invocation
    #[serde(rename = "requiresApproval")]
    pub requires_approval: Option<bool>,

    /// Optional: confirmation field for consent
    pub confirmation: Option<String>,
}

/// MCP resource definition schema
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)] // deserialized from JSON; fields not individually accessed
pub struct McpResourceSchema {
    /// Required: RFC3986 URI identifier
    pub uri: Option<String>,

    /// Required: resource name
    pub name: Option<String>,

    /// Optional: human-readable display name
    pub title: Option<String>,

    /// Optional: resource description
    pub description: Option<String>,

    /// Optional: MIME type
    #[serde(rename = "mimeType")]
    pub mime_type: Option<String>,

    /// Optional: size metadata
    pub size: Option<serde_json::Value>,

    /// Optional: resource annotations
    #[serde(default)]
    pub annotations: Option<HashMap<String, serde_json::Value>>,
}

/// MCP resource read content schema
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)] // deserialized from JSON; fields not individually accessed
pub struct McpResourceContentSchema {
    /// Required: resource URI
    pub uri: Option<String>,

    /// Required: MIME type
    #[serde(rename = "mimeType")]
    pub mime_type: Option<String>,

    /// Optional: text content
    pub text: Option<String>,

    /// Optional: base64 blob content
    pub blob: Option<String>,
}

/// MCP prompt argument schema
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)] // deserialized from JSON; fields not individually accessed
pub struct McpPromptArgumentSchema {
    /// Required: argument name
    pub name: Option<String>,

    /// Optional: argument description
    pub description: Option<String>,

    /// Optional: required flag
    pub required: Option<bool>,
}

/// MCP prompt definition schema
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)] // deserialized from JSON; fields not individually accessed
pub struct McpPromptSchema {
    /// Required: prompt name
    pub name: Option<String>,

    /// Optional: prompt description
    pub description: Option<String>,

    /// Optional: prompt display title
    pub title: Option<String>,

    /// Optional: arguments definition (validated in rule layer)
    pub arguments: Option<serde_json::Value>,
}

/// MCP JSON-RPC message schema
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpJsonRpcMessage {
    /// Must be "2.0"
    pub jsonrpc: Option<String>,

    /// Request/response ID
    pub id: Option<serde_json::Value>,

    /// Method name
    pub method: Option<String>,

    /// Parameters
    pub params: Option<serde_json::Value>,

    /// Result (for responses)
    pub result: Option<serde_json::Value>,

    /// Error (for error responses)
    pub error: Option<serde_json::Value>,
}

/// Valid MCP server transport types
pub const VALID_MCP_SERVER_TYPES: &[&str] = &["stdio", "http", "sse"];

/// MCP server configuration (as used in .mcp.json or settings.json)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpServerConfig {
    /// Transport type: stdio (default), http, or sse
    #[serde(rename = "type")]
    pub server_type: Option<String>,

    /// Command to run the server (required for stdio)
    pub command: Option<serde_json::Value>, // Can be string or array

    /// Command arguments
    #[serde(default)]
    pub args: Option<serde_json::Value>,

    /// Environment variables
    #[serde(default)]
    pub env: Option<HashMap<String, String>>,

    /// Server endpoint URL (required for http/sse)
    pub url: Option<String>,
}

/// MCP configuration file schema (standalone .mcp.json)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)] // deserialized from JSON; fields not individually accessed
pub struct McpConfigSchema {
    /// Server definitions
    #[serde(rename = "mcpServers")]
    pub mcp_servers: Option<HashMap<String, McpServerConfig>>,

    /// Tools array (for tool definition files)
    pub tools: Option<Vec<McpToolSchema>>,

    /// Resources array (for resources/list payloads)
    pub resources: Option<Vec<McpResourceSchema>>,

    /// Prompts array (for prompts/list payloads)
    pub prompts: Option<Vec<McpPromptSchema>>,

    /// Capability map (for initialize payloads)
    pub capabilities: Option<HashMap<String, serde_json::Value>>,

    /// JSON-RPC version (for message files)
    pub jsonrpc: Option<String>,
}

/// Valid JSON Schema types
pub const VALID_JSON_SCHEMA_TYPES: &[&str] = &[
    "string", "number", "integer", "boolean", "object", "array", "null",
];

/// Default MCP protocol version (latest stable per MCP spec 2025-11-25)
pub const DEFAULT_MCP_PROTOCOL_VERSION: &str = "2025-11-25";

/// MCP initialize request params
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)] // deserialized from JSON; fields not individually accessed
pub struct McpInitializeParams {
    /// Protocol version requested by client
    #[serde(rename = "protocolVersion")]
    pub protocol_version: Option<String>,

    /// Client info
    #[serde(rename = "clientInfo")]
    pub client_info: Option<serde_json::Value>,

    /// Capabilities
    pub capabilities: Option<serde_json::Value>,
}

/// MCP initialize result (from server response)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)] // deserialized from JSON; fields not individually accessed
pub struct McpInitializeResult {
    /// Protocol version negotiated by server
    #[serde(rename = "protocolVersion")]
    pub protocol_version: Option<String>,

    /// Server info
    #[serde(rename = "serverInfo")]
    pub server_info: Option<serde_json::Value>,

    /// Server capabilities
    pub capabilities: Option<serde_json::Value>,
}

/// Check if a JSON-RPC message is an initialize request
pub fn is_initialize_message(value: &serde_json::Value) -> bool {
    value
        .get("method")
        .and_then(|m| m.as_str())
        .is_some_and(|m| m == "initialize")
}

/// Check if a JSON-RPC message is an initialize response (has result with protocolVersion)
pub fn is_initialize_response(value: &serde_json::Value) -> bool {
    value
        .get("result")
        .and_then(|r| r.get("protocolVersion"))
        .is_some()
}

/// Extract protocol version from an initialize request's params
pub fn extract_request_protocol_version(value: &serde_json::Value) -> Option<String> {
    value
        .get("params")
        .and_then(|p| p.get("protocolVersion"))
        .and_then(|v| v.as_str())
        .map(|s| s.to_string())
}

/// Extract protocol version from an initialize response's result
pub fn extract_response_protocol_version(value: &serde_json::Value) -> Option<String> {
    value
        .get("result")
        .and_then(|r| r.get("protocolVersion"))
        .and_then(|v| v.as_str())
        .map(|s| s.to_string())
}

impl McpToolSchema {
    /// Check if all required fields are present
    pub fn has_required_fields(&self) -> (bool, bool, bool) {
        (
            !self.name.as_deref().unwrap_or("").trim().is_empty(),
            !self.description.as_deref().unwrap_or("").trim().is_empty(),
            self.input_schema.is_some(),
        )
    }

    /// Check if description is meaningful (not empty, reasonably long)
    pub fn has_meaningful_description(&self) -> bool {
        self.description
            .as_deref()
            .is_some_and(|desc| !desc.trim().is_empty() && desc.len() >= 10)
    }

    /// Check if tool has consent-related fields with meaningful values
    /// - requiresApproval must be true (false doesn't indicate consent mechanism)
    /// - confirmation must be a non-empty string
    pub fn has_consent_fields(&self) -> bool {
        self.requires_approval == Some(true)
            || self
                .confirmation
                .as_deref()
                .is_some_and(|c| !c.trim().is_empty())
    }

    /// Check if tool has annotations (which should be validated)
    pub fn has_annotations(&self) -> bool {
        self.annotations.as_ref().is_some_and(|a| !a.is_empty())
    }
}

impl McpJsonRpcMessage {
    /// Check if JSON-RPC version is valid (must be "2.0")
    #[allow(dead_code)] // schema-level API; validation uses Validator trait
    pub fn has_valid_jsonrpc_version(&self) -> bool {
        match &self.jsonrpc {
            Some(version) => version == "2.0",
            None => false,
        }
    }
}

/// Validate JSON Schema structure (basic structural validation)
pub fn validate_json_schema_structure(schema: &serde_json::Value) -> Vec<String> {
    let mut errors = Vec::new();

    // Must be an object
    if !schema.is_object() {
        errors.push("inputSchema must be an object".to_string());
        return errors;
    }

    let obj = schema.as_object().unwrap();

    // If "type" field exists, must be a valid JSON Schema type
    if let Some(type_val) = obj.get("type") {
        if let Some(type_str) = type_val.as_str() {
            if !VALID_JSON_SCHEMA_TYPES.contains(&type_str) {
                errors.push(format!(
                    "Invalid JSON Schema type '{}', expected one of: {}",
                    type_str,
                    VALID_JSON_SCHEMA_TYPES.join(", ")
                ));
            }
        } else if let Some(type_arr) = type_val.as_array() {
            // Type can also be an array of types (union type)
            for t in type_arr {
                if let Some(t_str) = t.as_str() {
                    if !VALID_JSON_SCHEMA_TYPES.contains(&t_str) {
                        errors.push(format!(
                            "Invalid JSON Schema type '{}' in type array",
                            t_str
                        ));
                    }
                } else {
                    // Non-string element in type array
                    errors.push("'type' array elements must be strings".to_string());
                }
            }
        } else {
            // type field is neither string nor array (e.g., number, object, boolean)
            errors.push("'type' field must be a string or array of strings".to_string());
        }
    }

    // If "properties" field exists, must be an object
    if let Some(props) = obj.get("properties") {
        if !props.is_object() {
            errors.push("'properties' field must be an object".to_string());
        }
    }

    // If "required" field exists, must be an array of strings
    if let Some(required) = obj.get("required") {
        if let Some(arr) = required.as_array() {
            for item in arr {
                if !item.is_string() {
                    errors.push("'required' array must contain only strings".to_string());
                    break;
                }
            }
        } else {
            errors.push("'required' field must be an array".to_string());
        }
    }

    errors
}

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

    #[test]
    fn test_mcp_tool_has_required_fields() {
        let tool = McpToolSchema {
            name: Some("test-tool".to_string()),
            description: Some("A test tool".to_string()),
            input_schema: Some(json!({"type": "object"})),
            title: None,
            output_schema: None,
            icons: None,
            annotations: None,
            requires_approval: None,
            confirmation: None,
        };
        assert_eq!(tool.has_required_fields(), (true, true, true));
    }

    #[test]
    fn test_mcp_tool_missing_name() {
        let tool = McpToolSchema {
            name: None,
            description: Some("A test tool".to_string()),
            input_schema: Some(json!({"type": "object"})),
            title: None,
            output_schema: None,
            icons: None,
            annotations: None,
            requires_approval: None,
            confirmation: None,
        };
        assert_eq!(tool.has_required_fields(), (false, true, true));
    }

    #[test]
    fn test_mcp_tool_empty_name() {
        let tool = McpToolSchema {
            name: Some("".to_string()),
            description: Some("A test tool".to_string()),
            input_schema: Some(json!({"type": "object"})),
            title: None,
            output_schema: None,
            icons: None,
            annotations: None,
            requires_approval: None,
            confirmation: None,
        };
        assert_eq!(tool.has_required_fields(), (false, true, true));
    }

    #[test]
    fn test_meaningful_description() {
        let tool = McpToolSchema {
            name: Some("test".to_string()),
            description: Some("This is a meaningful description".to_string()),
            input_schema: None,
            title: None,
            output_schema: None,
            icons: None,
            annotations: None,
            requires_approval: None,
            confirmation: None,
        };
        assert!(tool.has_meaningful_description());
    }

    #[test]
    fn test_short_description() {
        let tool = McpToolSchema {
            name: Some("test".to_string()),
            description: Some("Short".to_string()),
            input_schema: None,
            title: None,
            output_schema: None,
            icons: None,
            annotations: None,
            requires_approval: None,
            confirmation: None,
        };
        assert!(!tool.has_meaningful_description());
    }

    #[test]
    fn test_consent_fields_requires_approval_true() {
        let tool = McpToolSchema {
            name: Some("test".to_string()),
            description: None,
            input_schema: None,
            title: None,
            output_schema: None,
            icons: None,
            annotations: None,
            requires_approval: Some(true),
            confirmation: None,
        };
        assert!(tool.has_consent_fields());
    }

    #[test]
    fn test_consent_fields_requires_approval_false() {
        // requiresApproval: false should NOT count as having consent mechanism
        let tool = McpToolSchema {
            name: Some("test".to_string()),
            description: None,
            input_schema: None,
            title: None,
            output_schema: None,
            icons: None,
            annotations: None,
            requires_approval: Some(false),
            confirmation: None,
        };
        assert!(!tool.has_consent_fields());
    }

    #[test]
    fn test_consent_fields_confirmation_non_empty() {
        let tool = McpToolSchema {
            name: Some("test".to_string()),
            description: None,
            input_schema: None,
            title: None,
            output_schema: None,
            icons: None,
            annotations: None,
            requires_approval: None,
            confirmation: Some("Are you sure?".to_string()),
        };
        assert!(tool.has_consent_fields());
    }

    #[test]
    fn test_consent_fields_confirmation_empty() {
        // Empty confirmation should NOT count as having consent mechanism
        let tool = McpToolSchema {
            name: Some("test".to_string()),
            description: None,
            input_schema: None,
            title: None,
            output_schema: None,
            icons: None,
            annotations: None,
            requires_approval: None,
            confirmation: Some("".to_string()),
        };
        assert!(!tool.has_consent_fields());
    }

    #[test]
    fn test_consent_fields_confirmation_whitespace() {
        // Whitespace-only confirmation should NOT count as having consent mechanism
        let tool = McpToolSchema {
            name: Some("test".to_string()),
            description: None,
            input_schema: None,
            title: None,
            output_schema: None,
            icons: None,
            annotations: None,
            requires_approval: None,
            confirmation: Some("   ".to_string()),
        };
        assert!(!tool.has_consent_fields());
    }

    #[test]
    fn test_jsonrpc_version_valid() {
        let msg = McpJsonRpcMessage {
            jsonrpc: Some("2.0".to_string()),
            id: None,
            method: None,
            params: None,
            result: None,
            error: None,
        };
        assert!(msg.has_valid_jsonrpc_version());
    }

    #[test]
    fn test_jsonrpc_version_invalid() {
        let msg = McpJsonRpcMessage {
            jsonrpc: Some("1.0".to_string()),
            id: None,
            method: None,
            params: None,
            result: None,
            error: None,
        };
        assert!(!msg.has_valid_jsonrpc_version());
    }

    #[test]
    fn test_validate_schema_structure_valid() {
        let schema = json!({
            "type": "object",
            "properties": {
                "name": {"type": "string"}
            },
            "required": ["name"]
        });
        let errors = validate_json_schema_structure(&schema);
        assert!(errors.is_empty());
    }

    #[test]
    fn test_validate_schema_structure_invalid_type() {
        let schema = json!({
            "type": "invalid_type"
        });
        let errors = validate_json_schema_structure(&schema);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("Invalid JSON Schema type"));
    }

    #[test]
    fn test_validate_schema_not_object() {
        let schema = json!("not an object");
        let errors = validate_json_schema_structure(&schema);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("must be an object"));
    }

    #[test]
    fn test_validate_schema_type_not_string_or_array() {
        // type field is a number - should error
        let schema = json!({"type": 123});
        let errors = validate_json_schema_structure(&schema);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("must be a string or array"));
    }

    #[test]
    fn test_validate_schema_type_array_with_non_string() {
        // type array contains non-string elements
        let schema = json!({"type": ["string", 123]});
        let errors = validate_json_schema_structure(&schema);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("must be strings"));
    }

    #[test]
    fn test_validate_schema_type_object_value() {
        // type field is an object - should error
        let schema = json!({"type": {"nested": "object"}});
        let errors = validate_json_schema_structure(&schema);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("must be a string or array"));
    }

    // ===== Protocol Version Helper Tests =====

    #[test]
    fn test_is_initialize_message() {
        let msg = json!({"jsonrpc": "2.0", "method": "initialize", "id": 1});
        assert!(super::is_initialize_message(&msg));

        let other = json!({"jsonrpc": "2.0", "method": "tools/list", "id": 1});
        assert!(!super::is_initialize_message(&other));

        let no_method = json!({"jsonrpc": "2.0", "id": 1});
        assert!(!super::is_initialize_message(&no_method));
    }

    #[test]
    fn test_is_initialize_response() {
        let response = json!({
            "jsonrpc": "2.0",
            "id": 1,
            "result": {"protocolVersion": "2025-11-25"}
        });
        assert!(super::is_initialize_response(&response));

        let other_response = json!({
            "jsonrpc": "2.0",
            "id": 1,
            "result": {"tools": []}
        });
        assert!(!super::is_initialize_response(&other_response));
    }

    #[test]
    fn test_extract_request_protocol_version() {
        let msg = json!({
            "jsonrpc": "2.0",
            "method": "initialize",
            "id": 1,
            "params": {"protocolVersion": "2024-11-05"}
        });
        assert_eq!(
            super::extract_request_protocol_version(&msg),
            Some("2024-11-05".to_string())
        );

        let no_version = json!({
            "jsonrpc": "2.0",
            "method": "initialize",
            "id": 1,
            "params": {}
        });
        assert_eq!(super::extract_request_protocol_version(&no_version), None);
    }

    #[test]
    fn test_extract_response_protocol_version() {
        let response = json!({
            "jsonrpc": "2.0",
            "id": 1,
            "result": {"protocolVersion": "2025-11-25"}
        });
        assert_eq!(
            super::extract_response_protocol_version(&response),
            Some("2025-11-25".to_string())
        );

        let no_version = json!({
            "jsonrpc": "2.0",
            "id": 1,
            "result": {}
        });
        assert_eq!(super::extract_response_protocol_version(&no_version), None);
    }

    #[test]
    fn test_default_mcp_protocol_version_constant() {
        assert_eq!(super::DEFAULT_MCP_PROTOCOL_VERSION, "2025-11-25");
    }
}