dbmcp_postgres/tools/
explain_query.rs1use std::borrow::Cow;
4
5use dbmcp_server::types::{ExplainQueryRequest, QueryResponse};
6use dbmcp_sql::Connection as _;
7use dbmcp_sql::SqlError;
8use dbmcp_sql::validation::validate_read_only;
9use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
10use rmcp::model::{ErrorData, ToolAnnotations};
11
12use crate::PostgresHandler;
13
14pub(crate) struct ExplainQueryTool;
16
17impl ExplainQueryTool {
18 const NAME: &'static str = "explainQuery";
19 const TITLE: &'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 readQuery — it provides structured JSON output.
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 readQuery or writeQuery
32- Checking table structure → use listTables(detailed=true)
33</when_not_to_use>
34
35<examples>
36✓ "Why is my SELECT on orders slow?" → explainQuery(query="SELECT ...")
37✓ "Should I add an index?" → explainQuery with analyze=true
38✗ "Run this SELECT" → use readQuery
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 title() -> Option<String> {
62 Some(Self::TITLE.into())
63 }
64
65 fn description() -> Option<Cow<'static, str>> {
66 Some(Self::DESCRIPTION.into())
67 }
68
69 fn annotations() -> Option<ToolAnnotations> {
70 Some(
71 ToolAnnotations::new()
72 .read_only(true)
73 .destructive(false)
74 .idempotent(true)
75 .open_world(true),
76 )
77 }
78}
79
80impl AsyncTool<PostgresHandler> for ExplainQueryTool {
81 async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
82 Ok(handler.explain_query(params).await?)
83 }
84}
85
86impl PostgresHandler {
87 pub async fn explain_query(
98 &self,
99 ExplainQueryRequest {
100 database,
101 query,
102 analyze,
103 }: ExplainQueryRequest,
104 ) -> Result<QueryResponse, SqlError> {
105 if analyze && self.config.read_only {
106 let _ = validate_read_only(&query, &sqlparser::dialect::PostgreSqlDialect {})?;
107 }
108
109 let database = database.as_deref().map(str::trim).filter(|s| !s.is_empty());
110
111 let explain_sql = if analyze {
112 format!("EXPLAIN (ANALYZE, FORMAT JSON) {query}")
113 } else {
114 format!("EXPLAIN (FORMAT JSON) {query}")
115 };
116
117 let rows = self.connection.fetch_json(explain_sql.as_str(), database).await?;
118
119 Ok(QueryResponse { rows })
120 }
121}