Skip to main content

dbmcp_postgres/tools/
explain_query.rs

1//! MCP tool: `explainQuery`.
2
3use std::borrow::Cow;
4
5use dbmcp_server::types::{ExplainQueryRequest, QueryResponse};
6use dbmcp_sql::Connection as _;
7use dbmcp_sql::SqlError;
8use dbmcp_sql::sanitize::validate_ident;
9use dbmcp_sql::validation::validate_read_only;
10use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
11use rmcp::model::{ErrorData, ToolAnnotations};
12
13use crate::PostgresHandler;
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 JSON 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<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 [`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::PostgreSqlDialect {})?;
108        }
109
110        let database = database
111            .as_deref()
112            .map(str::trim)
113            .filter(|s| !s.is_empty())
114            .map(validate_ident)
115            .transpose()?;
116
117        let explain_sql = if analyze {
118            format!("EXPLAIN (ANALYZE, FORMAT JSON) {query}")
119        } else {
120            format!("EXPLAIN (FORMAT JSON) {query}")
121        };
122
123        let rows = self.connection.fetch_json(&explain_sql, database).await?;
124
125        Ok(QueryResponse { rows })
126    }
127}