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::timeout::execute_with_timeout;
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;
12use sqlx::postgres::PgRow;
13use sqlx_to_json::RowExt;
14
15use crate::PostgresHandler;
16
17/// Marker type for the `explain_query` MCP tool.
18pub(crate) struct ExplainQueryTool;
19
20impl ExplainQueryTool {
21    const NAME: &'static str = "explain_query";
22    const DESCRIPTION: &'static str = "Return the execution plan for a SQL query.";
23}
24
25impl ToolBase for ExplainQueryTool {
26    type Parameter = ExplainQueryRequest;
27    type Output = QueryResponse;
28    type Error = ErrorData;
29
30    fn name() -> Cow<'static, str> {
31        Self::NAME.into()
32    }
33
34    fn description() -> Option<Cow<'static, str>> {
35        Some(Self::DESCRIPTION.into())
36    }
37
38    fn annotations() -> Option<ToolAnnotations> {
39        Some(
40            ToolAnnotations::new()
41                .read_only(true)
42                .destructive(false)
43                .idempotent(true)
44                .open_world(true),
45        )
46    }
47}
48
49impl AsyncTool<PostgresHandler> for ExplainQueryTool {
50    async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
51        Ok(handler.explain_query(&params).await?)
52    }
53}
54
55impl PostgresHandler {
56    /// Returns the execution plan for a query.
57    ///
58    /// When `analyze` is true and read-only mode is enabled, the inner
59    /// query is validated to be read-only before executing.
60    ///
61    /// # Errors
62    ///
63    /// Returns [`AppError::ReadOnlyViolation`] if `analyze` is true,
64    /// read-only mode is enabled, and the query is a write statement.
65    /// Returns [`AppError::Query`] if the backend reports an error.
66    pub async fn explain_query(&self, request: &ExplainQueryRequest) -> Result<QueryResponse, AppError> {
67        if request.analyze && self.config.read_only {
68            validate_read_only_with_dialect(&request.query, &sqlparser::dialect::PostgreSqlDialect {})?;
69        }
70
71        let pool = self.get_pool(Some(&request.database_name)).await?;
72
73        let explain_sql = if request.analyze {
74            format!("EXPLAIN (ANALYZE, FORMAT JSON) {}", request.query)
75        } else {
76            format!("EXPLAIN (FORMAT JSON) {}", request.query)
77        };
78
79        let rows: Vec<PgRow> = execute_with_timeout(
80            self.config.query_timeout,
81            &explain_sql,
82            sqlx::query(&explain_sql).fetch_all(&pool),
83        )
84        .await?;
85
86        Ok(QueryResponse {
87            rows: Value::Array(rows.iter().map(RowExt::to_json).collect()),
88        })
89    }
90}