Skip to main content

database_mcp_sqlite/tools/
explain_query.rs

1//! MCP tool: `explain_query`.
2
3use std::borrow::Cow;
4
5use database_mcp_server::AppError;
6use database_mcp_server::types::QueryResponse;
7use database_mcp_sql::Connection as _;
8use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
9use rmcp::model::{ErrorData, ToolAnnotations};
10use serde_json::Value;
11
12use crate::SqliteHandler;
13use crate::types::ExplainQueryRequest;
14
15/// Marker type for the `explain_query` MCP tool.
16pub(crate) struct ExplainQueryTool;
17
18impl ExplainQueryTool {
19    const NAME: &'static str = "explain_query";
20    const DESCRIPTION: &'static str = r#"Return the execution plan for a SQL query to diagnose performance. Use this tool instead of running EXPLAIN directly through read_query — it provides structured output via EXPLAIN QUERY PLAN.
21
22<usecase>
23Use when:
24- A query runs slowly and you need to understand why
25- Understanding how SQLite will scan tables and use indexes
26- Deciding whether to add an index
27</usecase>
28
29<when_not_to_use>
30- Running actual queries → use read_query or write_query
31- Checking table structure → use get_table_schema
32</when_not_to_use>
33
34<examples>
35✓ "Why is my SELECT on orders slow?" → explain_query(query="SELECT ...")
36✓ "How will SQLite execute this join?" → explain_query
37✗ "Run this SELECT" → use read_query
38</examples>
39
40<what_it_returns>
41A JSON array of EXPLAIN QUERY PLAN rows showing how SQLite will scan tables, use indexes, and order operations.
42</what_it_returns>"#;
43}
44
45impl ToolBase for ExplainQueryTool {
46    type Parameter = ExplainQueryRequest;
47    type Output = QueryResponse;
48    type Error = ErrorData;
49
50    fn name() -> Cow<'static, str> {
51        Self::NAME.into()
52    }
53
54    fn description() -> Option<Cow<'static, str>> {
55        Some(Self::DESCRIPTION.into())
56    }
57
58    fn annotations() -> Option<ToolAnnotations> {
59        Some(
60            ToolAnnotations::new()
61                .read_only(true)
62                .destructive(false)
63                .idempotent(true)
64                .open_world(true),
65        )
66    }
67}
68
69impl AsyncTool<SqliteHandler> for ExplainQueryTool {
70    async fn invoke(handler: &SqliteHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
71        Ok(handler.explain_query(&params).await?)
72    }
73}
74
75impl SqliteHandler {
76    /// Returns the execution plan for a query.
77    ///
78    /// Always uses `EXPLAIN QUERY PLAN` — `SQLite` does not support
79    /// `EXPLAIN ANALYZE`.
80    ///
81    /// # Errors
82    ///
83    /// Returns [`AppError::Query`] if the backend reports an error.
84    pub async fn explain_query(&self, request: &ExplainQueryRequest) -> Result<QueryResponse, AppError> {
85        let explain_sql = format!("EXPLAIN QUERY PLAN {}", request.query);
86        let rows = self.connection.fetch(explain_sql.as_str(), None).await?;
87        Ok(QueryResponse {
88            rows: Value::Array(rows),
89        })
90    }
91}