Skip to main content

reddb_server/mcp/
server.rs

1//! MCP Server for RedDB.
2//!
3//! Runs an embedded RedDB runtime and exposes it to AI agents via the
4//! Model Context Protocol JSON-RPC transport over stdio.
5
6use crate::application::{
7    CreateDocumentInput, CreateEdgeInput, CreateNodeInput, CreateRowInput, CreateVectorInput,
8    DeleteEntityInput, EntityUseCases, ExecuteQueryInput, GraphCentralityInput,
9    GraphClusteringInput, GraphCommunitiesInput, GraphComponentsInput, GraphCyclesInput,
10    GraphShortestPathInput, GraphTraversalInput, GraphUseCases, ScanCollectionInput,
11    SearchSimilarInput, SearchTextInput,
12};
13use crate::auth::store::AuthStore;
14use crate::auth::{AuthConfig, Role};
15use crate::json::{
16    from_str as json_from_str, to_string as json_to_string, Map, Value as JsonValue,
17};
18use crate::mcp::capability::McpCapability;
19use crate::mcp::{protocol, tools};
20use crate::presentation::entity_json::created_entity_output_json;
21use crate::presentation::entity_json::storage_value_to_json;
22use crate::presentation::query_result_json::{runtime_query_json, runtime_stats_json};
23use crate::runtime::agent_tools::{self, RedToolExecutor, ToolExecutionProfile, ToolParseMode};
24use crate::runtime::{
25    RedDBRuntime, RuntimeGraphCentralityAlgorithm, RuntimeGraphCommunityAlgorithm,
26    RuntimeGraphComponentsMode, RuntimeGraphDirection, RuntimeGraphPathAlgorithm,
27    RuntimeGraphTraversalStrategy,
28};
29use crate::storage::EntityId;
30use reddb_types::Value;
31
32use std::io::{self, BufRead, Write};
33use std::sync::Arc;
34
35/// MCP server wrapping an embedded RedDB runtime.
36pub struct McpServer {
37    runtime: RedDBRuntime,
38    auth_store: Arc<AuthStore>,
39    initialized: bool,
40    /// What this session may do. Read-only unless the operator opted in —
41    /// see [`crate::mcp::capability`] for why the tool list, not the
42    /// transport, is the boundary that matters here.
43    capability: McpCapability,
44}
45
46impl McpServer {
47    /// Create a new MCP server with the given runtime.
48    pub fn new(runtime: RedDBRuntime) -> Self {
49        let auth_store = Arc::new(AuthStore::new(AuthConfig {
50            enabled: true,
51            ..Default::default()
52        }));
53        auth_store.bootstrap_from_env();
54        runtime.set_auth_store(Arc::clone(&auth_store));
55        Self {
56            runtime,
57            auth_store,
58            initialized: false,
59            capability: McpCapability::default(),
60        }
61    }
62
63    /// Set the session's capability level. The default is read-only; the
64    /// CLI raises it from `--allow-write` / `--allow-admin`.
65    pub fn with_capability(mut self, capability: McpCapability) -> Self {
66        self.capability = capability;
67        self
68    }
69
70    /// The session's capability level.
71    pub fn capability(&self) -> McpCapability {
72        self.capability
73    }
74
75    /// Refuse `tool_name` when the session is below the level it needs.
76    fn check_tool_capability(&self, tool_name: &str) -> Result<(), String> {
77        let required = crate::mcp::capability::tool_capability(tool_name);
78        if self.capability.permits(required) {
79            Ok(())
80        } else {
81            Err(crate::mcp::capability::refusal(
82                &format!("tool `{tool_name}`"),
83                self.capability,
84                required,
85            ))
86        }
87    }
88
89    /// Run the MCP server reading from stdin and writing to stdout.
90    ///
91    /// This blocks until stdin is closed (EOF). Diagnostic messages are
92    /// written to stderr so they do not interfere with the protocol.
93    pub fn run_stdio(&mut self) {
94        let stdin = io::stdin();
95        let stdout = io::stdout();
96        let mut reader = io::BufReader::new(stdin.lock());
97        let mut writer = io::BufWriter::new(stdout.lock());
98
99        tracing::info!(target: "reddb::mcp", "server started, waiting for messages on stdin");
100
101        loop {
102            let payload = match protocol::read_payload(&mut reader) {
103                Ok(Some(p)) => p,
104                Ok(None) => {
105                    tracing::info!(target: "reddb::mcp", "stdin closed, shutting down");
106                    break;
107                }
108                Err(e) => {
109                    tracing::error!(target: "reddb::mcp", err = %e, "read error");
110                    continue;
111                }
112            };
113
114            let request: JsonValue = match json_from_str(&payload) {
115                Ok(v) => v,
116                Err(e) => {
117                    tracing::warn!(target: "reddb::mcp", err = %e, "invalid JSON");
118                    let msg = protocol::build_error_message(None, -32700, "parse error");
119                    let _ = protocol::write_message(&mut writer, &msg);
120                    continue;
121                }
122            };
123
124            let response = self.handle_message(&request);
125            if let Some(resp) = response {
126                if let Err(e) = protocol::write_message(&mut writer, &resp) {
127                    tracing::error!(target: "reddb::mcp", err = %e, "write error");
128                    break;
129                }
130            }
131        }
132    }
133
134    /// Route a JSON-RPC message to the appropriate handler.
135    fn handle_message(&mut self, msg: &JsonValue) -> Option<String> {
136        let method = msg.get("method").and_then(|v| v.as_str())?;
137        let id = msg.get("id");
138
139        match method {
140            "initialize" => Some(self.handle_initialize(id)),
141            "initialized" | "notifications/initialized" => {
142                // Notification -- no response required.
143                None
144            }
145            "tools/list" => Some(self.handle_tools_list(id)),
146            "tools/call" => Some(self.handle_tools_call(id, msg.get("params"))),
147            "resources/list" => Some(self.handle_resources_list(id)),
148            "resources/read" => Some(self.handle_resources_read(id, msg.get("params"))),
149            "ping" => {
150                let mut result = Map::new();
151                result.insert("status".to_string(), JsonValue::String("ok".to_string()));
152                Some(protocol::build_result_message(
153                    id,
154                    JsonValue::Object(result),
155                ))
156            }
157            _ => Some(protocol::build_error_message(
158                id,
159                -32601,
160                &format!("unknown method: {}", method),
161            )),
162        }
163    }
164
165    // ------------------------------------------------------------------
166    // MCP lifecycle
167    // ------------------------------------------------------------------
168
169    fn handle_initialize(&mut self, id: Option<&JsonValue>) -> String {
170        self.initialized = true;
171
172        let mut capabilities = Map::new();
173        {
174            let mut tools_cap = Map::new();
175            tools_cap.insert("listChanged".to_string(), JsonValue::Bool(false));
176            capabilities.insert("tools".to_string(), JsonValue::Object(tools_cap));
177        }
178        {
179            // Read-only knowledge resources (ADR 0061). No subscriptions and
180            // the set is static, so both change-notification flags are false.
181            let mut resources_cap = Map::new();
182            resources_cap.insert("subscribe".to_string(), JsonValue::Bool(false));
183            resources_cap.insert("listChanged".to_string(), JsonValue::Bool(false));
184            capabilities.insert("resources".to_string(), JsonValue::Object(resources_cap));
185        }
186
187        let mut server_info = Map::new();
188        server_info.insert(
189            "name".to_string(),
190            JsonValue::String("reddb-mcp".to_string()),
191        );
192        server_info.insert(
193            "version".to_string(),
194            JsonValue::String(env!("CARGO_PKG_VERSION").to_string()),
195        );
196
197        let mut result = Map::new();
198        result.insert(
199            "protocolVersion".to_string(),
200            JsonValue::String("2024-11-05".to_string()),
201        );
202        result.insert("capabilities".to_string(), JsonValue::Object(capabilities));
203        result.insert("serverInfo".to_string(), JsonValue::Object(server_info));
204
205        protocol::build_result_message(id, JsonValue::Object(result))
206    }
207
208    // ------------------------------------------------------------------
209    // tools/list
210    // ------------------------------------------------------------------
211
212    fn handle_tools_list(&self, id: Option<&JsonValue>) -> String {
213        let defs = tools::all_tools();
214        let mut tools_json: Vec<JsonValue> = defs
215            .into_iter()
216            .map(|def| {
217                let mut obj = Map::new();
218                obj.insert("name".to_string(), JsonValue::String(def.name.to_string()));
219                obj.insert(
220                    "description".to_string(),
221                    JsonValue::String(def.descriptor_description()),
222                );
223                obj.insert("inputSchema".to_string(), def.input_schema);
224                JsonValue::Object(obj)
225            })
226            .collect();
227        tools_json.push(tools::ask_descriptor());
228
229        let mut result = Map::new();
230        result.insert("tools".to_string(), JsonValue::Array(tools_json));
231        protocol::build_result_message(id, JsonValue::Object(result))
232    }
233
234    // ------------------------------------------------------------------
235    // resources/list + resources/read (knowledge surface, ADR 0061)
236    // ------------------------------------------------------------------
237
238    fn handle_resources_list(&self, id: Option<&JsonValue>) -> String {
239        let resources: Vec<JsonValue> = tools::knowledge_resources()
240            .iter()
241            .map(|res| {
242                let mut obj = Map::new();
243                obj.insert("uri".to_string(), JsonValue::String(res.uri.to_string()));
244                obj.insert("name".to_string(), JsonValue::String(res.title.to_string()));
245                obj.insert(
246                    "description".to_string(),
247                    JsonValue::String(res.description.to_string()),
248                );
249                obj.insert(
250                    "mimeType".to_string(),
251                    JsonValue::String(res.mime_type.to_string()),
252                );
253                JsonValue::Object(obj)
254            })
255            .collect();
256
257        let mut result = Map::new();
258        result.insert("resources".to_string(), JsonValue::Array(resources));
259        protocol::build_result_message(id, JsonValue::Object(result))
260    }
261
262    fn handle_resources_read(&self, id: Option<&JsonValue>, params: Option<&JsonValue>) -> String {
263        let uri = params.and_then(|p| p.get("uri")).and_then(|v| v.as_str());
264        let uri = match uri {
265            Some(u) => u,
266            None => return protocol::build_error_message(id, -32602, "missing resource uri"),
267        };
268
269        let resources = tools::knowledge_resources();
270        let resource = match resources.iter().find(|res| res.uri == uri) {
271            Some(res) => res,
272            None => {
273                return protocol::build_error_message(
274                    id,
275                    -32602,
276                    &format!("unknown resource: {uri}"),
277                );
278            }
279        };
280
281        let mut contents = Map::new();
282        contents.insert(
283            "uri".to_string(),
284            JsonValue::String(resource.uri.to_string()),
285        );
286        contents.insert(
287            "mimeType".to_string(),
288            JsonValue::String(resource.mime_type.to_string()),
289        );
290        contents.insert("text".to_string(), JsonValue::String((resource.body)()));
291
292        let mut result = Map::new();
293        result.insert(
294            "contents".to_string(),
295            JsonValue::Array(vec![JsonValue::Object(contents)]),
296        );
297        protocol::build_result_message(id, JsonValue::Object(result))
298    }
299
300    // ------------------------------------------------------------------
301    // tools/call dispatcher
302    // ------------------------------------------------------------------
303
304    fn handle_tools_call(&self, id: Option<&JsonValue>, params: Option<&JsonValue>) -> String {
305        let name = params.and_then(|p| p.get("name")).and_then(|v| v.as_str());
306        let name = match name {
307            Some(n) => n,
308            None => {
309                return protocol::build_error_message(id, -32602, "missing tool name");
310            }
311        };
312
313        let empty = JsonValue::Object(Map::new());
314        let args = params.and_then(|p| p.get("arguments")).unwrap_or(&empty);
315
316        let result = tools::authorize_tool(name, tools::McpIdentityPosture::EmbeddedImplicitAdmin)
317            .and_then(|_| self.check_tool_capability(name))
318            .and_then(|_| match name {
319                agent_tools::QUERY_TOOL => self.tool_query(args),
320                "reddb_collections" => self.tool_collections(),
321                agent_tools::CATALOG_TOOL => self.tool_catalog(),
322                agent_tools::DESCRIBE_COLLECTION_TOOL => self.tool_describe_collection(args),
323                agent_tools::FIND_FIELD_TOOL => self.tool_find_field(args),
324                "reddb_insert_row" => self.tool_insert_row(args),
325                "reddb_insert_node" => self.tool_insert_node(args),
326                "reddb_insert_edge" => self.tool_insert_edge(args),
327                "reddb_insert_vector" => self.tool_insert_vector(args),
328                "reddb_insert_document" => self.tool_insert_document(args),
329                "reddb_kv_get" => self.tool_kv_get(args),
330                "reddb_kv_set" => self.tool_kv_set(args),
331                "reddb_kv_invalidate_tags" => self.tool_kv_invalidate_tags(args),
332                "reddb_config_get" => self.tool_config_get(args),
333                "reddb_config_put" => self.tool_config_put(args),
334                "reddb_config_resolve" => self.tool_config_resolve(args),
335                "reddb_vault_get" => self.tool_vault_get(args),
336                "reddb_vault_put" => self.tool_vault_put(args),
337                "reddb_vault_reveal" | "reddb_vault_unseal" => self.tool_vault_unseal(args),
338                "reddb_delete" => self.tool_delete(args),
339                "reddb_search_vector" => self.tool_search_vector(args),
340                "reddb_search_text" => self.tool_search_text(args),
341                "reddb_health" => self.tool_health(),
342                "reddb_graph_traverse" => self.tool_graph_traverse(args),
343                "reddb_graph_shortest_path" => self.tool_graph_shortest_path(args),
344                "reddb_update" => self.tool_update(args),
345                "reddb_scan" => self.tool_scan(args),
346                "reddb_graph_centrality" => self.tool_graph_centrality(args),
347                "reddb_graph_community" => self.tool_graph_community(args),
348                "reddb_graph_components" => self.tool_graph_components(args),
349                "reddb_graph_cycles" => self.tool_graph_cycles(args),
350                "reddb_graph_clustering" => self.tool_graph_clustering(args),
351                "reddb_create_collection" => self.tool_create_collection(args),
352                "reddb_drop_collection" => self.tool_drop_collection(args),
353                "reddb_rql_validate" => self.tool_rql_validate(args),
354                "reddb_rql_explain" => self.tool_rql_explain(args),
355                "reddb_type_of" => self.tool_type_of(args),
356                "reddb_explain_connection" => self.tool_explain_connection(args),
357                "reddb_auth_bootstrap" => self.tool_auth_bootstrap(args),
358                "reddb_auth_create_user" => self.tool_auth_create_user(args),
359                "reddb_auth_login" => self.tool_auth_login(args),
360                "reddb_auth_create_api_key" => self.tool_auth_create_api_key(args),
361                "reddb_auth_list_users" => self.tool_auth_list_users(),
362                crate::runtime::ai::mcp_ask_tool::TOOL_NAME => self.tool_ask(args),
363                _ => Err(format!("unknown tool: {name}")),
364            });
365
366        match result {
367            Ok(text) => {
368                let mut content = Map::new();
369                content.insert("type".to_string(), JsonValue::String("text".to_string()));
370                content.insert("text".to_string(), JsonValue::String(text));
371
372                let mut result_obj = Map::new();
373                result_obj.insert(
374                    "content".to_string(),
375                    JsonValue::Array(vec![JsonValue::Object(content)]),
376                );
377                protocol::build_result_message(id, JsonValue::Object(result_obj))
378            }
379            Err(err) => {
380                let mut content = Map::new();
381                content.insert("type".to_string(), JsonValue::String("text".to_string()));
382                content.insert("text".to_string(), JsonValue::String(err.clone()));
383
384                let mut result_obj = Map::new();
385                result_obj.insert(
386                    "content".to_string(),
387                    JsonValue::Array(vec![JsonValue::Object(content)]),
388                );
389                result_obj.insert("isError".to_string(), JsonValue::Bool(true));
390                protocol::build_result_message(id, JsonValue::Object(result_obj))
391            }
392        }
393    }
394
395    // ------------------------------------------------------------------
396    // Tool implementations
397    // ------------------------------------------------------------------
398
399    fn tool_query(&self, args: &JsonValue) -> Result<String, String> {
400        let sql = args
401            .get("sql")
402            .and_then(|v| v.as_str())
403            .ok_or("missing required field 'sql'")?;
404
405        // `reddb_query` is a read-only *tool* that accepts arbitrary SQL, so
406        // the statement decides what it needs. Without this a read-only
407        // session could send `DROP COLLECTION` through the one tool it was
408        // allowed to call.
409        let required = crate::mcp::capability::statement_capability(sql);
410        if !self.capability.permits(required) {
411            return Err(crate::mcp::capability::refusal(
412                "this statement",
413                self.capability,
414                required,
415            ));
416        }
417
418        self.execute_common_tool(agent_tools::QUERY_TOOL, args)
419    }
420
421    fn tool_ask(&self, args: &JsonValue) -> Result<String, String> {
422        let invocation =
423            crate::runtime::ai::mcp_ask_tool::parse(args).map_err(format_mcp_ask_parse_error)?;
424        let ask = reddb_rql::ast::AskQuery {
425            explain: false,
426            question: invocation.question,
427            question_param: None,
428            provider: invocation.using,
429            model: invocation.model,
430            depth: invocation.depth.map(|v| v as usize),
431            limit: invocation.limit.map(|v| v as usize),
432            min_score: invocation.min_score.map(|v| v as f32),
433            collection: None,
434            temperature: invocation.temperature.map(|v| v as f32),
435            seed: invocation.seed,
436            strict: invocation.strict.unwrap_or(true),
437            stream: false,
438            cache: if matches!(invocation.nocache, Some(true)) {
439                reddb_rql::ast::AskCacheClause::NoCache
440            } else if let Some(ttl) = invocation.cache_ttl {
441                reddb_rql::ast::AskCacheClause::CacheTtl(ttl)
442            } else {
443                reddb_rql::ast::AskCacheClause::Default
444            },
445            plan_only: false,
446            steps: None,
447        };
448        let result = self
449            .runtime
450            .execute_ask("ASK <mcp>", &ask)
451            .map_err(|e| format!("{}", e))?;
452        let json = crate::presentation::query_result::tagged_summary(&result);
453        json_to_string(&json).map_err(|e| format!("serialization error: {}", e))
454    }
455
456    fn tool_collections(&self) -> Result<String, String> {
457        let collections = self.runtime.db().collections();
458        let json = JsonValue::Array(collections.into_iter().map(JsonValue::String).collect());
459        json_to_string(&json).map_err(|error| format!("serialization error: {error}"))
460    }
461
462    fn tool_catalog(&self) -> Result<String, String> {
463        self.execute_common_tool(agent_tools::CATALOG_TOOL, &JsonValue::Object(Map::new()))
464    }
465
466    fn tool_describe_collection(&self, args: &JsonValue) -> Result<String, String> {
467        self.execute_common_tool(agent_tools::DESCRIBE_COLLECTION_TOOL, args)
468    }
469
470    fn tool_find_field(&self, args: &JsonValue) -> Result<String, String> {
471        self.execute_common_tool(agent_tools::FIND_FIELD_TOOL, args)
472    }
473
474    fn execute_common_tool(&self, name: &str, args: &JsonValue) -> Result<String, String> {
475        let call = agent_tools::parse_call(name, args, ToolParseMode::Direct)
476            .map_err(|error| error.to_string())?;
477        let scope = self.runtime.ai_scope();
478        let result = RedToolExecutor::new(&self.runtime, &scope, ToolExecutionProfile::Direct)
479            .execute(&call)
480            .map_err(|error| error.to_string())?;
481        let json = runtime_query_json(&result, &None, &None);
482        json_to_string(&json).map_err(|error| format!("serialization error: {error}"))
483    }
484
485    fn tool_insert_row(&self, args: &JsonValue) -> Result<String, String> {
486        let collection = args
487            .get("collection")
488            .and_then(|v| v.as_str())
489            .ok_or("missing required field 'collection'")?;
490        let data = args
491            .get("data")
492            .and_then(|v| v.as_object())
493            .ok_or("missing required field 'data' (must be an object)")?;
494
495        let mut fields = Vec::new();
496        for (key, value) in data {
497            let sv = crate::application::entity::json_to_storage_value(value)
498                .map_err(|e| format!("{}", e))?;
499            fields.push((key.clone(), sv));
500        }
501
502        let metadata = parse_metadata_arg(args)?;
503
504        let uc = EntityUseCases::new(&self.runtime);
505        let output = uc
506            .create_row(CreateRowInput {
507                collection: collection.to_string(),
508                fields,
509                metadata,
510                node_links: vec![],
511                vector_links: vec![],
512            })
513            .map_err(|e| format!("{}", e))?;
514
515        let json = created_entity_output_json(&output);
516        json_to_string(&json).map_err(|e| format!("serialization error: {}", e))
517    }
518
519    fn tool_insert_node(&self, args: &JsonValue) -> Result<String, String> {
520        let collection = args
521            .get("collection")
522            .and_then(|v| v.as_str())
523            .ok_or("missing required field 'collection'")?;
524        let label = args
525            .get("label")
526            .and_then(|v| v.as_str())
527            .ok_or("missing required field 'label'")?;
528        let node_type = args
529            .get("node_type")
530            .and_then(|v| v.as_str())
531            .map(String::from);
532
533        let mut properties = Vec::new();
534        if let Some(props) = args.get("properties").and_then(|v| v.as_object()) {
535            for (key, value) in props {
536                let sv = crate::application::entity::json_to_storage_value(value)
537                    .map_err(|e| format!("{}", e))?;
538                properties.push((key.clone(), sv));
539            }
540        }
541
542        let metadata = parse_metadata_arg(args)?;
543
544        let uc = EntityUseCases::new(&self.runtime);
545        let output = uc
546            .create_node(CreateNodeInput {
547                collection: collection.to_string(),
548                label: label.to_string(),
549                node_type,
550                properties,
551                metadata,
552                embeddings: vec![],
553                table_links: vec![],
554                node_links: vec![],
555            })
556            .map_err(|e| format!("{}", e))?;
557
558        let json = created_entity_output_json(&output);
559        json_to_string(&json).map_err(|e| format!("serialization error: {}", e))
560    }
561
562    fn tool_insert_edge(&self, args: &JsonValue) -> Result<String, String> {
563        let collection = args
564            .get("collection")
565            .and_then(|v| v.as_str())
566            .ok_or("missing required field 'collection'")?;
567        let label = args
568            .get("label")
569            .and_then(|v| v.as_str())
570            .ok_or("missing required field 'label'")?;
571        let from_id = args
572            .get("from")
573            .and_then(|v| v.as_u64())
574            .ok_or("missing required field 'from' (integer)")?;
575        let to_id = args
576            .get("to")
577            .and_then(|v| v.as_u64())
578            .ok_or("missing required field 'to' (integer)")?;
579        let weight = args
580            .get("weight")
581            .and_then(|v| v.as_f64())
582            .map(|w| w as f32);
583
584        let mut properties = Vec::new();
585        if let Some(props) = args.get("properties").and_then(|v| v.as_object()) {
586            for (key, value) in props {
587                let sv = crate::application::entity::json_to_storage_value(value)
588                    .map_err(|e| format!("{}", e))?;
589                properties.push((key.clone(), sv));
590            }
591        }
592
593        let metadata = parse_metadata_arg(args)?;
594
595        let uc = EntityUseCases::new(&self.runtime);
596        let output = uc
597            .create_edge(CreateEdgeInput {
598                collection: collection.to_string(),
599                label: label.to_string(),
600                from: EntityId::new(from_id),
601                to: EntityId::new(to_id),
602                weight,
603                properties,
604                metadata,
605            })
606            .map_err(|e| format!("{}", e))?;
607
608        let json = created_entity_output_json(&output);
609        json_to_string(&json).map_err(|e| format!("serialization error: {}", e))
610    }
611
612    fn tool_insert_vector(&self, args: &JsonValue) -> Result<String, String> {
613        let collection = args
614            .get("collection")
615            .and_then(|v| v.as_str())
616            .ok_or("missing required field 'collection'")?;
617        let dense_arr = args
618            .get("dense")
619            .and_then(|v| v.as_array())
620            .ok_or("missing required field 'dense' (array of numbers)")?;
621
622        let mut dense = Vec::with_capacity(dense_arr.len());
623        for v in dense_arr {
624            dense.push(
625                v.as_f64()
626                    .ok_or("'dense' array must contain only numbers")? as f32,
627            );
628        }
629        if dense.is_empty() {
630            return Err("'dense' vector cannot be empty".to_string());
631        }
632
633        let content = args
634            .get("content")
635            .and_then(|v| v.as_str())
636            .map(String::from);
637        let metadata = parse_metadata_arg(args)?;
638
639        let uc = EntityUseCases::new(&self.runtime);
640        let output = uc
641            .create_vector(CreateVectorInput {
642                collection: collection.to_string(),
643                dense,
644                content,
645                metadata,
646                link_row: None,
647                link_node: None,
648            })
649            .map_err(|e| format!("{}", e))?;
650
651        let json = created_entity_output_json(&output);
652        json_to_string(&json).map_err(|e| format!("serialization error: {}", e))
653    }
654
655    fn tool_insert_document(&self, args: &JsonValue) -> Result<String, String> {
656        let collection = args
657            .get("collection")
658            .and_then(|v| v.as_str())
659            .ok_or("missing required field 'collection'")?;
660        let body = args.get("body").ok_or("missing required field 'body'")?;
661
662        let metadata = parse_metadata_arg(args)?;
663
664        let uc = EntityUseCases::new(&self.runtime);
665        let output = uc
666            .create_document(CreateDocumentInput {
667                collection: collection.to_string(),
668                body: body.clone(),
669                metadata,
670                node_links: vec![],
671                vector_links: vec![],
672            })
673            .map_err(|e| format!("{}", e))?;
674
675        let json = created_entity_output_json(&output);
676        json_to_string(&json).map_err(|e| format!("serialization error: {}", e))
677    }
678
679    fn tool_kv_get(&self, args: &JsonValue) -> Result<String, String> {
680        let collection = args
681            .get("collection")
682            .and_then(|v| v.as_str())
683            .ok_or("missing required field 'collection'")?;
684        let key = args
685            .get("key")
686            .and_then(|v| v.as_str())
687            .ok_or("missing required field 'key'")?;
688
689        let uc = EntityUseCases::new(&self.runtime);
690        match uc.get_kv(collection, key).map_err(|e| format!("{}", e))? {
691            Some((value, entity_id)) => {
692                let mut obj = Map::new();
693                obj.insert("found".to_string(), JsonValue::Bool(true));
694                obj.insert("key".to_string(), JsonValue::String(key.to_string()));
695                obj.insert("value".to_string(), storage_value_to_json(&value));
696                obj.insert("rid".to_string(), JsonValue::Number(entity_id.raw() as f64));
697                obj.insert("kind".to_string(), JsonValue::String("kv".to_string()));
698                json_to_string(&JsonValue::Object(obj))
699                    .map_err(|e| format!("serialization error: {}", e))
700            }
701            None => {
702                let mut obj = Map::new();
703                obj.insert("found".to_string(), JsonValue::Bool(false));
704                obj.insert("key".to_string(), JsonValue::String(key.to_string()));
705                json_to_string(&JsonValue::Object(obj))
706                    .map_err(|e| format!("serialization error: {}", e))
707            }
708        }
709    }
710
711    fn tool_kv_set(&self, args: &JsonValue) -> Result<String, String> {
712        let collection = args
713            .get("collection")
714            .and_then(|v| v.as_str())
715            .ok_or("missing required field 'collection'")?;
716        let key = args
717            .get("key")
718            .and_then(|v| v.as_str())
719            .ok_or("missing required field 'key'")?;
720        let value_arg = args.get("value").ok_or("missing required field 'value'")?;
721
722        let sv = crate::application::entity::json_to_storage_value(value_arg)
723            .map_err(|e| format!("{}", e))?;
724
725        let metadata = parse_metadata_arg(args)?;
726
727        let tags = parse_string_array_arg(args, "tags")?;
728        let ops = crate::runtime::impl_kv::KvAtomicOps::new(&self.runtime);
729        let (_, id) = ops
730            .set_with_tags_and_metadata(collection, key, sv, None, &tags, false, metadata)
731            .map_err(|e| format!("{}", e))?;
732
733        let mut obj = Map::new();
734        obj.insert("ok".to_string(), JsonValue::Bool(true));
735        obj.insert("rid".to_string(), JsonValue::Number(id.raw() as f64));
736        obj.insert("kind".to_string(), JsonValue::String("kv".to_string()));
737        obj.insert(
738            "tags".to_string(),
739            JsonValue::Array(tags.into_iter().map(JsonValue::String).collect()),
740        );
741        json_to_string(&JsonValue::Object(obj)).map_err(|e| format!("serialization error: {}", e))
742    }
743
744    fn tool_kv_invalidate_tags(&self, args: &JsonValue) -> Result<String, String> {
745        let collection = args
746            .get("collection")
747            .and_then(|v| v.as_str())
748            .ok_or("missing required field 'collection'")?;
749        let tags = parse_string_array_arg(args, "tags")?;
750        if tags.is_empty() {
751            return Err("missing required field 'tags'".to_string());
752        }
753        let ops = crate::runtime::impl_kv::KvAtomicOps::new(&self.runtime);
754        let count = ops
755            .invalidate_tags(collection, &tags)
756            .map_err(|e| format!("{}", e))?;
757
758        let mut obj = Map::new();
759        obj.insert("ok".to_string(), JsonValue::Bool(true));
760        obj.insert("invalidated".to_string(), JsonValue::Number(count as f64));
761        obj.insert(
762            "tags".to_string(),
763            JsonValue::Array(tags.into_iter().map(JsonValue::String).collect()),
764        );
765        json_to_string(&JsonValue::Object(obj)).map_err(|e| format!("serialization error: {}", e))
766    }
767
768    fn tool_config_get(&self, args: &JsonValue) -> Result<String, String> {
769        let collection = mcp_keyed_ident(get_str_field(args, "collection")?)?;
770        let key = mcp_keyed_ident(get_str_field(args, "key")?)?;
771        self.tool_keyed_query(format!("GET CONFIG {collection} {key}"))
772    }
773
774    fn tool_config_put(&self, args: &JsonValue) -> Result<String, String> {
775        reject_mcp_volatile_options(args, "CONFIG")?;
776        let collection = mcp_keyed_ident(get_str_field(args, "collection")?)?;
777        let key = mcp_keyed_ident(get_str_field(args, "key")?)?;
778        let tags = parse_string_array_arg(args, "tags")?;
779        let literal = if let Some(secret_ref) = args.get("secret_ref") {
780            let object = secret_ref
781                .as_object()
782                .ok_or("field 'secret_ref' must be an object")?;
783            let ref_collection = object
784                .get("collection")
785                .and_then(|v| v.as_str())
786                .ok_or_else(|| "secret_ref.collection is required".to_string())
787                .and_then(mcp_keyed_ident)?;
788            let ref_key = object
789                .get("key")
790                .and_then(|v| v.as_str())
791                .ok_or_else(|| "secret_ref.key is required".to_string())
792                .and_then(mcp_keyed_ident)?;
793            format!("SECRET_REF(vault, {ref_collection}.{ref_key})")
794        } else {
795            mcp_value_literal(args.get("value").ok_or("missing required field 'value'")?)?
796        };
797        let mut sql = format!("PUT CONFIG {collection} {key} = {literal}");
798        append_mcp_tags_clause(&mut sql, &tags);
799        self.tool_keyed_query(sql)
800    }
801
802    fn tool_config_resolve(&self, args: &JsonValue) -> Result<String, String> {
803        let collection = mcp_keyed_ident(get_str_field(args, "collection")?)?;
804        let key = mcp_keyed_ident(get_str_field(args, "key")?)?;
805        self.tool_keyed_query(format!("RESOLVE CONFIG {collection} {key}"))
806    }
807
808    fn tool_vault_get(&self, args: &JsonValue) -> Result<String, String> {
809        let collection = mcp_keyed_ident(get_str_field(args, "collection")?)?;
810        let key = mcp_keyed_ident(get_str_field(args, "key")?)?;
811        self.tool_keyed_query(format!("VAULT GET {collection}.{key}"))
812    }
813
814    fn tool_vault_put(&self, args: &JsonValue) -> Result<String, String> {
815        reject_mcp_volatile_options(args, "VAULT")?;
816        let collection = mcp_keyed_ident(get_str_field(args, "collection")?)?;
817        let key = mcp_keyed_ident(get_str_field(args, "key")?)?;
818        let value = mcp_value_literal(args.get("value").ok_or("missing required field 'value'")?)?;
819        let tags = parse_string_array_arg(args, "tags")?;
820        let mut sql = format!("VAULT PUT {collection}.{key} = {value}");
821        append_mcp_tags_clause(&mut sql, &tags);
822        self.tool_keyed_query(sql)
823    }
824
825    fn tool_vault_unseal(&self, args: &JsonValue) -> Result<String, String> {
826        let collection = mcp_keyed_ident(get_str_field(args, "collection")?)?;
827        let key = mcp_keyed_ident(get_str_field(args, "key")?)?;
828        self.tool_keyed_query(format!("VAULT REVEAL {collection}.{key}"))
829    }
830
831    fn tool_keyed_query(&self, sql: String) -> Result<String, String> {
832        let uc = &self.runtime;
833        let result = uc.execute_query(&(sql)).map_err(|e| format!("{}", e))?;
834        let json = runtime_query_json(&result, &None, &None);
835        json_to_string(&json).map_err(|e| format!("serialization error: {}", e))
836    }
837
838    fn tool_delete(&self, args: &JsonValue) -> Result<String, String> {
839        let collection = args
840            .get("collection")
841            .and_then(|v| v.as_str())
842            .ok_or("missing required field 'collection'")?;
843        let id = args
844            .get("id")
845            .and_then(|v| v.as_u64())
846            .ok_or("missing required field 'id' (integer)")?;
847
848        let uc = EntityUseCases::new(&self.runtime);
849        let output = uc
850            .delete(DeleteEntityInput {
851                collection: collection.to_string(),
852                id: EntityId::new(id),
853            })
854            .map_err(|e| format!("{}", e))?;
855
856        let mut obj = Map::new();
857        obj.insert("deleted".to_string(), JsonValue::Bool(output.deleted));
858        obj.insert("id".to_string(), JsonValue::Number(output.id.raw() as f64));
859        json_to_string(&JsonValue::Object(obj)).map_err(|e| format!("serialization error: {}", e))
860    }
861
862    fn tool_search_vector(&self, args: &JsonValue) -> Result<String, String> {
863        let collection = args
864            .get("collection")
865            .and_then(|v| v.as_str())
866            .ok_or("missing required field 'collection'")?;
867        let vector_arr = args
868            .get("vector")
869            .and_then(|v| v.as_array())
870            .ok_or("missing required field 'vector' (array of numbers)")?;
871
872        let mut vector = Vec::with_capacity(vector_arr.len());
873        for v in vector_arr {
874            vector.push(
875                v.as_f64()
876                    .ok_or("'vector' array must contain only numbers")? as f32,
877            );
878        }
879        let k = args
880            .get("k")
881            .and_then(|v| v.as_u64())
882            .map(|v| v as usize)
883            .unwrap_or(10);
884        let min_score = args
885            .get("min_score")
886            .and_then(|v| v.as_f64())
887            .map(|v| v as f32)
888            .unwrap_or(0.0);
889
890        let uc = &self.runtime;
891        let results = uc
892            .search_similar_input(SearchSimilarInput {
893                collection: collection.to_string(),
894                vector,
895                k,
896                min_score,
897                text: None,
898                provider: None,
899            })
900            .map_err(|e| format!("{}", e))?;
901
902        let items: Vec<JsonValue> = results
903            .iter()
904            .map(|r| {
905                let mut obj = Map::new();
906                obj.insert(
907                    "rid".to_string(),
908                    JsonValue::Number(r.entity_id.raw() as f64),
909                );
910                obj.insert("kind".to_string(), JsonValue::String("vector".to_string()));
911                obj.insert("score".to_string(), JsonValue::Number(r.score as f64));
912                obj.insert("distance".to_string(), JsonValue::Number(r.distance as f64));
913                JsonValue::Object(obj)
914            })
915            .collect();
916
917        let mut obj = Map::new();
918        obj.insert("count".to_string(), JsonValue::Number(items.len() as f64));
919        obj.insert("results".to_string(), JsonValue::Array(items));
920        json_to_string(&JsonValue::Object(obj)).map_err(|e| format!("serialization error: {}", e))
921    }
922
923    fn tool_search_text(&self, args: &JsonValue) -> Result<String, String> {
924        let query = args
925            .get("query")
926            .and_then(|v| v.as_str())
927            .ok_or("missing required field 'query'")?;
928
929        let collections = args
930            .get("collections")
931            .and_then(|v| v.as_array())
932            .map(|arr| {
933                arr.iter()
934                    .filter_map(|v| v.as_str().map(String::from))
935                    .collect::<Vec<_>>()
936            });
937        let limit = args
938            .get("limit")
939            .and_then(|v| v.as_u64())
940            .map(|v| v as usize);
941        let fuzzy = args.get("fuzzy").and_then(|v| v.as_bool()).unwrap_or(false);
942
943        let uc = &self.runtime;
944        let result = uc
945            .search_text_input(SearchTextInput {
946                query: query.to_string(),
947                collections,
948                entity_types: None,
949                capabilities: None,
950                fields: None,
951                limit,
952                fuzzy,
953            })
954            .map_err(|e| format!("{}", e))?;
955
956        let items: Vec<JsonValue> = result
957            .matches
958            .iter()
959            .map(|m| {
960                let mut obj = Map::new();
961                obj.insert(
962                    "rid".to_string(),
963                    JsonValue::Number(m.entity.id.raw() as f64),
964                );
965                obj.insert(
966                    "kind".to_string(),
967                    JsonValue::String(m.entity.kind.storage_type().to_string()),
968                );
969                obj.insert("score".to_string(), JsonValue::Number(m.score as f64));
970                JsonValue::Object(obj)
971            })
972            .collect();
973
974        let mut obj = Map::new();
975        obj.insert("count".to_string(), JsonValue::Number(items.len() as f64));
976        obj.insert("results".to_string(), JsonValue::Array(items));
977        json_to_string(&JsonValue::Object(obj)).map_err(|e| format!("serialization error: {}", e))
978    }
979
980    fn tool_health(&self) -> Result<String, String> {
981        let uc = &self.runtime;
982        let stats = uc.stats();
983        let json = runtime_stats_json(&stats);
984        json_to_string(&json).map_err(|e| format!("serialization error: {}", e))
985    }
986
987    fn tool_graph_traverse(&self, args: &JsonValue) -> Result<String, String> {
988        let source = args
989            .get("source")
990            .and_then(|v| v.as_str())
991            .ok_or("missing required field 'source'")?;
992        let direction = parse_direction(args.get("direction").and_then(|v| v.as_str()));
993        let max_depth = args
994            .get("max_depth")
995            .and_then(|v| v.as_u64())
996            .map(|v| v as usize)
997            .unwrap_or(3);
998        let strategy = match args.get("strategy").and_then(|v| v.as_str()) {
999            Some("dfs") => RuntimeGraphTraversalStrategy::Dfs,
1000            _ => RuntimeGraphTraversalStrategy::Bfs,
1001        };
1002
1003        let uc = GraphUseCases::new(&self.runtime);
1004        let result = uc
1005            .traverse(GraphTraversalInput {
1006                source: source.to_string(),
1007                direction,
1008                max_depth,
1009                strategy,
1010                edge_labels: None,
1011                projection: None,
1012            })
1013            .map_err(|e| format!("{}", e))?;
1014
1015        let visits: Vec<JsonValue> = result
1016            .visits
1017            .iter()
1018            .map(|v| {
1019                let mut obj = Map::new();
1020                obj.insert("depth".to_string(), JsonValue::Number(v.depth as f64));
1021                obj.insert("node_id".to_string(), JsonValue::String(v.node.id.clone()));
1022                obj.insert("label".to_string(), JsonValue::String(v.node.label.clone()));
1023                obj.insert(
1024                    "node_type".to_string(),
1025                    JsonValue::String(v.node.node_type.clone()),
1026                );
1027                JsonValue::Object(obj)
1028            })
1029            .collect();
1030
1031        let edges: Vec<JsonValue> = result
1032            .edges
1033            .iter()
1034            .map(|e| {
1035                let mut obj = Map::new();
1036                obj.insert("source".to_string(), JsonValue::String(e.source.clone()));
1037                obj.insert("target".to_string(), JsonValue::String(e.target.clone()));
1038                obj.insert(
1039                    "edge_type".to_string(),
1040                    JsonValue::String(e.edge_type.clone()),
1041                );
1042                obj.insert("weight".to_string(), JsonValue::Number(e.weight as f64));
1043                JsonValue::Object(obj)
1044            })
1045            .collect();
1046
1047        let mut obj = Map::new();
1048        obj.insert(
1049            "source".to_string(),
1050            JsonValue::String(result.source.clone()),
1051        );
1052        obj.insert(
1053            "visit_count".to_string(),
1054            JsonValue::Number(visits.len() as f64),
1055        );
1056        obj.insert("visits".to_string(), JsonValue::Array(visits));
1057        obj.insert("edges".to_string(), JsonValue::Array(edges));
1058        json_to_string(&JsonValue::Object(obj)).map_err(|e| format!("serialization error: {}", e))
1059    }
1060
1061    fn tool_graph_shortest_path(&self, args: &JsonValue) -> Result<String, String> {
1062        let source = args
1063            .get("source")
1064            .and_then(|v| v.as_str())
1065            .ok_or("missing required field 'source'")?;
1066        let target = args
1067            .get("target")
1068            .and_then(|v| v.as_str())
1069            .ok_or("missing required field 'target'")?;
1070        let direction = parse_direction(args.get("direction").and_then(|v| v.as_str()));
1071        let algorithm = match args.get("algorithm").and_then(|v| v.as_str()) {
1072            Some("astar") | Some("a*") => RuntimeGraphPathAlgorithm::AStar,
1073            Some("bellman_ford") | Some("bellmanford") => RuntimeGraphPathAlgorithm::BellmanFord,
1074            Some("dijkstra") => RuntimeGraphPathAlgorithm::Dijkstra,
1075            _ => RuntimeGraphPathAlgorithm::Bfs,
1076        };
1077
1078        let uc = GraphUseCases::new(&self.runtime);
1079        let result = uc
1080            .shortest_path(GraphShortestPathInput {
1081                source: source.to_string(),
1082                target: target.to_string(),
1083                direction,
1084                algorithm,
1085                edge_labels: None,
1086                projection: None,
1087            })
1088            .map_err(|e| format!("{}", e))?;
1089
1090        let mut obj = Map::new();
1091        obj.insert(
1092            "source".to_string(),
1093            JsonValue::String(result.source.clone()),
1094        );
1095        obj.insert(
1096            "target".to_string(),
1097            JsonValue::String(result.target.clone()),
1098        );
1099        obj.insert(
1100            "nodes_visited".to_string(),
1101            JsonValue::Number(result.nodes_visited as f64),
1102        );
1103
1104        match &result.path {
1105            Some(path) => {
1106                obj.insert("found".to_string(), JsonValue::Bool(true));
1107                obj.insert(
1108                    "hop_count".to_string(),
1109                    JsonValue::Number(path.hop_count as f64),
1110                );
1111                obj.insert(
1112                    "total_weight".to_string(),
1113                    JsonValue::Number(path.total_weight),
1114                );
1115                let nodes_json: Vec<JsonValue> = path
1116                    .nodes
1117                    .iter()
1118                    .map(|n| {
1119                        let mut nobj = Map::new();
1120                        nobj.insert("id".to_string(), JsonValue::String(n.id.clone()));
1121                        nobj.insert("label".to_string(), JsonValue::String(n.label.clone()));
1122                        JsonValue::Object(nobj)
1123                    })
1124                    .collect();
1125                obj.insert("nodes".to_string(), JsonValue::Array(nodes_json));
1126            }
1127            None => {
1128                obj.insert("found".to_string(), JsonValue::Bool(false));
1129            }
1130        }
1131
1132        json_to_string(&JsonValue::Object(obj)).map_err(|e| format!("serialization error: {}", e))
1133    }
1134
1135    fn tool_update(&self, args: &JsonValue) -> Result<String, String> {
1136        let collection = get_str_field(args, "collection")?;
1137        let set_obj = args.get("set").ok_or("missing 'set'")?;
1138        let where_clause = args
1139            .get("where_filter")
1140            .and_then(|v| v.as_str())
1141            .unwrap_or("");
1142
1143        // Build UPDATE SQL and execute via runtime. The collection and the
1144        // column names are spliced as identifiers, so they must be bare
1145        // identifiers; the values go through the SQL literal renderer, which
1146        // escapes quotes and backslashes the way the lexer reads them.
1147        use crate::server::handlers_query::is_safe_sql_identifier;
1148        if !is_safe_sql_identifier(collection) {
1149            return Err(format!(
1150                "invalid collection name '{collection}': expected [A-Za-z_][A-Za-z0-9_]*"
1151            ));
1152        }
1153        let mut sql = format!("UPDATE {} SET ", collection);
1154        if let Some(obj) = set_obj.as_object() {
1155            let assignments: Vec<String> = obj
1156                .iter()
1157                .map(|(k, v)| {
1158                    if !is_safe_sql_identifier(k) {
1159                        return Err(format!(
1160                            "invalid column name '{k}': expected [A-Za-z_][A-Za-z0-9_]*"
1161                        ));
1162                    }
1163                    Ok(format!(
1164                        "{} = {}",
1165                        k,
1166                        crate::rpc_stdio::value_to_sql_literal(v)
1167                    ))
1168                })
1169                .collect::<Result<_, String>>()?;
1170            sql.push_str(&assignments.join(", "));
1171        } else {
1172            return Err("'set' must be a JSON object".to_string());
1173        }
1174        if !where_clause.is_empty() {
1175            sql.push_str(&format!(" WHERE {}", where_clause));
1176        }
1177
1178        let uc = &self.runtime;
1179        let result = uc.execute_query(&(sql)).map_err(|e| format!("{}", e))?;
1180
1181        let mut resp = Map::new();
1182        resp.insert("ok".into(), JsonValue::Bool(true));
1183        resp.insert(
1184            "affected_rows".into(),
1185            JsonValue::Number(result.affected_rows as f64),
1186        );
1187        json_to_string(&JsonValue::Object(resp)).map_err(|e| format!("serialization error: {}", e))
1188    }
1189
1190    fn tool_scan(&self, args: &JsonValue) -> Result<String, String> {
1191        let collection = get_str_field(args, "collection")?;
1192        let limit = args
1193            .get("limit")
1194            .and_then(|v| v.as_u64())
1195            .map(|v| v as usize)
1196            .unwrap_or(10);
1197        let offset = args
1198            .get("offset")
1199            .and_then(|v| v.as_u64())
1200            .map(|v| v as usize)
1201            .unwrap_or(0);
1202
1203        let uc = &self.runtime;
1204        let page = uc
1205            .scan(ScanCollectionInput {
1206                collection: collection.to_string(),
1207                offset,
1208                limit,
1209            })
1210            .map_err(|e| format!("{}", e))?;
1211
1212        let json = crate::presentation::entity_json::scan_page_json(&page);
1213        json_to_string(&json).map_err(|e| format!("serialization error: {}", e))
1214    }
1215
1216    fn tool_graph_centrality(&self, args: &JsonValue) -> Result<String, String> {
1217        let algorithm_str = get_str_field(args, "algorithm")?;
1218        let algo = match algorithm_str {
1219            "degree" => RuntimeGraphCentralityAlgorithm::Degree,
1220            "closeness" => RuntimeGraphCentralityAlgorithm::Closeness,
1221            "betweenness" => RuntimeGraphCentralityAlgorithm::Betweenness,
1222            "eigenvector" => RuntimeGraphCentralityAlgorithm::Eigenvector,
1223            "pagerank" => RuntimeGraphCentralityAlgorithm::PageRank,
1224            _ => return Err(format!("unknown algorithm: {algorithm_str}")),
1225        };
1226
1227        let uc = GraphUseCases::new(&self.runtime);
1228        let result = uc
1229            .centrality(GraphCentralityInput {
1230                algorithm: algo,
1231                top_k: 100,
1232                normalize: true,
1233                max_iterations: None,
1234                epsilon: None,
1235                alpha: None,
1236                projection: None,
1237            })
1238            .map_err(|e| format!("{}", e))?;
1239
1240        let json = crate::presentation::graph_json::graph_centrality_json(&result);
1241        json_to_string(&json).map_err(|e| format!("serialization error: {}", e))
1242    }
1243
1244    fn tool_graph_community(&self, args: &JsonValue) -> Result<String, String> {
1245        let algorithm_str = get_str_field(args, "algorithm")?;
1246        let algo = match algorithm_str {
1247            "label_propagation" => RuntimeGraphCommunityAlgorithm::LabelPropagation,
1248            "louvain" => RuntimeGraphCommunityAlgorithm::Louvain,
1249            _ => return Err(format!("unknown algorithm: {algorithm_str}")),
1250        };
1251        let max_iterations = args
1252            .get("max_iterations")
1253            .and_then(|v| v.as_u64())
1254            .map(|v| v as usize);
1255
1256        let uc = GraphUseCases::new(&self.runtime);
1257        let result = uc
1258            .communities(GraphCommunitiesInput {
1259                algorithm: algo,
1260                min_size: 1,
1261                max_iterations,
1262                resolution: None,
1263                projection: None,
1264            })
1265            .map_err(|e| format!("{}", e))?;
1266
1267        let json = crate::presentation::graph_json::graph_community_json(&result);
1268        json_to_string(&json).map_err(|e| format!("serialization error: {}", e))
1269    }
1270
1271    fn tool_graph_components(&self, args: &JsonValue) -> Result<String, String> {
1272        let mode = match args.get("mode").and_then(|v| v.as_str()) {
1273            Some("strongly_connected") => RuntimeGraphComponentsMode::Strong,
1274            _ => RuntimeGraphComponentsMode::Weak,
1275        };
1276
1277        let uc = GraphUseCases::new(&self.runtime);
1278        let result = uc
1279            .components(GraphComponentsInput {
1280                mode,
1281                min_size: 1,
1282                projection: None,
1283            })
1284            .map_err(|e| format!("{}", e))?;
1285
1286        let json = crate::presentation::graph_json::graph_components_json(&result);
1287        json_to_string(&json).map_err(|e| format!("serialization error: {}", e))
1288    }
1289
1290    fn tool_graph_cycles(&self, args: &JsonValue) -> Result<String, String> {
1291        let max_length = args
1292            .get("max_length")
1293            .and_then(|v| v.as_u64())
1294            .map(|v| v as usize)
1295            .unwrap_or(10);
1296        let max_cycles = args
1297            .get("max_cycles")
1298            .and_then(|v| v.as_u64())
1299            .map(|v| v as usize)
1300            .unwrap_or(100);
1301
1302        let uc = GraphUseCases::new(&self.runtime);
1303        let result = uc
1304            .cycles(GraphCyclesInput {
1305                max_length,
1306                max_cycles,
1307                projection: None,
1308            })
1309            .map_err(|e| format!("{}", e))?;
1310
1311        let json = crate::presentation::graph_json::graph_cycles_json(&result);
1312        json_to_string(&json).map_err(|e| format!("serialization error: {}", e))
1313    }
1314
1315    fn tool_graph_clustering(&self, _args: &JsonValue) -> Result<String, String> {
1316        let uc = GraphUseCases::new(&self.runtime);
1317        let result = uc
1318            .clustering(GraphClusteringInput {
1319                top_k: 100,
1320                include_triangles: true,
1321                projection: None,
1322            })
1323            .map_err(|e| format!("{}", e))?;
1324
1325        let json = crate::presentation::graph_json::graph_clustering_json(&result);
1326        json_to_string(&json).map_err(|e| format!("serialization error: {}", e))
1327    }
1328
1329    fn tool_create_collection(&self, args: &JsonValue) -> Result<String, String> {
1330        let name = get_str_field(args, "name")?;
1331        self.runtime
1332            .db()
1333            .store()
1334            .create_collection(name)
1335            .map_err(|e| format!("{e:?}"))?;
1336        let mut resp = Map::new();
1337        resp.insert("ok".into(), JsonValue::Bool(true));
1338        resp.insert("collection".into(), JsonValue::String(name.to_string()));
1339        json_to_string(&JsonValue::Object(resp)).map_err(|e| format!("serialization error: {}", e))
1340    }
1341
1342    fn tool_drop_collection(&self, args: &JsonValue) -> Result<String, String> {
1343        let name = get_str_field(args, "name")?;
1344        self.runtime
1345            .db()
1346            .store()
1347            .drop_collection(name)
1348            .map_err(|e| format!("{e:?}"))?;
1349        let mut resp = Map::new();
1350        resp.insert("ok".into(), JsonValue::Bool(true));
1351        resp.insert("dropped".into(), JsonValue::String(name.to_string()));
1352        json_to_string(&JsonValue::Object(resp)).map_err(|e| format!("serialization error: {}", e))
1353    }
1354
1355    fn tool_rql_validate(&self, args: &JsonValue) -> Result<String, String> {
1356        let rql = get_str_field(args, "rql")?;
1357        let verdict = reddb_rql::knowledge::validate_rql(rql);
1358        let json = rql_validation_json(&verdict);
1359        json_to_string(&json).map_err(|e| format!("serialization error: {}", e))
1360    }
1361
1362    fn tool_rql_explain(&self, args: &JsonValue) -> Result<String, String> {
1363        let rql = get_str_field(args, "rql")?;
1364        let explanation = reddb_rql::knowledge::explain_rql(rql);
1365
1366        let mut obj = Map::new();
1367        obj.insert(
1368            "validation".to_string(),
1369            rql_validation_json(&explanation.validation),
1370        );
1371        if let Some(ast) = &explanation.ast {
1372            obj.insert("ast".to_string(), JsonValue::String(ast.clone()));
1373        }
1374        if let Some(optimized) = &explanation.optimized_ast {
1375            obj.insert(
1376                "optimized_ast".to_string(),
1377                JsonValue::String(optimized.clone()),
1378            );
1379        }
1380        obj.insert(
1381            "applied_passes".to_string(),
1382            JsonValue::Array(
1383                explanation
1384                    .applied_passes
1385                    .iter()
1386                    .cloned()
1387                    .map(JsonValue::String)
1388                    .collect(),
1389            ),
1390        );
1391        json_to_string(&JsonValue::Object(obj)).map_err(|e| format!("serialization error: {}", e))
1392    }
1393
1394    /// `reddb_type_of`: resolve a type name or a literal value to its canonical
1395    /// type plus applicable casts/operators, answered entirely from the
1396    /// generated `reddb-io-types` catalog (ADR 0061). This handler owns no type
1397    /// knowledge — it only marshals arguments into and JSON out of
1398    /// [`reddb_types::knowledge::type_of_json`].
1399    fn tool_type_of(&self, args: &JsonValue) -> Result<String, String> {
1400        let type_name = args.get("type").and_then(|v| v.as_str());
1401        let value = args.get("value");
1402        if type_name.is_none() && value.is_none() {
1403            return Err(
1404                "provide one of 'type' (a type name) or 'value' (a JSON literal)".to_string(),
1405            );
1406        }
1407        let facts =
1408            reddb_types::knowledge::type_of_json(type_name, value).ok_or_else(
1409                || match type_name {
1410                    Some(name) => format!("unknown type name '{name}'"),
1411                    None => "could not resolve a type from the request".to_string(),
1412                },
1413            )?;
1414        json_to_string(&facts).map_err(|e| format!("serialization error: {}", e))
1415    }
1416
1417    fn tool_explain_connection(&self, args: &JsonValue) -> Result<String, String> {
1418        let uri = get_str_field(args, "uri")?;
1419        let target = reddb_wire::parse(uri).map_err(|err| err.to_string())?;
1420        let json = connection_explanation_json(uri, &target);
1421        json_to_string(&json).map_err(|e| format!("serialization error: {}", e))
1422    }
1423}
1424
1425// ------------------------------------------------------------------
1426// Helpers
1427// ------------------------------------------------------------------
1428
1429fn format_mcp_ask_parse_error(err: crate::runtime::ai::mcp_ask_tool::ParseError) -> String {
1430    use crate::runtime::ai::mcp_ask_tool::ParseError;
1431
1432    match err {
1433        ParseError::NotAnObject => "arguments must be an object".to_string(),
1434        ParseError::MissingQuestion => "missing required field 'question'".to_string(),
1435        ParseError::QuestionWrongType => "field 'question' must be a string".to_string(),
1436        ParseError::WrongType { path, expected } => {
1437            format!("{path} must be {expected}")
1438        }
1439        ParseError::OutOfRange { path, detail } => {
1440            format!("{path} out of range: {detail}")
1441        }
1442        ParseError::CacheAndNocache => {
1443            "options.cache and options.nocache are mutually exclusive".to_string()
1444        }
1445        ParseError::UnknownOption { path } => format!("unknown option {path}"),
1446    }
1447}
1448
1449fn connection_explanation_json(uri: &str, target: &reddb_wire::ConnectionTarget) -> JsonValue {
1450    let scheme = connection_uri_scheme(uri);
1451    let mut obj = Map::new();
1452    obj.insert("uri".to_string(), JsonValue::String(uri.to_string()));
1453    obj.insert("scheme".to_string(), JsonValue::String(scheme.clone()));
1454
1455    let mut target_obj = Map::new();
1456    match target {
1457        reddb_wire::ConnectionTarget::Memory => {
1458            obj.insert(
1459                "mode".to_string(),
1460                JsonValue::String("embedded".to_string()),
1461            );
1462            obj.insert(
1463                "transport".to_string(),
1464                JsonValue::String("memory".to_string()),
1465            );
1466            obj.insert(
1467                "topology".to_string(),
1468                JsonValue::String("ephemeral".to_string()),
1469            );
1470            target_obj.insert("kind".to_string(), JsonValue::String("memory".to_string()));
1471        }
1472        reddb_wire::ConnectionTarget::File { path } => {
1473            obj.insert(
1474                "mode".to_string(),
1475                JsonValue::String("embedded".to_string()),
1476            );
1477            obj.insert(
1478                "transport".to_string(),
1479                JsonValue::String("filesystem".to_string()),
1480            );
1481            obj.insert(
1482                "topology".to_string(),
1483                JsonValue::String("persisted".to_string()),
1484            );
1485            target_obj.insert("kind".to_string(), JsonValue::String("file".to_string()));
1486            target_obj.insert(
1487                "path".to_string(),
1488                JsonValue::String(path.display().to_string()),
1489            );
1490        }
1491        reddb_wire::ConnectionTarget::Grpc { endpoint } => {
1492            obj.insert("mode".to_string(), JsonValue::String("remote".to_string()));
1493            obj.insert(
1494                "transport".to_string(),
1495                JsonValue::String(
1496                    if scheme == "grpcs" {
1497                        "grpc_tls"
1498                    } else {
1499                        "grpc"
1500                    }
1501                    .to_string(),
1502                ),
1503            );
1504            obj.insert(
1505                "topology".to_string(),
1506                JsonValue::String("single".to_string()),
1507            );
1508            target_obj.insert("kind".to_string(), JsonValue::String("grpc".to_string()));
1509            target_obj.insert("endpoint".to_string(), JsonValue::String(endpoint.clone()));
1510        }
1511        reddb_wire::ConnectionTarget::GrpcCluster {
1512            primary,
1513            replicas,
1514            force_primary,
1515        } => {
1516            obj.insert("mode".to_string(), JsonValue::String("remote".to_string()));
1517            obj.insert(
1518                "transport".to_string(),
1519                JsonValue::String(cluster_transport_label(&scheme).to_string()),
1520            );
1521            obj.insert(
1522                "topology".to_string(),
1523                JsonValue::String("primary_replica".to_string()),
1524            );
1525            target_obj.insert(
1526                "kind".to_string(),
1527                JsonValue::String("primary_replica".to_string()),
1528            );
1529            target_obj.insert("primary".to_string(), JsonValue::String(primary.clone()));
1530            target_obj.insert(
1531                "replicas".to_string(),
1532                JsonValue::Array(replicas.iter().cloned().map(JsonValue::String).collect()),
1533            );
1534            target_obj.insert("force_primary".to_string(), JsonValue::Bool(*force_primary));
1535        }
1536        reddb_wire::ConnectionTarget::Http { base_url } => {
1537            obj.insert("mode".to_string(), JsonValue::String("remote".to_string()));
1538            obj.insert(
1539                "transport".to_string(),
1540                JsonValue::String(if scheme == "https" { "https" } else { "http" }.to_string()),
1541            );
1542            obj.insert(
1543                "topology".to_string(),
1544                JsonValue::String("single".to_string()),
1545            );
1546            target_obj.insert("kind".to_string(), JsonValue::String("http".to_string()));
1547            target_obj.insert("base_url".to_string(), JsonValue::String(base_url.clone()));
1548        }
1549        reddb_wire::ConnectionTarget::RedWire { host, port, tls } => {
1550            obj.insert("mode".to_string(), JsonValue::String("remote".to_string()));
1551            obj.insert(
1552                "transport".to_string(),
1553                JsonValue::String(if *tls { "redwire_tls" } else { "redwire" }.to_string()),
1554            );
1555            obj.insert(
1556                "topology".to_string(),
1557                JsonValue::String("single".to_string()),
1558            );
1559            target_obj.insert("kind".to_string(), JsonValue::String("redwire".to_string()));
1560            target_obj.insert("host".to_string(), JsonValue::String(host.clone()));
1561            target_obj.insert("port".to_string(), JsonValue::Number(*port as f64));
1562            target_obj.insert("tls".to_string(), JsonValue::Bool(*tls));
1563        }
1564        reddb_wire::ConnectionTarget::WsNative { host, port, tls } => {
1565            obj.insert("mode".to_string(), JsonValue::String("remote".to_string()));
1566            obj.insert(
1567                "transport".to_string(),
1568                JsonValue::String(if *tls { "redwire_wss" } else { "redwire_ws" }.to_string()),
1569            );
1570            obj.insert(
1571                "topology".to_string(),
1572                JsonValue::String("single".to_string()),
1573            );
1574            target_obj.insert(
1575                "kind".to_string(),
1576                JsonValue::String("redwire_websocket".to_string()),
1577            );
1578            target_obj.insert("host".to_string(), JsonValue::String(host.clone()));
1579            target_obj.insert("port".to_string(), JsonValue::Number(*port as f64));
1580            target_obj.insert("tls".to_string(), JsonValue::Bool(*tls));
1581        }
1582    }
1583    obj.insert("target".to_string(), JsonValue::Object(target_obj));
1584    JsonValue::Object(obj)
1585}
1586
1587fn connection_uri_scheme(uri: &str) -> String {
1588    uri.split_once(':')
1589        .map(|(scheme, _)| scheme.to_ascii_lowercase())
1590        .unwrap_or_default()
1591}
1592
1593fn cluster_transport_label(scheme: &str) -> &'static str {
1594    match scheme {
1595        "red" => "redwire",
1596        "reds" => "redwire_tls",
1597        "grpcs" => "grpc_tls",
1598        _ => "grpc",
1599    }
1600}
1601
1602/// Render an RQL parse verdict (ADR 0061, #1317) as the JSON the
1603/// `reddb_rql_validate` / `reddb_rql_explain` tools return.
1604fn rql_validation_json(verdict: &reddb_rql::knowledge::RqlValidation) -> JsonValue {
1605    let mut obj = Map::new();
1606    obj.insert("valid".to_string(), JsonValue::Bool(verdict.valid));
1607    if let Some(statement) = &verdict.statement {
1608        obj.insert(
1609            "statement".to_string(),
1610            JsonValue::String(statement.clone()),
1611        );
1612    }
1613    obj.insert(
1614        "has_with_clause".to_string(),
1615        JsonValue::Bool(verdict.has_with_clause),
1616    );
1617    if let Some(error) = &verdict.error {
1618        obj.insert("error".to_string(), rql_diagnostic_json(error));
1619    }
1620    JsonValue::Object(obj)
1621}
1622
1623/// Render a structured RQL parse diagnostic as JSON.
1624fn rql_diagnostic_json(diag: &reddb_rql::knowledge::RqlDiagnostic) -> JsonValue {
1625    let mut obj = Map::new();
1626    obj.insert(
1627        "message".to_string(),
1628        JsonValue::String(diag.message.clone()),
1629    );
1630    obj.insert("line".to_string(), JsonValue::Number(diag.line as f64));
1631    obj.insert("column".to_string(), JsonValue::Number(diag.column as f64));
1632    obj.insert("offset".to_string(), JsonValue::Number(diag.offset as f64));
1633    obj.insert("kind".to_string(), JsonValue::String(diag.kind.clone()));
1634    obj.insert(
1635        "expected".to_string(),
1636        JsonValue::Array(
1637            diag.expected
1638                .iter()
1639                .cloned()
1640                .map(JsonValue::String)
1641                .collect(),
1642        ),
1643    );
1644    JsonValue::Object(obj)
1645}
1646
1647fn parse_direction(s: Option<&str>) -> RuntimeGraphDirection {
1648    match s {
1649        Some("incoming") => RuntimeGraphDirection::Incoming,
1650        Some("both") => RuntimeGraphDirection::Both,
1651        _ => RuntimeGraphDirection::Outgoing,
1652    }
1653}
1654
1655/// Parse optional metadata from an `args` JSON object.
1656fn parse_metadata_arg(
1657    args: &JsonValue,
1658) -> Result<Vec<(String, crate::storage::unified::MetadataValue)>, String> {
1659    match args.get("metadata").and_then(|v| v.as_object()) {
1660        Some(obj) => {
1661            let mut out = Vec::with_capacity(obj.len());
1662            for (key, value) in obj {
1663                let mv = crate::application::entity::json_to_metadata_value(value)
1664                    .map_err(|e| format!("{}", e))?;
1665                out.push((key.clone(), mv));
1666            }
1667            Ok(out)
1668        }
1669        None => Ok(vec![]),
1670    }
1671}
1672
1673fn parse_string_array_arg(args: &JsonValue, field: &str) -> Result<Vec<String>, String> {
1674    match args.get(field) {
1675        None | Some(JsonValue::Null) => Ok(Vec::new()),
1676        Some(JsonValue::Array(values)) => values
1677            .iter()
1678            .map(|value| {
1679                value
1680                    .as_str()
1681                    .map(ToOwned::to_owned)
1682                    .ok_or_else(|| format!("field '{field}' must be an array of strings"))
1683            })
1684            .collect(),
1685        _ => Err(format!("field '{field}' must be an array of strings")),
1686    }
1687}
1688
1689fn mcp_keyed_ident(value: &str) -> Result<String, String> {
1690    if !value.is_empty()
1691        && value
1692            .bytes()
1693            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'.')
1694    {
1695        Ok(value.to_string())
1696    } else {
1697        Err(
1698            "keyed collection and key names must use letters, numbers, underscores, or dots"
1699                .to_string(),
1700        )
1701    }
1702}
1703
1704fn mcp_value_literal(value: &JsonValue) -> Result<String, String> {
1705    match value {
1706        JsonValue::String(value) => Ok(format!("'{}'", value.replace('\'', "''"))),
1707        JsonValue::Integer(value) => Ok(value.to_string()),
1708        JsonValue::Number(value) => Ok(value.to_string()),
1709        JsonValue::Decimal(value) => Ok(value.clone()),
1710        JsonValue::Bool(value) => Ok(value.to_string()),
1711        JsonValue::Null => Ok("NULL".to_string()),
1712        JsonValue::Array(_) | JsonValue::Object(_) => {
1713            json_to_string(value).map_err(|err| format!("serialization error: {err}"))
1714        }
1715    }
1716}
1717
1718fn append_mcp_tags_clause(sql: &mut String, tags: &[String]) {
1719    if tags.is_empty() {
1720        return;
1721    }
1722    sql.push_str(" TAGS [");
1723    for (index, tag) in tags.iter().enumerate() {
1724        if index > 0 {
1725            sql.push_str(", ");
1726        }
1727        sql.push('\'');
1728        sql.push_str(&tag.replace('\'', "''"));
1729        sql.push('\'');
1730    }
1731    sql.push(']');
1732}
1733
1734fn reject_mcp_volatile_options(args: &JsonValue, domain: &str) -> Result<(), String> {
1735    for field in ["ttl", "ttl_ms", "expire", "expire_ms", "expires_at"] {
1736        if args.get(field).is_some() {
1737            return Err(format!(
1738                "{domain} does not support TTL or expiration options"
1739            ));
1740        }
1741    }
1742    Ok(())
1743}
1744
1745// Convert a storage Value to JSON (local helper to avoid visibility issues).
1746fn get_str_field<'a>(args: &'a JsonValue, field: &str) -> Result<&'a str, String> {
1747    args.get(field)
1748        .and_then(|v| v.as_str())
1749        .ok_or_else(|| format!("missing '{field}'"))
1750}
1751
1752// Auth tool implementations
1753impl McpServer {
1754    fn tool_auth_bootstrap(&self, args: &JsonValue) -> Result<String, String> {
1755        let username = get_str_field(args, "username")?;
1756        let password = get_str_field(args, "password")?;
1757
1758        let br = self
1759            .auth_store
1760            .bootstrap(username, password)
1761            .map_err(|e| e.to_string())?;
1762
1763        let mut result = Map::new();
1764        result.insert("ok".into(), JsonValue::Bool(true));
1765        result.insert("username".into(), JsonValue::String(br.user.username));
1766        result.insert(
1767            "role".into(),
1768            JsonValue::String(br.user.role.as_str().into()),
1769        );
1770        result.insert("api_key".into(), JsonValue::String(br.api_key.key));
1771        result.insert("api_key_name".into(), JsonValue::String(br.api_key.name));
1772        if let Some(cert) = br.certificate {
1773            result.insert("certificate".into(), JsonValue::String(cert));
1774            result.insert(
1775                "message".into(),
1776                JsonValue::String(
1777                    "Save this certificate — it is the ONLY way to unseal the vault after restart."
1778                        .into(),
1779                ),
1780            );
1781        } else {
1782            result.insert(
1783                "message".into(),
1784                JsonValue::String(
1785                    "First admin user created. Save the API key — it won't be shown again.".into(),
1786                ),
1787            );
1788        }
1789        json_to_string(&JsonValue::Object(result))
1790    }
1791
1792    fn tool_auth_create_user(&self, args: &JsonValue) -> Result<String, String> {
1793        let username = get_str_field(args, "username")?;
1794        let password = get_str_field(args, "password")?;
1795        let role_str = get_str_field(args, "role")?;
1796        let role = Role::from_str(role_str).ok_or_else(|| format!("invalid role: {role_str}"))?;
1797
1798        self.auth_store
1799            .create_user(username, password, role)
1800            .map_err(|e| e.to_string())?;
1801
1802        let mut result = Map::new();
1803        result.insert("ok".into(), JsonValue::Bool(true));
1804        result.insert("username".into(), JsonValue::String(username.into()));
1805        result.insert("role".into(), JsonValue::String(role.as_str().into()));
1806        json_to_string(&JsonValue::Object(result))
1807    }
1808
1809    fn tool_auth_login(&self, args: &JsonValue) -> Result<String, String> {
1810        let username = get_str_field(args, "username")?;
1811        let password = get_str_field(args, "password")?;
1812
1813        let session = self
1814            .auth_store
1815            .authenticate_active(None, username, password)
1816            .map_err(|e| e.to_string())?;
1817
1818        let mut result = Map::new();
1819        result.insert("ok".into(), JsonValue::Bool(true));
1820        result.insert("token".into(), JsonValue::String(session.token));
1821        result.insert("username".into(), JsonValue::String(session.username));
1822        result.insert(
1823            "role".into(),
1824            JsonValue::String(session.role.as_str().into()),
1825        );
1826        result.insert(
1827            "expires_at".into(),
1828            JsonValue::Number(session.expires_at as f64),
1829        );
1830        json_to_string(&JsonValue::Object(result))
1831    }
1832
1833    fn tool_auth_create_api_key(&self, args: &JsonValue) -> Result<String, String> {
1834        let username = get_str_field(args, "username")?;
1835        let name = get_str_field(args, "name")?;
1836        let role_str = get_str_field(args, "role")?;
1837        let role = Role::from_str(role_str).ok_or_else(|| format!("invalid role: {role_str}"))?;
1838
1839        let key = self
1840            .auth_store
1841            .create_api_key(username, name, role)
1842            .map_err(|e| e.to_string())?;
1843
1844        let mut result = Map::new();
1845        result.insert("ok".into(), JsonValue::Bool(true));
1846        result.insert("key".into(), JsonValue::String(key.key));
1847        result.insert("name".into(), JsonValue::String(key.name));
1848        result.insert("role".into(), JsonValue::String(key.role.as_str().into()));
1849        json_to_string(&JsonValue::Object(result))
1850    }
1851
1852    fn tool_auth_list_users(&self) -> Result<String, String> {
1853        let users = self.auth_store.list_users();
1854        let arr: Vec<JsonValue> = users
1855            .into_iter()
1856            .map(|u| {
1857                let mut obj = Map::new();
1858                obj.insert("username".into(), JsonValue::String(u.username));
1859                obj.insert("role".into(), JsonValue::String(u.role.as_str().into()));
1860                obj.insert("enabled".into(), JsonValue::Bool(u.enabled));
1861                obj.insert(
1862                    "api_key_count".into(),
1863                    JsonValue::Number(u.api_keys.len() as f64),
1864                );
1865                JsonValue::Object(obj)
1866            })
1867            .collect();
1868        json_to_string(&JsonValue::Array(arr))
1869    }
1870}
1871
1872#[cfg(test)]
1873mod tests {
1874    use super::*;
1875    use std::io::{Read, Write};
1876    use std::net::{SocketAddr, TcpListener, TcpStream};
1877    use std::sync::atomic::{AtomicBool, Ordering};
1878    use std::sync::{Arc, Mutex};
1879    use std::thread::{self, JoinHandle};
1880    use std::time::Duration;
1881
1882    static ASK_ENV_LOCK: Mutex<()> = Mutex::new(());
1883
1884    /// The existing suite exercises the whole tool surface (DDL, inserts,
1885    /// vault, auth), so it runs at the level an operator would opt into with
1886    /// `--allow-admin`. `read_only_session_*` below cover the default.
1887    fn make_server() -> McpServer {
1888        let rt = RedDBRuntime::in_memory().expect("in-memory runtime");
1889        McpServer::new(rt).with_capability(McpCapability::Admin)
1890    }
1891
1892    /// A session at the shipped default: no flags.
1893    fn make_read_only_server() -> McpServer {
1894        let rt = RedDBRuntime::in_memory().expect("in-memory runtime");
1895        McpServer::new(rt)
1896    }
1897
1898    #[test]
1899    fn update_tool_renders_values_as_literals_and_refuses_crafted_identifiers() {
1900        let srv = make_server();
1901        srv.tool_query(&parse_json(
1902            r#"{"sql":"CREATE TABLE mcp_upd (id INTEGER, name TEXT)"}"#,
1903        ))
1904        .expect("create");
1905        srv.tool_query(&parse_json(
1906            r#"{"sql":"INSERT INTO mcp_upd (id, name) VALUES (1, 'a')"}"#,
1907        ))
1908        .expect("seed");
1909        // A quote inside the value used to close the literal and run the
1910        // remainder as SQL.
1911        srv.tool_update(&parse_json(
1912            r#"{"collection":"mcp_upd","set":{"name":"o'brien"},"where_filter":"id = 1"}"#,
1913        ))
1914        .expect("escaped value");
1915        let rows = srv
1916            .tool_query(&parse_json(
1917                r#"{"sql":"SELECT name FROM mcp_upd WHERE id = 1"}"#,
1918            ))
1919            .expect("read back");
1920        assert!(rows.contains("o'brien"), "{rows}");
1921
1922        for args in [
1923            r#"{"collection":"mcp_upd; DROP TABLE mcp_upd","set":{"name":"x"}}"#,
1924            r#"{"collection":"mcp_upd","set":{"name = 'x' WHERE 1=1 --":"x"}}"#,
1925        ] {
1926            let err = srv
1927                .tool_update(&parse_json(args))
1928                .expect_err("crafted identifier must be refused");
1929            assert!(err.contains("invalid"), "{err}");
1930        }
1931    }
1932
1933    #[test]
1934    fn read_only_session_refuses_mutating_tools() {
1935        // The MCP transport has no second principal to authenticate, so the
1936        // tool list is the boundary: a model steered by injected content
1937        // must not reach `drop_collection` or the vault by default.
1938        let srv = make_read_only_server();
1939        assert_eq!(srv.capability(), McpCapability::ReadOnly);
1940        for tool in [
1941            "reddb_drop_collection",
1942            "reddb_delete",
1943            "reddb_insert_row",
1944            "reddb_vault_unseal",
1945            "reddb_auth_create_api_key",
1946        ] {
1947            let err = srv
1948                .check_tool_capability(tool)
1949                .expect_err("mutating tool must be refused by default");
1950            assert!(err.contains("read-only"), "{tool}: {err}");
1951        }
1952        // Reads still work, otherwise the default is useless.
1953        srv.check_tool_capability("reddb_query")
1954            .expect("reads stay available");
1955        srv.check_tool_capability("reddb_collections")
1956            .expect("introspection stays available");
1957        srv.check_tool_capability("reddb_catalog")
1958            .expect("catalog inspection stays available");
1959        srv.check_tool_capability("reddb_describe_collection")
1960            .expect("collection descriptions stay available");
1961        srv.check_tool_capability("reddb_find_field")
1962            .expect("field discovery stays available");
1963        srv.check_tool_capability(crate::runtime::ai::mcp_ask_tool::TOOL_NAME)
1964            .expect("grounded ASK stays available");
1965    }
1966
1967    #[test]
1968    fn metadata_tools_use_parameterized_catalog_queries() {
1969        let srv = make_server();
1970        srv.tool_query(&parse_json(
1971            r#"{"sql":"CREATE TABLE people (id INTEGER PRIMARY KEY, passport_number TEXT)"}"#,
1972        ))
1973        .expect("create people table");
1974        srv.tool_query(&parse_json(
1975            r#"{"sql":"CREATE TABLE visits (id INTEGER PRIMARY KEY, arrived_at TIMESTAMP)"}"#,
1976        ))
1977        .expect("create visits table");
1978
1979        let collections = srv.tool_collections().expect("list collection names");
1980        assert!(collections.contains("people"), "{collections}");
1981        assert!(!collections.contains("table"), "{collections}");
1982
1983        let catalog = srv.tool_catalog().expect("list collection metadata");
1984        assert!(catalog.contains("people"), "{catalog}");
1985        assert!(catalog.contains("table"), "{catalog}");
1986
1987        let description = srv
1988            .tool_describe_collection(&parse_json(r#"{"collection":"people"}"#))
1989            .expect("describe people");
1990        assert!(description.contains("passport_number"), "{description}");
1991        assert!(description.contains("is_primary_key"), "{description}");
1992
1993        let matches = srv
1994            .tool_find_field(&parse_json(r#"{"field":"passport_number"}"#))
1995            .expect("find passport field");
1996        assert!(matches.contains("people"), "{matches}");
1997        assert!(!matches.contains("visits"), "{matches}");
1998
1999        let injected = srv
2000            .tool_describe_collection(&parse_json(
2001                r#"{"collection":"people' OR collection = 'visits"}"#,
2002            ))
2003            .expect("crafted collection remains a bind value");
2004        assert!(!injected.contains("passport_number"), "{injected}");
2005        assert!(!injected.contains("arrived_at"), "{injected}");
2006    }
2007
2008    #[test]
2009    fn read_only_session_refuses_mutating_sql_through_the_query_tool() {
2010        // `reddb_query` is a read tool that takes arbitrary SQL, so the
2011        // statement has to be classified too — otherwise the one tool a
2012        // read-only session may call is a full write channel.
2013        let srv = make_read_only_server();
2014        let err = srv
2015            .tool_query(&parse_json(r#"{"sql":"DROP TABLE users"}"#))
2016            .expect_err("DDL must be refused in a read-only session");
2017        assert!(err.contains("write"), "{err}");
2018
2019        let err = srv
2020            .tool_query(&parse_json(r#"{"sql":"SHOW SECRETS"}"#))
2021            .expect_err("secret reads must require admin");
2022        assert!(err.contains("admin"), "{err}");
2023
2024        srv.tool_query(&parse_json(r#"{"sql":"SELECT 1 AS one"}"#))
2025            .expect("plain reads still work");
2026    }
2027
2028    #[test]
2029    fn allow_write_does_not_unlock_vault_or_auth_tools() {
2030        // `--allow-write` is for data and schema. Credentials need the
2031        // separate, louder opt-in.
2032        let rt = RedDBRuntime::in_memory().expect("in-memory runtime");
2033        let srv = McpServer::new(rt).with_capability(McpCapability::Write);
2034        srv.check_tool_capability("reddb_insert_row")
2035            .expect("writes are enabled");
2036        let err = srv
2037            .check_tool_capability("reddb_vault_get")
2038            .expect_err("vault stays behind --allow-admin");
2039        assert!(err.contains("admin"), "{err}");
2040    }
2041
2042    fn parse_json(s: &str) -> JsonValue {
2043        json_from_str(s).expect("valid json")
2044    }
2045
2046    #[test]
2047    fn initialize_advertises_resources_capability() {
2048        let mut srv = make_server();
2049        let response = srv.handle_initialize(Some(&JsonValue::Number(1.0)));
2050        let parsed = parse_json(&response);
2051        let resources = parsed
2052            .get("result")
2053            .and_then(|result| result.get("capabilities"))
2054            .and_then(|caps| caps.get("resources"))
2055            .expect("resources capability advertised");
2056        assert_eq!(
2057            resources.get("subscribe").and_then(JsonValue::as_bool),
2058            Some(false)
2059        );
2060    }
2061
2062    #[test]
2063    fn resources_list_includes_rql_knowledge() {
2064        let mut srv = make_server();
2065        let request = parse_json(r#"{"jsonrpc":"2.0","id":7,"method":"resources/list"}"#);
2066        let response = srv.handle_message(&request).expect("response");
2067        let parsed = parse_json(&response);
2068        let resources = parsed
2069            .get("result")
2070            .and_then(|result| result.get("resources"))
2071            .and_then(JsonValue::as_array)
2072            .expect("resources array");
2073
2074        let rql = resources
2075            .iter()
2076            .find(|res| res.get("uri").and_then(JsonValue::as_str) == Some("reddb://knowledge/rql"))
2077            .expect("rql knowledge resource listed");
2078        assert_eq!(
2079            rql.get("mimeType").and_then(JsonValue::as_str),
2080            Some("text/markdown")
2081        );
2082        assert!(rql.get("name").and_then(JsonValue::as_str).is_some());
2083    }
2084
2085    #[test]
2086    fn resources_list_includes_connection_knowledge() {
2087        let mut srv = make_server();
2088        let request = parse_json(r#"{"jsonrpc":"2.0","id":11,"method":"resources/list"}"#);
2089        let response = srv.handle_message(&request).expect("response");
2090        let parsed = parse_json(&response);
2091        let resources = parsed
2092            .get("result")
2093            .and_then(|result| result.get("resources"))
2094            .and_then(JsonValue::as_array)
2095            .expect("resources array");
2096
2097        let connection = resources
2098            .iter()
2099            .find(|res| {
2100                res.get("uri").and_then(JsonValue::as_str)
2101                    == Some(reddb_wire::knowledge::RESOURCE_URI)
2102            })
2103            .expect("connection knowledge resource listed");
2104        assert_eq!(
2105            connection.get("mimeType").and_then(JsonValue::as_str),
2106            Some("text/markdown")
2107        );
2108        assert!(connection.get("name").and_then(JsonValue::as_str).is_some());
2109    }
2110
2111    #[test]
2112    fn resources_read_returns_generated_rql_reference() {
2113        let mut srv = make_server();
2114        let request = parse_json(
2115            r#"{"jsonrpc":"2.0","id":8,"method":"resources/read","params":{"uri":"reddb://knowledge/rql"}}"#,
2116        );
2117        let response = srv.handle_message(&request).expect("response");
2118        let parsed = parse_json(&response);
2119        let text = parsed
2120            .get("result")
2121            .and_then(|result| result.get("contents"))
2122            .and_then(JsonValue::as_array)
2123            .and_then(|contents| contents.first())
2124            .and_then(|item| item.get("text"))
2125            .and_then(JsonValue::as_str)
2126            .expect("resource text");
2127
2128        // The body is exactly what the RQL authority generates — same source as
2129        // docs/llms.txt.
2130        assert_eq!(text, reddb_rql::knowledge::rql_reference_markdown());
2131        // And it is genuinely generated from the engine: a sampled keyword and
2132        // function from the authorities are present.
2133        assert!(text.contains("`SELECT`"), "keyword missing: {text:.120}");
2134        assert!(text.contains("`COUNT`"), "function missing");
2135    }
2136
2137    #[test]
2138    fn resources_read_returns_generated_type_reference() {
2139        let mut srv = make_server();
2140        let request = parse_json(
2141            r#"{"jsonrpc":"2.0","id":10,"method":"resources/read","params":{"uri":"reddb://knowledge/types"}}"#,
2142        );
2143        let response = srv.handle_message(&request).expect("response");
2144        let parsed = parse_json(&response);
2145        let text = parsed
2146            .get("result")
2147            .and_then(|result| result.get("contents"))
2148            .and_then(JsonValue::as_array)
2149            .and_then(|contents| contents.first())
2150            .and_then(|item| item.get("text"))
2151            .and_then(JsonValue::as_str)
2152            .expect("resource text");
2153
2154        // The body is exactly what the type authority generates — same source as
2155        // docs/llms.txt.
2156        assert_eq!(text, reddb_types::knowledge::type_reference_markdown());
2157        // And it is genuinely generated from the engine: a sampled value type and
2158        // a multi-model paradigm are present.
2159        assert!(
2160            text.contains("`INTEGER`"),
2161            "value type missing: {text:.120}"
2162        );
2163        assert!(text.contains("Multi-model map"), "multi-model map missing");
2164    }
2165
2166    #[test]
2167    fn resources_read_returns_generated_connection_reference() {
2168        let mut srv = make_server();
2169        let request = parse_json(
2170            r#"{"jsonrpc":"2.0","id":12,"method":"resources/read","params":{"uri":"reddb://knowledge/connections"}}"#,
2171        );
2172        let response = srv.handle_message(&request).expect("response");
2173        let parsed = parse_json(&response);
2174        let text = parsed
2175            .get("result")
2176            .and_then(|result| result.get("contents"))
2177            .and_then(JsonValue::as_array)
2178            .and_then(|contents| contents.first())
2179            .and_then(|item| item.get("text"))
2180            .and_then(JsonValue::as_str)
2181            .expect("resource text");
2182
2183        // The body is exactly what the wire authority generates — same source as
2184        // docs/llms.txt.
2185        assert_eq!(text, reddb_wire::knowledge::connection_reference_markdown());
2186        assert!(text.contains("`red://`"), "red scheme missing: {text:.120}");
2187        assert!(text.contains("`reds://`"), "reds scheme missing");
2188        assert!(
2189            text.contains("principal transport"),
2190            "principal transport narrative missing"
2191        );
2192        assert!(
2193            text.contains("Embedded / standalone"),
2194            "embedded topology missing"
2195        );
2196        assert!(text.contains("Serverless"), "serverless topology missing");
2197        assert!(
2198            text.contains("Primary-replica"),
2199            "primary-replica topology missing"
2200        );
2201        assert!(text.contains("Cluster"), "cluster topology missing");
2202    }
2203
2204    #[test]
2205    fn resources_read_unknown_uri_errors() {
2206        let mut srv = make_server();
2207        let request = parse_json(
2208            r#"{"jsonrpc":"2.0","id":9,"method":"resources/read","params":{"uri":"reddb://knowledge/nope"}}"#,
2209        );
2210        let response = srv.handle_message(&request).expect("response");
2211        let parsed = parse_json(&response);
2212        assert!(
2213            parsed.get("error").is_some(),
2214            "unknown resource must error: {response}"
2215        );
2216    }
2217
2218    #[test]
2219    fn tools_list_registers_reddb_ask_descriptor() {
2220        let srv = make_server();
2221        let response = srv.handle_tools_list(Some(&JsonValue::Number(1.0)));
2222        let parsed = parse_json(&response);
2223        let tools = parsed
2224            .get("result")
2225            .and_then(|result| result.get("tools"))
2226            .and_then(JsonValue::as_array)
2227            .expect("tools array");
2228
2229        let ask = tools
2230            .iter()
2231            .find(|tool| tool.get("name").and_then(JsonValue::as_str) == Some("reddb.ask"))
2232            .expect("reddb.ask registered");
2233
2234        let desc = ask
2235            .get("description")
2236            .and_then(JsonValue::as_str)
2237            .expect("description");
2238        assert!(desc.contains("citations"), "description: {desc}");
2239        assert!(desc.contains("sources_flat"), "description: {desc}");
2240        assert!(desc.contains("URN"), "description: {desc}");
2241
2242        let options = ask
2243            .get("inputSchema")
2244            .and_then(|schema| schema.get("properties"))
2245            .and_then(|props| props.get("options"))
2246            .and_then(|opts| opts.get("properties"))
2247            .and_then(JsonValue::as_object)
2248            .expect("options properties");
2249        for key in [
2250            "strict",
2251            "using",
2252            "model",
2253            "limit",
2254            "min_score",
2255            "depth",
2256            "temperature",
2257            "seed",
2258            "cache",
2259            "nocache",
2260        ] {
2261            assert!(
2262                options.contains_key(key),
2263                "missing option {key} in {options:?}"
2264            );
2265        }
2266    }
2267
2268    #[test]
2269    fn embedded_dispatch_reaches_every_advertised_tool() {
2270        let server = make_server();
2271        let mut tool_names: Vec<&str> = tools::all_tools()
2272            .into_iter()
2273            .map(|tool| tool.name)
2274            .collect();
2275        tool_names.push(crate::runtime::ai::mcp_ask_tool::TOOL_NAME);
2276
2277        for tool_name in tool_names {
2278            let mut params = Map::new();
2279            params.insert("name".to_string(), JsonValue::String(tool_name.to_string()));
2280            params.insert("arguments".to_string(), JsonValue::Object(Map::new()));
2281            let response = server.handle_tools_call(
2282                Some(&JsonValue::Number(1.0)),
2283                Some(&JsonValue::Object(params)),
2284            );
2285            let parsed = parse_json(&response);
2286            let result = parsed.get("result").expect("tool result");
2287            let text = result
2288                .get("content")
2289                .and_then(JsonValue::as_array)
2290                .and_then(|content| content.first())
2291                .and_then(|item| item.get("text"))
2292                .and_then(JsonValue::as_str)
2293                .expect("tool result text");
2294
2295            assert!(
2296                !text.contains("unknown tool") && !text.contains("denied by policy"),
2297                "embedded tool {tool_name} did not reach its dispatch arm: {text}"
2298            );
2299        }
2300    }
2301
2302    #[test]
2303    fn tools_call_reddb_ask_uses_typed_argument_parser() {
2304        let srv = make_server();
2305        let params = parse_json(
2306            r#"{
2307                "name": "reddb.ask",
2308                "arguments": {
2309                    "question": "what cites this?",
2310                    "options": { "tempurature": 0.2 }
2311                }
2312            }"#,
2313        );
2314
2315        let response = srv.handle_tools_call(Some(&JsonValue::Number(1.0)), Some(&params));
2316        let parsed = parse_json(&response);
2317        let result = parsed.get("result").expect("result");
2318        assert_eq!(
2319            result.get("isError").and_then(JsonValue::as_bool),
2320            Some(true)
2321        );
2322        let text = result
2323            .get("content")
2324            .and_then(JsonValue::as_array)
2325            .and_then(|content| content.first())
2326            .and_then(|item| item.get("text"))
2327            .and_then(JsonValue::as_str)
2328            .expect("error text");
2329        assert!(text.contains("options.tempurature"), "text: {text}");
2330    }
2331
2332    /// Helper: drive a `reddb_type_of` `tools/call` over the JSON-RPC seam and
2333    /// return the parsed result object (`content`/`isError`), exercising the
2334    /// real dispatcher.
2335    fn call_type_of(srv: &mut McpServer, arguments: &str) -> JsonValue {
2336        let request = parse_json(&format!(
2337            r#"{{"jsonrpc":"2.0","id":21,"method":"tools/call","params":{{"name":"reddb_type_of","arguments":{arguments}}}}}"#
2338        ));
2339        let response = srv.handle_message(&request).expect("response");
2340        parse_json(&response)
2341            .get("result")
2342            .cloned()
2343            .expect("result object")
2344    }
2345
2346    /// Extract the text payload of a (non-error) tool result and parse it as JSON.
2347    fn type_of_result_json(result: &JsonValue) -> JsonValue {
2348        assert_ne!(
2349            result.get("isError").and_then(JsonValue::as_bool),
2350            Some(true),
2351            "tool returned an error: {result:?}"
2352        );
2353        let text = result
2354            .get("content")
2355            .and_then(JsonValue::as_array)
2356            .and_then(|content| content.first())
2357            .and_then(|item| item.get("text"))
2358            .and_then(JsonValue::as_str)
2359            .expect("result text");
2360        parse_json(text)
2361    }
2362
2363    #[test]
2364    fn tools_list_includes_reddb_type_of() {
2365        let srv = make_server();
2366        let response = srv.handle_tools_list(Some(&JsonValue::Number(1.0)));
2367        let parsed = parse_json(&response);
2368        let tools = parsed
2369            .get("result")
2370            .and_then(|result| result.get("tools"))
2371            .and_then(JsonValue::as_array)
2372            .expect("tools array");
2373        assert!(
2374            tools
2375                .iter()
2376                .any(|tool| tool.get("name").and_then(JsonValue::as_str) == Some("reddb_type_of")),
2377            "reddb_type_of must be advertised in tools/list"
2378        );
2379    }
2380
2381    #[test]
2382    fn tools_call_type_of_resolves_type_name_from_catalog() {
2383        let mut srv = make_server();
2384        let result = call_type_of(&mut srv, r#"{"type":"int"}"#);
2385        let facts = type_of_result_json(&result);
2386
2387        // Canonical type + category come from the catalog authority.
2388        assert_eq!(
2389            facts.get("canonical_type").and_then(JsonValue::as_str),
2390            Some("INTEGER")
2391        );
2392        assert_eq!(
2393            facts.get("category").and_then(JsonValue::as_str),
2394            Some("Numeric")
2395        );
2396        // Applicable casts include the implicit INTEGER → FLOAT widening.
2397        let casts = facts.get("casts").and_then(JsonValue::as_array).unwrap();
2398        assert!(
2399            casts.iter().any(|c| {
2400                c.get("target").and_then(JsonValue::as_str) == Some("FLOAT")
2401                    && c.get("context").and_then(JsonValue::as_str) == Some("implicit")
2402            }),
2403            "casts: {casts:?}"
2404        );
2405        // Applicable operators include arithmetic +.
2406        let operators = facts
2407            .get("operators")
2408            .and_then(JsonValue::as_array)
2409            .unwrap();
2410        assert!(
2411            operators
2412                .iter()
2413                .any(|o| o.get("symbol").and_then(JsonValue::as_str) == Some("+")),
2414            "operators: {operators:?}"
2415        );
2416    }
2417
2418    #[test]
2419    fn tools_call_type_of_infers_type_from_literal_value() {
2420        let mut srv = make_server();
2421        let result = call_type_of(&mut srv, r#"{"value":true}"#);
2422        let facts = type_of_result_json(&result);
2423        assert_eq!(
2424            facts.get("canonical_type").and_then(JsonValue::as_str),
2425            Some("BOOLEAN")
2426        );
2427    }
2428
2429    #[test]
2430    fn tools_call_type_of_unknown_name_is_error() {
2431        let mut srv = make_server();
2432        let result = call_type_of(&mut srv, r#"{"type":"frobnicate"}"#);
2433        assert_eq!(
2434            result.get("isError").and_then(JsonValue::as_bool),
2435            Some(true)
2436        );
2437        let text = result
2438            .get("content")
2439            .and_then(JsonValue::as_array)
2440            .and_then(|content| content.first())
2441            .and_then(|item| item.get("text"))
2442            .and_then(JsonValue::as_str)
2443            .expect("error text");
2444        assert!(text.contains("frobnicate"), "text: {text}");
2445    }
2446
2447    #[test]
2448    fn tools_call_type_of_requires_an_argument() {
2449        let mut srv = make_server();
2450        let result = call_type_of(&mut srv, r#"{}"#);
2451        assert_eq!(
2452            result.get("isError").and_then(JsonValue::as_bool),
2453            Some(true)
2454        );
2455    }
2456
2457    #[test]
2458    fn tools_call_reddb_ask_returns_canonical_citation_envelope() {
2459        let _guard = ASK_ENV_LOCK.lock().expect("env lock");
2460        let stub = AskStub::start();
2461        let _api_base = EnvVarGuard::set(
2462            "REDDB_OLLAMA_API_BASE",
2463            &format!("http://{}/v1", stub.addr()),
2464        );
2465
2466        let srv = make_server();
2467        srv.tool_query(&parse_json(
2468            r#"{"sql":"CREATE TABLE travel (id INTEGER, passport TEXT, notes TEXT)"}"#,
2469        ))
2470        .expect("ddl ok");
2471        srv.tool_query(&parse_json(
2472            r#"{"sql":"INSERT INTO travel (id, passport, notes) VALUES (1, 'PT-002', 'incident FDD-12313 escalated')"}"#,
2473        ))
2474        .expect("insert ok");
2475
2476        let params = parse_json(
2477            r#"{
2478                "name": "reddb.ask",
2479                "arguments": {
2480                    "question": "passport FDD-12313",
2481                    "options": {
2482                        "strict": false,
2483                        "using": "ollama",
2484                        "model": "mock-ask",
2485                        "limit": 1,
2486                        "min_score": 0,
2487                        "depth": 0,
2488                        "temperature": 0,
2489                        "seed": 0,
2490                        "cache": { "ttl": "5m" }
2491                    }
2492                }
2493            }"#,
2494        );
2495
2496        let response = srv.handle_tools_call(Some(&JsonValue::Number(1.0)), Some(&params));
2497        let parsed = parse_json(&response);
2498        let result = parsed.get("result").expect("result");
2499        assert_ne!(
2500            result.get("isError").and_then(JsonValue::as_bool),
2501            Some(true),
2502            "response: {response}"
2503        );
2504        let text = result
2505            .get("content")
2506            .and_then(JsonValue::as_array)
2507            .and_then(|content| content.first())
2508            .and_then(|item| item.get("text"))
2509            .and_then(JsonValue::as_str)
2510            .expect("tool text");
2511        let envelope = parse_json(text);
2512
2513        assert_eq!(
2514            envelope.get("answer").and_then(JsonValue::as_str),
2515            Some("FDD-12313 escalated [^1].")
2516        );
2517        assert_eq!(
2518            envelope.get("provider").and_then(JsonValue::as_str),
2519            Some("ollama")
2520        );
2521        assert_eq!(
2522            envelope.get("model").and_then(JsonValue::as_str),
2523            Some("mock-ask")
2524        );
2525        assert_eq!(
2526            envelope.get("cache_hit").and_then(JsonValue::as_bool),
2527            Some(false)
2528        );
2529        assert!(envelope
2530            .get("sources_flat")
2531            .and_then(JsonValue::as_array)
2532            .is_some());
2533        assert!(envelope
2534            .get("citations")
2535            .and_then(JsonValue::as_array)
2536            .is_some());
2537        assert!(envelope
2538            .get("validation")
2539            .and_then(JsonValue::as_object)
2540            .is_some());
2541        assert!(
2542            envelope.get("rows").is_none(),
2543            "ASK must not be row-wrapped: {text}"
2544        );
2545    }
2546
2547    #[test]
2548    fn tool_query_without_params_keeps_legacy_path() {
2549        let srv = make_server();
2550        let args = parse_json(r#"{"sql":"SELECT 1 AS one"}"#);
2551        let out = srv.tool_query(&args).expect("query ok");
2552        assert!(out.contains("\"one\""), "expected 'one' column in {out}");
2553    }
2554
2555    #[test]
2556    fn tool_query_binds_int_and_text_params() {
2557        let srv = make_server();
2558        srv.tool_query(&parse_json(
2559            r#"{"sql":"CREATE TABLE mcpp (id INTEGER, name TEXT)"}"#,
2560        ))
2561        .expect("ddl ok");
2562        srv.tool_query(&parse_json(
2563            r#"{"sql":"INSERT INTO mcpp (id, name) VALUES (1, 'Alice')"}"#,
2564        ))
2565        .expect("insert 1");
2566        srv.tool_query(&parse_json(
2567            r#"{"sql":"INSERT INTO mcpp (id, name) VALUES (2, 'Bob')"}"#,
2568        ))
2569        .expect("insert 2");
2570
2571        let out = srv
2572            .tool_query(&parse_json(
2573                r#"{"sql":"SELECT * FROM mcpp WHERE id = $1 AND name = $2","params":[1,"Alice"]}"#,
2574            ))
2575            .expect("query with params ok");
2576        assert!(out.contains("Alice"), "expected Alice in {out}");
2577        assert!(!out.contains("Bob"), "Bob must not match: {out}");
2578    }
2579
2580    #[test]
2581    fn tool_query_params_must_be_array() {
2582        let srv = make_server();
2583        let err = srv
2584            .tool_query(&parse_json(
2585                r#"{"sql":"SELECT 1","params":{"not":"array"}}"#,
2586            ))
2587            .expect_err("must reject non-array params");
2588        assert!(err.contains("array"), "got {err}");
2589    }
2590
2591    #[test]
2592    fn tool_query_param_arity_mismatch_surfaces_error() {
2593        let srv = make_server();
2594        srv.tool_query(&parse_json(r#"{"sql":"CREATE TABLE mcpa (id INTEGER)"}"#))
2595            .expect("ddl ok");
2596        let err = srv
2597            .tool_query(&parse_json(
2598                r#"{"sql":"SELECT * FROM mcpa WHERE id = $1","params":[1,2]}"#,
2599            ))
2600            .expect_err("arity mismatch");
2601        assert!(
2602            err.contains("number of parameters") || err.contains("expects"),
2603            "got {err}"
2604        );
2605    }
2606
2607    #[test]
2608    fn tool_query_vector_param_binds_into_search_similar() {
2609        let srv = make_server();
2610        let out = srv.tool_query(&parse_json(
2611            r#"{"sql":"SEARCH SIMILAR $1 COLLECTION mcpv LIMIT 5","params":[[0.1,0.2,0.3]]}"#,
2612        ));
2613        // The collection doesn't exist; we only need to confirm the
2614        // param-bind path runs (i.e. the error reflects runtime semantics,
2615        // not a `$N` placeholder being unresolved).
2616        if let Err(e) = out {
2617            assert!(
2618                !e.contains("placeholder") && !e.contains("Parameter"),
2619                "param did not bind: {e}"
2620            );
2621        }
2622    }
2623
2624    // ------------------------------------------------------------------
2625    // RQL validate / explain tools (ADR 0061, #1317), exercised at the
2626    // JSON-RPC tools/call seam.
2627    // ------------------------------------------------------------------
2628
2629    fn call_tool(srv: &McpServer, name: &str, rql: &str) -> JsonValue {
2630        let params = parse_json(
2631            &json_to_string(&{
2632                let mut p = Map::new();
2633                p.insert("name".to_string(), JsonValue::String(name.to_string()));
2634                let mut args = Map::new();
2635                args.insert("rql".to_string(), JsonValue::String(rql.to_string()));
2636                p.insert("arguments".to_string(), JsonValue::Object(args));
2637                JsonValue::Object(p)
2638            })
2639            .expect("serialize params"),
2640        );
2641        let response = srv.handle_tools_call(Some(&JsonValue::Number(1.0)), Some(&params));
2642        parse_json(&response)
2643    }
2644
2645    fn tool_result_text(parsed: &JsonValue) -> String {
2646        parsed
2647            .get("result")
2648            .and_then(|r| r.get("content"))
2649            .and_then(JsonValue::as_array)
2650            .and_then(|content| content.first())
2651            .and_then(|item| item.get("text"))
2652            .and_then(JsonValue::as_str)
2653            .expect("tool text")
2654            .to_string()
2655    }
2656
2657    #[test]
2658    fn tools_list_registers_rql_validate_and_explain() {
2659        let srv = make_server();
2660        let response = srv.handle_tools_list(Some(&JsonValue::Number(1.0)));
2661        let parsed = parse_json(&response);
2662        let tools = parsed
2663            .get("result")
2664            .and_then(|result| result.get("tools"))
2665            .and_then(JsonValue::as_array)
2666            .expect("tools array");
2667        let names: Vec<&str> = tools
2668            .iter()
2669            .filter_map(|t| t.get("name").and_then(JsonValue::as_str))
2670            .collect();
2671        assert!(names.contains(&"reddb_rql_validate"), "{names:?}");
2672        assert!(names.contains(&"reddb_rql_explain"), "{names:?}");
2673    }
2674
2675    #[test]
2676    fn tools_call_rql_validate_accepts_valid_query() {
2677        let srv = make_server();
2678        let parsed = call_tool(&srv, "reddb_rql_validate", "SELECT * FROM users");
2679        let result = parsed.get("result").expect("result");
2680        assert_ne!(
2681            result.get("isError").and_then(JsonValue::as_bool),
2682            Some(true)
2683        );
2684        let envelope = parse_json(&tool_result_text(&parsed));
2685        assert_eq!(
2686            envelope.get("valid").and_then(JsonValue::as_bool),
2687            Some(true)
2688        );
2689        assert_eq!(
2690            envelope.get("statement").and_then(JsonValue::as_str),
2691            Some("Table")
2692        );
2693    }
2694
2695    #[test]
2696    fn tools_call_rql_validate_reports_structured_error() {
2697        let srv = make_server();
2698        let parsed = call_tool(&srv, "reddb_rql_validate", "SELECT * FROM");
2699        let envelope = parse_json(&tool_result_text(&parsed));
2700        assert_eq!(
2701            envelope.get("valid").and_then(JsonValue::as_bool),
2702            Some(false)
2703        );
2704        let error = envelope.get("error").expect("structured error");
2705        assert!(error
2706            .get("message")
2707            .and_then(JsonValue::as_str)
2708            .is_some_and(|m| !m.is_empty()));
2709        assert!(error.get("line").and_then(JsonValue::as_f64).is_some());
2710        assert!(error
2711            .get("kind")
2712            .and_then(JsonValue::as_str)
2713            .is_some_and(|k| !k.is_empty()));
2714    }
2715
2716    #[test]
2717    fn tools_call_rql_explain_returns_ast_and_plan() {
2718        let srv = make_server();
2719        let parsed = call_tool(
2720            &srv,
2721            "reddb_rql_explain",
2722            "SELECT * FROM users WHERE id = 1",
2723        );
2724        let envelope = parse_json(&tool_result_text(&parsed));
2725        assert_eq!(
2726            envelope
2727                .get("validation")
2728                .and_then(|v| v.get("valid"))
2729                .and_then(JsonValue::as_bool),
2730            Some(true)
2731        );
2732        assert!(envelope.get("ast").and_then(JsonValue::as_str).is_some());
2733        assert!(envelope
2734            .get("optimized_ast")
2735            .and_then(JsonValue::as_str)
2736            .is_some());
2737        assert!(envelope
2738            .get("applied_passes")
2739            .and_then(JsonValue::as_array)
2740            .is_some());
2741    }
2742
2743    #[test]
2744    fn tools_call_rql_validate_missing_field_errors() {
2745        let srv = make_server();
2746        let params = parse_json(r#"{"name":"reddb_rql_validate","arguments":{}}"#);
2747        let response = srv.handle_tools_call(Some(&JsonValue::Number(1.0)), Some(&params));
2748        let parsed = parse_json(&response);
2749        let result = parsed.get("result").expect("result");
2750        assert_eq!(
2751            result.get("isError").and_then(JsonValue::as_bool),
2752            Some(true)
2753        );
2754    }
2755
2756    fn call_explain_connection(srv: &mut McpServer, uri: &str) -> JsonValue {
2757        let request = parse_json(
2758            &json_to_string(&{
2759                let mut request = Map::new();
2760                request.insert("jsonrpc".to_string(), JsonValue::String("2.0".to_string()));
2761                request.insert("id".to_string(), JsonValue::Number(31.0));
2762                request.insert(
2763                    "method".to_string(),
2764                    JsonValue::String("tools/call".to_string()),
2765                );
2766
2767                let mut args = Map::new();
2768                args.insert("uri".to_string(), JsonValue::String(uri.to_string()));
2769
2770                let mut params = Map::new();
2771                params.insert(
2772                    "name".to_string(),
2773                    JsonValue::String("reddb_explain_connection".to_string()),
2774                );
2775                params.insert("arguments".to_string(), JsonValue::Object(args));
2776                request.insert("params".to_string(), JsonValue::Object(params));
2777                JsonValue::Object(request)
2778            })
2779            .expect("serialize request"),
2780        );
2781        let response = srv.handle_message(&request).expect("response");
2782        let parsed = parse_json(&response);
2783        let result = parsed.get("result").expect("result");
2784        assert_ne!(
2785            result.get("isError").and_then(JsonValue::as_bool),
2786            Some(true),
2787            "tool returned error: {parsed:?}"
2788        );
2789        parse_json(&tool_result_text(&parsed))
2790    }
2791
2792    #[test]
2793    fn tools_call_explain_connection_maps_supported_schemes() {
2794        let mut srv = make_server();
2795        for (uri, mode, transport, topology) in [
2796            ("memory://", "embedded", "memory", "ephemeral"),
2797            (
2798                "file:///tmp/reddb/data.rdb",
2799                "embedded",
2800                "filesystem",
2801                "persisted",
2802            ),
2803            ("red://db.example:5050", "remote", "redwire", "single"),
2804            ("reds://db.example", "remote", "redwire_tls", "single"),
2805            ("grpc://db.example", "remote", "grpc", "single"),
2806            ("http://db.example", "remote", "http", "single"),
2807            ("https://db.example", "remote", "https", "single"),
2808        ] {
2809            let envelope = call_explain_connection(&mut srv, uri);
2810            assert_eq!(envelope.get("uri").and_then(JsonValue::as_str), Some(uri));
2811            assert_eq!(
2812                envelope.get("mode").and_then(JsonValue::as_str),
2813                Some(mode),
2814                "{uri}: {envelope:?}"
2815            );
2816            assert_eq!(
2817                envelope.get("transport").and_then(JsonValue::as_str),
2818                Some(transport),
2819                "{uri}: {envelope:?}"
2820            );
2821            assert_eq!(
2822                envelope.get("topology").and_then(JsonValue::as_str),
2823                Some(topology),
2824                "{uri}: {envelope:?}"
2825            );
2826        }
2827
2828        let cluster = call_explain_connection(&mut srv, "grpc://primary,replica?route=primary");
2829        assert_eq!(
2830            cluster.get("topology").and_then(JsonValue::as_str),
2831            Some("primary_replica")
2832        );
2833        assert_eq!(
2834            cluster.get("transport").and_then(JsonValue::as_str),
2835            Some("grpc")
2836        );
2837        assert_eq!(
2838            cluster
2839                .get("target")
2840                .and_then(|target| target.get("force_primary"))
2841                .and_then(JsonValue::as_bool),
2842            Some(true)
2843        );
2844    }
2845
2846    struct EnvVarGuard {
2847        name: &'static str,
2848        previous: Option<String>,
2849    }
2850
2851    impl EnvVarGuard {
2852        fn set(name: &'static str, value: &str) -> Self {
2853            let previous = std::env::var(name).ok();
2854            std::env::set_var(name, value);
2855            Self { name, previous }
2856        }
2857    }
2858
2859    impl Drop for EnvVarGuard {
2860        fn drop(&mut self) {
2861            if let Some(value) = self.previous.take() {
2862                std::env::set_var(self.name, value);
2863            } else {
2864                std::env::remove_var(self.name);
2865            }
2866        }
2867    }
2868
2869    struct AskStub {
2870        addr: SocketAddr,
2871        shutdown: Arc<AtomicBool>,
2872        handle: Option<JoinHandle<()>>,
2873    }
2874
2875    impl AskStub {
2876        fn start() -> Self {
2877            let listener = TcpListener::bind("127.0.0.1:0").expect("stub bind");
2878            listener
2879                .set_nonblocking(true)
2880                .expect("nonblocking listener");
2881            let addr = listener.local_addr().expect("local addr");
2882            let shutdown = Arc::new(AtomicBool::new(false));
2883            let server_shutdown = Arc::clone(&shutdown);
2884            let handle = thread::spawn(move || {
2885                while !server_shutdown.load(Ordering::Relaxed) {
2886                    match listener.accept() {
2887                        Ok((mut stream, _)) => {
2888                            let request = read_stub_request(&mut stream);
2889                            if request.contains("/embeddings") {
2890                                write_json_response(
2891                                    &mut stream,
2892                                    r#"{"model":"mock-embedding","data":[{"index":0,"embedding":[1,0,0]}],"usage":{"prompt_tokens":3,"total_tokens":3}}"#,
2893                                );
2894                            } else {
2895                                write_json_response(
2896                                    &mut stream,
2897                                    r#"{"model":"mock-ask","choices":[{"message":{"role":"assistant","content":"FDD-12313 escalated [^1]."},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":4,"total_tokens":14}}"#,
2898                                );
2899                            }
2900                        }
2901                        Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
2902                            thread::sleep(Duration::from_millis(1));
2903                        }
2904                        Err(_) => break,
2905                    }
2906                }
2907            });
2908
2909            Self {
2910                addr,
2911                shutdown,
2912                handle: Some(handle),
2913            }
2914        }
2915
2916        fn addr(&self) -> SocketAddr {
2917            self.addr
2918        }
2919    }
2920
2921    impl Drop for AskStub {
2922        fn drop(&mut self) {
2923            self.shutdown.store(true, Ordering::Relaxed);
2924            let _ = TcpStream::connect(self.addr);
2925            if let Some(handle) = self.handle.take() {
2926                let _ = handle.join();
2927            }
2928        }
2929    }
2930
2931    fn read_stub_request(stream: &mut TcpStream) -> String {
2932        let _ = stream.set_read_timeout(Some(Duration::from_millis(100)));
2933        let mut buffer = [0_u8; 4096];
2934        let count = stream.read(&mut buffer).unwrap_or(0);
2935        String::from_utf8_lossy(&buffer[..count]).into_owned()
2936    }
2937
2938    fn write_json_response(stream: &mut TcpStream, body: &str) {
2939        let response = format!(
2940            "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
2941            body.len()
2942        );
2943        stream
2944            .write_all(response.as_bytes())
2945            .expect("write stub response");
2946    }
2947}