Skip to main content

qualia_mcp/
types.rs

1//! Types and data structures for the Model Context Protocol (MCP) server.
2//!
3//! Designed according to `AGENTS.md` ยง0-B (focused, single-purpose, <500 lines).
4
5use serde::{Deserialize, Serialize};
6
7/// Explicit operational states defining the execution boundaries.
8#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
9pub enum McpRuntimeState {
10    HandshakePhase,
11    AllocationFirewallActive,
12    SanctuaryGated,
13}
14
15/// System and dispatch errors surfaced through standard MCP/JSON-RPC channels.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum McpSystemError {
18    SanctuaryGateTriggered,
19    ToolNotFound,
20    ToolNotReady,
21    ParseError,
22    IntentFrameViolation,
23    FeatureNotEnabled,
24    InvalidParameters,
25    ExecutionFailed(String),
26}
27
28impl core::fmt::Display for McpSystemError {
29    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
30        match self {
31            Self::SanctuaryGateTriggered => write!(f, "Sanctuary gate triggered"),
32            Self::ToolNotFound => write!(f, "Tool not found"),
33            Self::ToolNotReady => write!(f, "Tool not implemented on the current MCP surface"),
34            Self::ParseError => write!(f, "Parse error"),
35            Self::IntentFrameViolation => write!(f, "Intent frame violation"),
36            Self::FeatureNotEnabled => write!(f, "Feature not enabled"),
37            Self::InvalidParameters => write!(f, "Invalid parameters"),
38            Self::ExecutionFailed(msg) => write!(f, "Execution failed: {msg}"),
39        }
40    }
41}
42
43impl std::error::Error for McpSystemError {}
44
45/// Operational intent and security boundary context for tool invocations.
46#[derive(Debug, Clone)]
47pub struct McpIntentFrame {
48    pub purpose_hash: u64,
49    pub active_deontic_constraints: Vec<u64>,
50    pub active_profile_id: Option<u64>,
51    pub session_nonce: u64,
52    /// Cryptographic 32-byte egress-override token. Fails closed when missing or zero.
53    pub sanctuary_override: Option<[u8; 32]>,
54    pub qpu_enabled: bool,
55    pub llm_enabled: bool,
56}
57
58impl Default for McpIntentFrame {
59    fn default() -> Self {
60        Self {
61            purpose_hash: 0,
62            active_deontic_constraints: Vec::new(),
63            active_profile_id: None,
64            session_nonce: 0,
65            sanctuary_override: None,
66            qpu_enabled: true,
67            llm_enabled: true,
68        }
69    }
70}
71
72/// Zero-deserialization view over an incoming `tools/call` byte buffer.
73pub struct RawToolPayload<'a> {
74    pub tool_name: &'a [u8],
75    pub arguments_raw: &'a [u8],
76}
77
78/// Static descriptor for an advertised MCP tool.
79#[derive(Clone, Copy, Debug)]
80pub struct McpToolDescriptor {
81    pub name: &'static str,
82    pub description: &'static str,
83    pub input_schema: &'static str,
84}
85
86/// Extract a raw JSON string value for `key` without heap allocation.
87pub fn extract_raw_json_string<'a>(payload: &'a [u8], key: &[u8]) -> Option<&'a [u8]> {
88    let mut i = 0;
89    while i < payload.len() {
90        if payload[i..].starts_with(key) {
91            i += key.len();
92            while i < payload.len() && (payload[i] == b' ' || payload[i] == b':') {
93                i += 1;
94            }
95            if i < payload.len() && payload[i] == b'"' {
96                i += 1;
97                let start = i;
98                while i < payload.len() && payload[i] != b'"' {
99                    i += 1;
100                }
101                return Some(&payload[start..i]);
102            }
103        }
104        i += 1;
105    }
106    None
107}
108
109/// Root storage dir: `QUALIA_STORAGE_PATH`, else `~/.qualia`
110/// (HOME/USERPROFILE), else `./.qualia`.
111pub fn qualia_storage_path() -> std::path::PathBuf {
112    std::env::var("QUALIA_STORAGE_PATH")
113        .unwrap_or_else(|_| {
114            std::env::var("HOME")
115                .or_else(|_| std::env::var("USERPROFILE"))
116                .map(|h| format!("{h}/.qualia"))
117                .unwrap_or_else(|_| ".qualia".to_string())
118        })
119        .into()
120}
121
122/// Decodes a hex string into raw bytes.
123pub fn hex_decode(s: &str) -> Result<Vec<u8>, McpSystemError> {
124    let s = s.trim();
125    if s.len() % 2 != 0 {
126        return Err(McpSystemError::InvalidParameters);
127    }
128    (0..s.len())
129        .step_by(2)
130        .map(|i| {
131            u8::from_str_radix(&s[i..i + 2], 16).map_err(|_| McpSystemError::InvalidParameters)
132        })
133        .collect()
134}
135
136/// Helper to parse tool arguments from raw JSON bytes.
137pub fn parse_tool_args(args: &[u8]) -> Result<serde_json::Value, McpSystemError> {
138    if args.is_empty() {
139        return Ok(serde_json::json!({}));
140    }
141    serde_json::from_slice(args).map_err(|_| McpSystemError::ParseError)
142}
143
144/// Helper to parse a slice of quins from JSON.
145pub fn parse_quin_slice(v: &serde_json::Value, field: &str) -> Result<Vec<qualia_core_db::NQuin>, McpSystemError> {
146    let arr = v.get(field).and_then(serde_json::Value::as_array).ok_or(McpSystemError::InvalidParameters)?;
147    let mut quins = Vec::with_capacity(arr.len());
148    for item in arr {
149        let subject = item.get("subject").and_then(serde_json::Value::as_u64).unwrap_or(0);
150        let predicate = item.get("predicate").and_then(serde_json::Value::as_u64).unwrap_or(0);
151        let object = item.get("object").and_then(serde_json::Value::as_u64).unwrap_or(0);
152        let context = item.get("context").and_then(serde_json::Value::as_u64).unwrap_or(0);
153        let metadata = item.get("metadata").and_then(serde_json::Value::as_u64).unwrap_or(0);
154        let parity = item.get("parity").and_then(serde_json::Value::as_u64).unwrap_or(subject ^ predicate ^ object ^ context ^ metadata);
155        quins.push(qualia_core_db::NQuin { subject, predicate, object, context, metadata, parity });
156    }
157    Ok(quins)
158}