tenuo 0.1.0-beta.20

Agent Capability Flow Control - Rust core library
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
//! MCP (Model Context Protocol) Integration Helpers
//!
//! This module provides configuration and helpers for integrating Tenuo with MCP servers.
//! Unlike the HTTP gateway, MCP is tool-centric, so we don't need route matching.
//! We just need to map MCP tool names to Tenuo tool configurations.
//!
//! # What is MCP?
//!
//! The [Model Context Protocol](https://modelcontextprotocol.io) is an open protocol for
//! connecting AI assistants to external data sources and tools. MCP servers expose tools that
//! AI models can call, and Tenuo provides authorization for those tool calls.
//!
//! # Why MCP + Tenuo?
//!
//! **Native AI Agent Integration**: MCP is the standard protocol for AI agent tool calling.
//! Tenuo's MCP integration means you can secure AI agent workflows without custom middleware.
//!
//! **Tool-Centric Authorization**: MCP tools map directly to Tenuo tool configurations.
//! No HTTP routing complexity—just map tool names to constraints.
//!
//! **Cryptographic Provenance**: Every tool call is authorized by a warrant chain that proves
//! who delegated the authority and what bounds apply. Perfect for multi-agent workflows where
//! an orchestrator delegates to specialized workers.
//!
//! # Example
//!
//! ```yaml
//! # mcp-config.yaml
//! version: "1"
//! settings:
//!   trusted_issuers:
//!     - "f32e74b5a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8"
//!
//! tools:
//!   filesystem_read:
//!     description: "Read files from the filesystem"
//!     constraints:
//!       path:
//!         from: body
//!         path: "path"
//!         required: true
//!       max_size:
//!         from: body
//!         path: "maxSize"
//!         type: integer
//!         default: 1048576
//! ```
//!
//! ```rust,ignore
//! use tenuo::{Authorizer, CompiledMcpConfig, McpConfig, PublicKey, wire};
//! use serde_json::json;
//!
//! // Load and compile configuration
//! let config = McpConfig::from_file("mcp-config.yaml")?;
//! let compiled = CompiledMcpConfig::compile(config);
//!
//! // Validate configuration (warns about incompatible extraction sources)
//! let warnings = compiled.validate();
//! for warning in warnings {
//!     eprintln!("Warning: {}", warning);
//! }
//!
//! // Initialize authorizer with trusted Control Plane key
//! let control_plane_key_bytes: [u8; 32] = hex::decode("f32e74b5...")?.try_into().unwrap();
//! let control_plane_key = PublicKey::from_bytes(&control_plane_key_bytes)?;
//! let authorizer = Authorizer::new().with_trusted_root(control_plane_key);
//!
//! // MCP tool call arrives from AI agent
//! let arguments = json!({
//!     "path": "/var/log/app.log",
//!     "maxSize": 1024
//! });
//!
//! // Warrant + PoP travel in params._meta.tenuo (handled by Python SDK).
//! // Rust extract_constraints() only extracts constraints from arguments.
//!
//! // 1. Extract constraints from arguments
//! let result = compiled.extract_constraints("filesystem_read", &arguments)?;
//!
//! // 2. Authorize (warrant, PoP, approvals come from params._meta on the Python side)
//! authorizer.authorize_one(
//!     &warrant,
//!     "filesystem_read",
//!     &result.constraints,
//!     Some(&pop_sig),
//!     &approvals,
//! )?;
//!
//! // 3. If authorized, execute the tool
//! // execute_filesystem_read(arguments);
//! ```
//!
//! # Extraction Source Compatibility
//!
//! MCP tool calls only provide an `arguments` JSON object. Extraction rules should use:
//! - `from: body` - Extract from the arguments object (default for MCP)
//! - `from: literal` - Use a default/literal value
//!
//! **Config Sugar**: `from: body` is implicit in MCP configs. These are equivalent:
//! ```yaml
//! # Explicit (verbose)
//! constraints:
//!   path:
//!     from: body
//!     path: "path"
//!
//! # Implicit (recommended for MCP)
//! constraints:
//!   path: "path"  # Defaults to from: body
//! ```
//!
//! Rules using `from: path`, `from: query`, or `from: header` will not work in MCP context
//! and will be flagged by `validate()`.
//!
//! # JSON-RPC Error Mapping
//!
//! MCP uses JSON-RPC 2.0. Map Tenuo errors to standard codes:
//! - `ExtractionError` (missing required field) → `-32602` (Invalid params)
//! - `ConstraintViolation` → `-32001` (Access denied, custom)
//! - `ExpiredError` → `-32001` (Access denied)
//!
//! Use `to_jsonrpc_error()` helper to convert.

