database_mcp_postgres/tools/
explain_query.rs1use 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::PostgresHandler;
14
15pub(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. Accepts an optional `database` 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 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 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 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, FORMAT JSON) {query}")
117 } else {
118 format!("EXPLAIN (FORMAT JSON) {query}")
119 };
120
121 let rows = self.connection.fetch_json(&explain_sql, db).await?;
122
123 Ok(QueryResponse { rows })
124 }
125}