Skip to main content

database_mcp_postgres/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::{ExplainQueryRequest, QueryResponse};
7use database_mcp_sql::Connection as _;
8use database_mcp_sql::validation::validate_read_only_with_dialect;
9use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
10use rmcp::model::{ErrorData, ToolAnnotations};
11use serde_json::Value;
12
13use crate::PostgresHandler;
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 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 read_query — it provides structured JSON output. Accepts an optional `database_name` to explain queries against a different database.
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 read_query or write_query
33- Checking table structure → use get_table_schema
34</when_not_to_use>
35
36<examples>
37✓ "Why is my SELECT on orders slow?" → explain_query(query="SELECT ...")
38✓ "Should I add an index?" → explain_query with analyze=true
39✗ "Run this SELECT" → use read_query
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<PostgresHandler> for ExplainQueryTool {
82    async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
83        Ok(handler.explain_query(&params).await?)
84    }
85}
86
87impl PostgresHandler {
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 [`AppError::ReadOnlyViolation`] if `analyze` is true,
96    /// read-only mode is enabled, and the query is a write statement.
97    /// Returns [`AppError::Query`] if the backend reports an error.
98    pub async fn explain_query(&self, request: &ExplainQueryRequest) -> Result<QueryResponse, AppError> {
99        if request.analyze && self.config.read_only {
100            validate_read_only_with_dialect(&request.query, &sqlparser::dialect::PostgreSqlDialect {})?;
101        }
102
103        let explain_sql = if request.analyze {
104            format!("EXPLAIN (ANALYZE, FORMAT JSON) {}", request.query)
105        } else {
106            format!("EXPLAIN (FORMAT JSON) {}", request.query)
107        };
108
109        let rows = self
110            .connection
111            .fetch(&explain_sql, Some(&request.database_name))
112            .await?;
113
114        Ok(QueryResponse {
115            rows: Value::Array(rows),
116        })
117    }
118}