Skip to main content

dbmcp_sqlite/tools/
explain_query.rs

1//! MCP tool: `explainQuery`.
2
3use std::borrow::Cow;
4
5use dbmcp_server::types::QueryResponse;
6
7use dbmcp_sql::Connection as _;
8use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
9use rmcp::model::{ErrorData, ToolAnnotations};
10
11use crate::SqliteHandler;
12use crate::types::ExplainQueryRequest;
13
14/// Marker type for the `explainQuery` MCP tool.
15pub(crate) struct ExplainQueryTool;
16
17impl ExplainQueryTool {
18    const NAME: &'static str = "explainQuery";
19    const TITLE: &'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 readQuery — 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 readQuery or writeQuery
31- Checking table structure → use listTables with `detailed: true`
32</when_not_to_use>
33
34<examples>
35✓ "Why is my SELECT on orders slow?" → explainQuery(query="SELECT ...")
36✓ "How will SQLite execute this join?" → explainQuery
37✗ "Run this SELECT" → use readQuery
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 title() -> Option<String> {
55        Some(Self::TITLE.into())
56    }
57
58    fn description() -> Option<Cow<'static, str>> {
59        Some(Self::DESCRIPTION.into())
60    }
61
62    fn annotations() -> Option<ToolAnnotations> {
63        Some(
64            ToolAnnotations::new()
65                .read_only(true)
66                .destructive(false)
67                .idempotent(true)
68                .open_world(true),
69        )
70    }
71}
72
73impl AsyncTool<SqliteHandler> for ExplainQueryTool {
74    async fn invoke(handler: &SqliteHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
75        handler.explain_query(params).await
76    }
77}
78
79impl SqliteHandler {
80    /// Returns the execution plan for a query.
81    ///
82    /// Always uses `EXPLAIN QUERY PLAN` — `SQLite` does not support
83    /// `EXPLAIN ANALYZE`.
84    ///
85    /// # Errors
86    ///
87    /// Returns [`SqlError::Query`] if the backend reports an error.
88    pub async fn explain_query(
89        &self,
90        ExplainQueryRequest { query }: ExplainQueryRequest,
91    ) -> Result<QueryResponse, ErrorData> {
92        let explain_sql = format!("EXPLAIN QUERY PLAN {query}");
93
94        let mut rows = self.connection.fetch_json(explain_sql.as_str(), None).await?;
95        if let Some(r) = &self.redactor {
96            r.apply(&mut rows)?;
97        }
98
99        Ok(QueryResponse { rows })
100    }
101}