Skip to main content

qualia_mcp/
protocol.rs

1//! JSON-RPC 2.0 Protocol Handler for Model Context Protocol (MCP).
2//!
3//! Complies with MCP specification (protocol version "2024-11-05").
4//! Strictly adheres to JSON-RPC 2.0 notification rules: notifications (requests without `id`)
5//! NEVER receive a response, preventing client socket closure.
6//! Follows `AGENTS.md` ยง0-B (<500 lines).
7
8use crate::dispatch::enforce_fiduciary_tool_dispatch;
9use crate::registry::tool_list_json;
10use crate::resources::{get_qapp_surface_schema, QAPP_SURFACE_SCHEMA_URI};
11use crate::types::{McpIntentFrame, McpSystemError, RawToolPayload};
12use serde_json::{json, Value};
13
14pub const MCP_PROTOCOL_VERSION: &str = "2024-11-05";
15
16/// Handle a single incoming JSON-RPC 2.0 line.
17/// Returns `Some(response_json)` if the request requires a response, or `None` if it was a notification.
18pub fn process_jsonrpc_message(
19    line: &str,
20    intent_frame: &McpIntentFrame,
21) -> Option<String> {
22    let req: Value = match serde_json::from_str(line) {
23        Ok(v) => v,
24        Err(_) => {
25            return Some(
26                json!({
27                    "jsonrpc": "2.0",
28                    "id": null,
29                    "error": {
30                        "code": -32700,
31                        "message": "Parse error"
32                    }
33                })
34                .to_string(),
35            );
36        }
37    };
38
39    let id = req.get("id");
40    let is_notification = id.is_none() || id == Some(&Value::Null);
41    let method = req.get("method").and_then(Value::as_str).unwrap_or("");
42
43    // JSON-RPC 2.0: notifications never receive responses
44    if is_notification {
45        log::debug!("Received MCP notification: method='{}'", method);
46        return None;
47    }
48
49    let req_id = id.cloned().unwrap_or(Value::Null);
50
51    let result = match method {
52        "initialize" => {
53            let client_version = req
54                .get("params")
55                .and_then(|p| p.get("protocolVersion"))
56                .and_then(Value::as_str)
57                .unwrap_or(MCP_PROTOCOL_VERSION);
58
59            let negotiated_version = match client_version {
60                "2025-11-25" | "2025-06-18" | "2025-03-26" | "2024-11-05" => client_version,
61                _ => MCP_PROTOCOL_VERSION,
62            };
63
64            log::info!(
65                "MCP Handshake initialized with client protocolVersion='{}', negotiated='{}'",
66                client_version,
67                negotiated_version
68            );
69
70            Ok(json!({
71                "protocolVersion": negotiated_version,
72                "capabilities": {
73                    "tools": { "listChanged": false },
74                    "resources": { "subscribe": false, "listChanged": false },
75                    "prompts": { "listChanged": false }
76                },
77                "serverInfo": {
78                    "name": "qualia-mcp",
79                    "version": env!("CARGO_PKG_VERSION")
80                }
81            }))
82        }
83
84        "prompts/list" => Ok(json!({ "prompts": [] })),
85
86        "ping" => Ok(json!({})),
87
88        "tools/list" => Ok(tool_list_json()),
89
90        "tools/call" => {
91            let params = req.get("params").ok_or(McpSystemError::InvalidParameters);
92            match params {
93                Ok(p) => {
94                    let tool_name = p.get("name").and_then(Value::as_str).unwrap_or("");
95                    let default_args = json!({});
96                    let arguments_val = p.get("arguments").unwrap_or(&default_args);
97                    let arguments_raw = arguments_val.to_string();
98
99                    let payload = RawToolPayload {
100                        tool_name: tool_name.as_bytes(),
101                        arguments_raw: arguments_raw.as_bytes(),
102                    };
103
104                    match enforce_fiduciary_tool_dispatch(payload, intent_frame) {
105                        Ok(text_output) => Ok(json!({
106                            "content": [
107                                {
108                                    "type": "text",
109                                    "text": text_output
110                                }
111                            ],
112                            "isError": false
113                        })),
114                        Err(e) => {
115                            let error_msg = format!("Tool '{tool_name}' execution error: {e:?}");
116                            Ok(json!({
117                                "content": [
118                                    {
119                                        "type": "text",
120                                        "text": error_msg
121                                    }
122                                ],
123                                "isError": true
124                            }))
125                        }
126                    }
127                }
128                Err(e) => Err(e),
129            }
130        }
131
132        "resources/list" => Ok(json!({
133            "resources": [
134                {
135                    "uri": QAPP_SURFACE_SCHEMA_URI,
136                    "name": "Qualia QApp Host Surface Schema",
137                    "mimeType": "application/json"
138                }
139            ]
140        })),
141
142        "resources/read" => {
143            let uri = req
144                .get("params")
145                .and_then(|p| p.get("uri"))
146                .and_then(Value::as_str)
147                .unwrap_or("");
148
149            if uri == QAPP_SURFACE_SCHEMA_URI {
150                Ok(json!({
151                    "contents": [
152                        {
153                            "uri": QAPP_SURFACE_SCHEMA_URI,
154                            "mimeType": "application/json",
155                            "text": get_qapp_surface_schema()
156                        }
157                    ]
158                }))
159            } else {
160                Err(McpSystemError::InvalidParameters)
161            }
162        }
163
164        _ => {
165            return Some(
166                json!({
167                    "jsonrpc": "2.0",
168                    "id": req_id,
169                    "error": {
170                        "code": -32601,
171                        "message": format!("Method not found: '{method}'")
172                    }
173                })
174                .to_string(),
175            );
176        }
177    };
178
179    match result {
180        Ok(val) => Some(
181            json!({
182                "jsonrpc": "2.0",
183                "id": req_id,
184                "result": val
185            })
186            .to_string(),
187        ),
188        Err(e) => Some(
189            json!({
190                "jsonrpc": "2.0",
191                "id": req_id,
192                "error": {
193                    "code": -32602,
194                    "message": format!("Invalid params: {e:?}")
195                }
196            })
197            .to_string(),
198        ),
199    }
200}