use crate::extraction::{
    CompiledExtractionRules, ExtractionError, ExtractionSource, RequestContext,
};
use crate::gateway_config::{ExtractionResult, ToolConfig};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[cfg(not(target_arch = "wasm32"))]
use std::path::Path;

const MAX_TOOLS_COUNT: usize = 200;
const MAX_CONSTRAINT_COUNT_PER_TOOL: usize = crate::wire::MAX_CONSTRAINTS_PER_TOOL;

/// MCP Gateway Configuration.
///
/// Simpler than `GatewayConfig` as it doesn't need HTTP routing.
/// It maps MCP tool names directly to Tenuo tool configurations.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpConfig {
    /// Configuration version
    pub version: String,
    /// Global settings
    #[serde(default)]
    pub settings: McpSettings,
    /// Tool definitions
    /// Key: MCP Tool Name
    /// Value: Tenuo Tool Configuration
    pub tools: HashMap<String, ToolConfig>,
}

/// Global MCP settings.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct McpSettings {
    /// Trusted Control Plane public keys (hex)
    #[serde(default)]
    pub trusted_issuers: Vec<String>,
}

/// Compiled MCP Configuration for performance.
pub struct CompiledMcpConfig {
    pub settings: McpSettings,
    /// Map of MCP Tool Name -> Compiled Rules
    pub tools: HashMap<String, CompiledTool>,
}

pub struct CompiledTool {
    pub config: ToolConfig,
    pub extraction_rules: CompiledExtractionRules,
}

impl McpConfig {
    /// Load configuration from a file.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn from_file(path: impl AsRef<Path>) -> Result<Self, crate::gateway_config::ConfigError> {
        let content = std::fs::read_to_string(path.as_ref()).map_err(|e| {
            crate::gateway_config::ConfigError::FileRead(path.as_ref().display().to_string(), e)
        })?;
        serde_yaml::from_str(&content).map_err(crate::gateway_config::ConfigError::YamlParse)
    }
}

impl CompiledMcpConfig {
    /// Compile the configuration.
    pub fn compile(config: McpConfig) -> crate::error::Result<Self> {
        if config.tools.len() > MAX_TOOLS_COUNT {
            return Err(crate::error::Error::ConfigurationError(format!(
                "Too many tools: {} (maximum {})",
                config.tools.len(),
                MAX_TOOLS_COUNT
            )));
        }

        let mut tools = HashMap::new();

        for (name, tool_config) in config.tools {
            if tool_config.constraints.len() > MAX_CONSTRAINT_COUNT_PER_TOOL {
                return Err(crate::error::Error::ConfigurationError(format!(
                    "Too many constraints for tool '{}': {} (maximum {})",
                    name,
                    tool_config.constraints.len(),
                    MAX_CONSTRAINT_COUNT_PER_TOOL
                )));
            }

            let rules = CompiledExtractionRules::compile(tool_config.constraints.clone());
            tools.insert(
                name,
                CompiledTool {
                    config: tool_config,
                    extraction_rules: rules,
                },
            );
        }

        Ok(Self {
            settings: config.settings,
            tools,
        })
    }

    /// Validate that extraction rules are compatible with MCP (body-only).
    ///
    /// MCP tool calls only provide an `arguments` JSON object, so extraction rules
    /// should use `from: body` or `from: literal`. Rules using `from: path`,
    /// `from: query`, or `from: header` will not work and will be flagged here.
    ///
    /// Returns a list of warning messages for incompatible rules.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let config = McpConfig::from_file("mcp-config.yaml")?;
    /// let compiled = CompiledMcpConfig::compile(config);
    ///
    /// let warnings = compiled.validate();
    /// for warning in warnings {
    ///     eprintln!("Warning: {}", warning);
    /// }
    /// ```
    pub fn validate(&self) -> Vec<String> {
        let mut warnings = Vec::new();
        for (tool_name, compiled_tool) in &self.tools {
            for (field_name, rule) in &compiled_tool.extraction_rules.rules {
                match rule.rule.from {
                    ExtractionSource::Path | ExtractionSource::Query | ExtractionSource::Header => {
                        warnings.push(format!(
                            "Tool '{}' field '{}' uses {:?} source, which won't work in MCP (only body/literal supported)",
                            tool_name, field_name, rule.rule.from
                        ));
                    }
                    ExtractionSource::Body | ExtractionSource::Literal => {
                        // These are fine
                    }
                }
            }
        }
        warnings
    }

