Skip to main content

database_mcp_sqlite/tools/
explain_query.rs

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