Skip to main content

database_mcp_mysql/tools/
explain_query.rs

1//! MCP tool: `explainQuery`.
2
3use std::borrow::Cow;
4
5use database_mcp_server::types::{ExplainQueryRequest, QueryResponse};
6use database_mcp_sql::Connection as _;
7use database_mcp_sql::SqlError;
8use database_mcp_sql::sanitize::validate_ident;
9use database_mcp_sql::validation::validate_read_only;
10use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
11use rmcp::model::{ErrorData, ToolAnnotations};
12
13use crate::MysqlHandler;
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.
22
23<usecase>
24Use when:
25- A query runs slowly and you need to understand why
26- Investigating performance bottlenecks
27- Planning index creation to optimize queries
28- Analyzing join methods, table scan strategies, and sort operations
29</usecase>
30
31<when_not_to_use>
32- Running actual queries → use readQuery or writeQuery
33- Checking table structure → use getTableSchema
34</when_not_to_use>
35
36<examples>
37✓ "Why is my SELECT on orders slow?" → explainQuery(query="SELECT ...")
38✓ "Should I add an index?" → explainQuery with analyze=true
39✗ "Run this SELECT" → use readQuery
40</examples>
41
42<safety>
43Set `analyze` to true for actual execution statistics (EXPLAIN ANALYZE).
44IMPORTANT: EXPLAIN ANALYZE actually executes the query! In read-only mode, only read-only statements are allowed with analyze.
45When analyze is false, returns EXPLAIN FORMAT=JSON output without executing.
46</safety>
47
48<what_it_returns>
49A JSON array of execution plan rows showing access methods, join types, row estimates, and costs.
50</what_it_returns>"#;
51}
52
53impl ToolBase for ExplainQueryTool {
54    type Parameter = ExplainQueryRequest;
55    type Output = QueryResponse;
56    type Error = ErrorData;
57
58    fn name() -> Cow<'static, str> {
59        Self::NAME.into()
60    }
61
62    fn title() -> Option<String> {
63        Some(Self::TITLE.into())
64    }
65
66    fn description() -> Option<Cow<'static, str>> {
67        Some(Self::DESCRIPTION.into())
68    }
69
70    fn annotations() -> Option<ToolAnnotations> {
71        Some(
72            ToolAnnotations::new()
73                .read_only(true)
74                .destructive(false)
75                .idempotent(true)
76                .open_world(true),
77        )
78    }
79}
80
81impl AsyncTool<MysqlHandler> for ExplainQueryTool {
82    async fn invoke(handler: &MysqlHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
83        Ok(handler.explain_query(params).await?)
84    }
85}
86
87impl MysqlHandler {
88    /// Returns the execution plan for a query.
89    ///
90    /// When `analyze` is true and read-only mode is enabled, the inner
91    /// query is validated to be read-only before executing.
92    ///
93    /// # Errors
94    ///
95    /// Returns [`SqlError::ReadOnlyViolation`] if `analyze` is true,
96    /// read-only mode is enabled, and the query is a write statement.
97    /// Returns [`SqlError::Query`] if the backend reports an error.
98    pub async fn explain_query(
99        &self,
100        ExplainQueryRequest {
101            database,
102            query,
103            analyze,
104        }: ExplainQueryRequest,
105    ) -> Result<QueryResponse, SqlError> {
106        if analyze && self.config.read_only {
107            let _ = validate_read_only(&query, &sqlparser::dialect::MySqlDialect {})?;
108        }
109
110        let db = Some(database.trim()).filter(|s| !s.is_empty());
111        if let Some(name) = &db {
112            validate_ident(name)?;
113        }
114
115        let explain_sql = if analyze {
116            format!("EXPLAIN ANALYZE {query}")
117        } else {
118            format!("EXPLAIN FORMAT=JSON {query}")
119        };
120
121        let rows = self.connection.fetch_json(explain_sql.as_str(), db).await?;
122        Ok(QueryResponse { rows })
123    }
124}