    /// Extract constraints from MCP tool call arguments.
    ///
    /// Pure constraint extraction — no warrant/signature handling.
    /// Warrant and PoP transport is handled by `params._meta.tenuo` at the
    /// Python SDK layer (see `MCPVerifier`).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let arguments = json!({
    ///     "path": "/var/log/app.log",
    ///     "maxSize": 1024
    /// });
    ///
    /// let result = compiled.extract_constraints("filesystem_read", &arguments)?;
    /// // result.constraints contains extracted values
    /// ```
    pub fn extract_constraints(
        &self,
        tool_name: &str,
        arguments: &serde_json::Value,
    ) -> Result<ExtractionResult, ExtractionError> {
        let tool = self.tools.get(tool_name).ok_or_else(|| ExtractionError {
            field: "tool".to_string(),
            source: ExtractionSource::Literal,
            path: tool_name.to_string(),
            hint: format!("Tool '{}' not defined in Tenuo configuration", tool_name),
            required: true,
        })?;

        let ctx = RequestContext::with_body(arguments.clone());

        let (constraints, traces) = tool.extraction_rules.extract_all(&ctx)?;

        Ok(ExtractionResult {
            constraints,
            traces,
            tool: tool_name.to_string(),
            warrant_base64: None,
            signature_base64: None,
            approvals_base64: Vec::new(),
        })
    }
}

/// Map Tenuo errors to JSON-RPC 2.0 error codes.
///
/// MCP uses JSON-RPC, so authorization failures should return standard codes:
/// - `-32602`: Invalid params (missing required fields)
/// - `-32001`: Access denied (authorization failure, custom code)
///
/// # Example
///
/// ```rust,ignore
/// match compiled.extract_constraints(tool, args) {
///     Ok(result) => { /* authorize and execute */ },
///     Err(e) => {
///         let (code, message) = to_jsonrpc_error(&e);
///         return jsonrpc_error_response(id, code, message);
///     }
/// }
/// ```
pub fn to_jsonrpc_error(error: &ExtractionError) -> (i32, String) {
    // JSON-RPC 2.0 error codes:
    // -32700: Parse error
    // -32600: Invalid Request
    // -32601: Method not found
    // -32602: Invalid params
    // -32603: Internal error
    // -32001 to -32099: Server error (custom)

    if error.required {
        // Missing required field or invalid value
        (-32602, format!("Invalid params: {}", error.hint))
    } else {
        // Other extraction errors (shouldn't happen for optional fields)
        (-32602, format!("Invalid params: {}", error.hint))
    }
}

