Skip to main content

qualia_client_core/conditioning/
mcp.rs

1//! MCP lowering adapter with explicit role degradation reporting.
2
3use serde::Serialize;
4use serde_json::{json, Value};
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
7#[serde(rename_all = "snake_case")]
8pub enum McpLoweringMode {
9    Structured,
10    Flattened,
11}
12
13#[derive(Debug, Clone, Serialize)]
14pub struct McpLoweringReceipt {
15    pub mode: McpLoweringMode,
16    pub role_degraded: bool,
17    pub degradation_reason: Option<&'static str>,
18}
19
20/// Lower system prompt and user objective into MCP tool call arguments.
21/// Accurately flags role degradation when flattening into a single string.
22pub fn lower_mcp_tool_arguments(
23    system_prompt: Option<&str>,
24    user_prompt: &str,
25    tool_schema_supports_system_role: bool,
26) -> (Value, McpLoweringReceipt) {
27    if tool_schema_supports_system_role {
28        let val = json!({
29            "system": system_prompt.unwrap_or(""),
30            "prompt": user_prompt,
31        });
32        (
33            val,
34            McpLoweringReceipt {
35                mode: McpLoweringMode::Structured,
36                role_degraded: false,
37                degradation_reason: None,
38            },
39        )
40    } else {
41        let flattened = match system_prompt {
42            Some(sys) if !sys.trim().is_empty() => format!("{sys}\n\n{user_prompt}"),
43            _ => user_prompt.to_string(),
44        };
45        let val = json!({
46            "prompt": flattened,
47        });
48        (
49            val,
50            McpLoweringReceipt {
51                mode: McpLoweringMode::Flattened,
52                role_degraded: system_prompt.is_some(),
53                degradation_reason: if system_prompt.is_some() {
54                    Some("MCP tool schema lacks dedicated system parameter; flattened into prompt")
55                } else {
56                    None
57                },
58            },
59        )
60    }
61}