database_mcp_postgres/tools/
explain_query.rs1use 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
15pub(crate) struct ExplainQueryTool;
17
18impl ExplainQueryTool {
19 const NAME: &'static str = "explain_query";
20 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.
21
22<usecase>
23Use when:
24- A query runs slowly and you need to understand why
25- Investigating performance bottlenecks
26- Planning index creation to optimize queries
27- Analyzing join methods, table scan strategies, and sort operations
28</usecase>
29
30<when_not_to_use>
31- Running actual queries → use read_query or write_query
32- Checking table structure → use get_table_schema
33</when_not_to_use>
34
35<examples>
36✓ "Why is my SELECT on orders slow?" → explain_query(query="SELECT ...")
37✓ "Should I add an index?" → explain_query with analyze=true
38✗ "Run this SELECT" → use read_query
39</examples>
40
41<safety>
42Set `analyze` to true for actual execution statistics (EXPLAIN ANALYZE).
43IMPORTANT: EXPLAIN ANALYZE actually executes the query! In read-only mode, only read-only statements are allowed with analyze.
44When analyze is false, returns EXPLAIN (FORMAT JSON) output without executing.
45</safety>
46
47<what_it_returns>
48A JSON array of execution plan rows showing access methods, join types, row estimates, and costs.
49</what_it_returns>"#;
50}
51
52impl ToolBase for ExplainQueryTool {
53 type Parameter = ExplainQueryRequest;
54 type Output = QueryResponse;
55 type Error = ErrorData;
56
57 fn name() -> Cow<'static, str> {
58 Self::NAME.into()
59 }
60
61 fn description() -> Option<Cow<'static, str>> {
62 Some(Self::DESCRIPTION.into())
63 }
64
65 fn annotations() -> Option<ToolAnnotations> {
66 Some(
67 ToolAnnotations::new()
68 .read_only(true)
69 .destructive(false)
70 .idempotent(true)
71 .open_world(true),
72 )
73 }
74}
75
76impl AsyncTool<PostgresHandler> for ExplainQueryTool {
77 async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
78 Ok(handler.explain_query(¶ms).await?)
79 }
80}
81
82impl PostgresHandler {
83 pub async fn explain_query(&self, request: &ExplainQueryRequest) -> Result<QueryResponse, AppError> {
94 if request.analyze && self.config.read_only {
95 validate_read_only_with_dialect(&request.query, &sqlparser::dialect::PostgreSqlDialect {})?;
96 }
97
98 let explain_sql = if request.analyze {
99 format!("EXPLAIN (ANALYZE, FORMAT JSON) {}", request.query)
100 } else {
101 format!("EXPLAIN (FORMAT JSON) {}", request.query)
102 };
103
104 let rows = self
105 .connection
106 .fetch(&explain_sql, Some(&request.database_name))
107 .await?;
108
109 Ok(QueryResponse {
110 rows: Value::Array(rows),
111 })
112 }
113}