/// Map authorization errors to JSON-RPC codes.
///
/// For use after successful extraction when authorization fails:
/// - `ConstraintViolation` → `-32001` (Access denied)
/// - `ExpiredError` → `-32001` (Access denied)
/// - `SignatureInvalid` → `-32001` (Access denied)
/// - `ApprovalRequired` → `-32002` (Approval required)
///
/// # Example
///
/// ```rust,ignore
/// match authorizer.authorize_one(&warrant, tool, &constraints, signature, &[]) {
///     Ok(_) => { /* execute tool */ },
///     Err(e) => {
///         let (code, message) = auth_error_to_jsonrpc(&e);
///         return jsonrpc_error_response(id, code, message);
///     }
/// }
/// ```
pub fn auth_error_to_jsonrpc(error: &crate::error::Error) -> (i32, String) {
    use crate::error::Error;

    match error {
        Error::ConstraintNotSatisfied { field, reason } => (
            -32001,
            format!(
                "Access denied: Constraint '{}' not satisfied: {}",
                field, reason
            ),
        ),
        Error::WarrantExpired(_) => (-32001, "Access denied: Warrant expired".to_string()),
        Error::SignatureInvalid(_) => (-32001, "Access denied: Invalid signature".to_string()),
        Error::ToolMismatch { .. } => (-32001, "Access denied: Tool not authorized".to_string()),
        Error::ApprovalRequired { tool, .. } => (
            -32002,
            format!(
                "Approval required for tool '{}'. Supply approvals in params._meta.tenuo.approvals.",
                tool
            ),
        ),
        _ => (-32001, format!("Access denied: {}", error)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::extraction::{ExtractionRule, ExtractionSource};
    use std::collections::HashMap;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_mcp_config_from_file() {
        // Create a temporary YAML file
        let yaml_content = r#"
version: "1"
settings:
  trusted_issuers:
    - "f32e74b5a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8"
tools:
  filesystem_read:
    description: "Read files from the filesystem"
    constraints:
      path:
        from: body
        path: "path"
        required: true
      max_size:
        from: body
        path: "maxSize"
        type: integer
        default: 1048576
"#;
        let mut file = NamedTempFile::new().unwrap();
        write!(file, "{}", yaml_content).unwrap();
        let path = file.path();

        let config = McpConfig::from_file(path).unwrap();
        assert_eq!(config.version, "1");
        assert_eq!(config.settings.trusted_issuers.len(), 1);
        assert!(config.tools.contains_key("filesystem_read"));
    }

    #[test]
    fn test_mcp_config_invalid_file() {
        let result = McpConfig::from_file("/nonexistent/path.yaml");
        assert!(result.is_err());
    }

    #[test]
    fn test_compiled_mcp_config_compile() {
        let mut tools = HashMap::new();
        let mut constraints = HashMap::new();

        constraints.insert(
            "path".to_string(),
            ExtractionRule {
                from: ExtractionSource::Body,
                path: "path".to_string(),
                required: true,
                default: None,
                description: None,
                value_type: None,
                allowed_values: None,
            },
        );

        tools.insert(
            "read_file".to_string(),
            ToolConfig {
                description: "Read a file".to_string(),
                constraints,
            },
        );

        let config = McpConfig {
            version: "1".to_string(),
            settings: McpSettings {
                trusted_issuers: vec![],
            },
            tools,
        };

        let compiled = CompiledMcpConfig::compile(config).unwrap();
        assert!(compiled.tools.contains_key("read_file"));
        assert_eq!(compiled.settings.trusted_issuers.len(), 0);
    }

    #[test]
    fn test_compiled_mcp_config_validate() {
        let mut tools = HashMap::new();
        let mut constraints = HashMap::new();

        // Valid: body extraction
        constraints.insert(
            "path".to_string(),
            ExtractionRule {
                from: ExtractionSource::Body,
                path: "path".to_string(),
                required: true,
                default: None,
                description: None,
                value_type: None,
                allowed_values: None,
            },
        );

        tools.insert(
            "read_file".to_string(),
            ToolConfig {
                description: "Read a file".to_string(),
                constraints,
            },
        );

        let config = McpConfig {
            version: "1".to_string(),
            settings: McpSettings {
                trusted_issuers: vec![],
            },
            tools,
        };

        let compiled = CompiledMcpConfig::compile(config).unwrap();
        let warnings = compiled.validate();
        assert_eq!(warnings.len(), 0); // No warnings for valid config
    }

    #[test]
    fn test_compiled_mcp_config_validate_incompatible_source() {
        let mut tools = HashMap::new();
        let mut constraints = HashMap::new();

        // Invalid: path extraction (MCP only has body)
        constraints.insert(
            "path".to_string(),
            ExtractionRule {
                from: ExtractionSource::Path,
                path: "path".to_string(),
                required: true,
                default: None,
                description: None,
                value_type: None,
                allowed_values: None,
            },
        );

        tools.insert(
            "read_file".to_string(),
            ToolConfig {
                description: "Read a file".to_string(),
                constraints,
            },
        );

        let config = McpConfig {
            version: "1".to_string(),
            settings: McpSettings {
                trusted_issuers: vec![],
            },
            tools,
        };

        let compiled = CompiledMcpConfig::compile(config).unwrap();
        let warnings = compiled.validate();
        assert!(!warnings.is_empty()); // Should warn about incompatible source
        assert!(warnings[0].contains("path") || warnings[0].contains("Path"));
    }

    #[test]
    fn test_mcp_config_minimal_without_settings() {
        let yaml_content = r#"
version: "1"
tools:
  read_file:
    description: "Read file contents"
    constraints:
      path:
        from: body
        path: "path"
"#;
        let mut file = NamedTempFile::new().unwrap();
        write!(file, "{}", yaml_content).unwrap();
        let path = file.path();

        let config = McpConfig::from_file(path).unwrap();
        assert_eq!(config.version, "1");
        assert!(config.tools.contains_key("read_file"));
        // settings should be default (empty trusted_issuers)
        assert!(config.settings.trusted_issuers.is_empty());
    }

    #[test]
    fn test_extract_constraints_no_warrant_fields() {
        let mut tools = HashMap::new();
        let mut constraints = HashMap::new();
        constraints.insert(
            "path".to_string(),
            ExtractionRule {
                from: ExtractionSource::Body,
                path: "path".to_string(),
                required: true,
                default: None,
                description: None,
                value_type: None,
                allowed_values: None,
            },
        );
        tools.insert(
            "read_file".to_string(),
            ToolConfig {
                description: "Read a file".to_string(),
                constraints,
            },
        );
        let config = McpConfig {
            version: "1".to_string(),
            settings: McpSettings {
                trusted_issuers: vec![],
            },
            tools,
        };
        let compiled = CompiledMcpConfig::compile(config).unwrap();

        let args = serde_json::json!({
            "path": "/data/file.txt"
        });

        let result = compiled.extract_constraints("read_file", &args).unwrap();
        assert!(result.warrant_base64.is_none());
        assert!(result.signature_base64.is_none());
        assert!(result.approvals_base64.is_empty());
        assert!(result.constraints.contains_key("path"));
    }
}