database_mcp_sqlite/tools/
explain_query.rs1use std::borrow::Cow;
4
5use database_mcp_server::AppError;
6use database_mcp_server::types::QueryResponse;
7use database_mcp_sql::Connection as _;
8use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
9use rmcp::model::{ErrorData, ToolAnnotations};
10use serde_json::Value;
11
12use crate::SqliteHandler;
13use crate::types::ExplainQueryRequest;
14
15pub(crate) struct ExplainQueryTool;
17
18impl ExplainQueryTool {
19 const NAME: &'static str = "explain_query";
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 read_query — it provides structured output via EXPLAIN QUERY PLAN.
22
23<usecase>
24Use when:
25- A query runs slowly and you need to understand why
26- Understanding how SQLite will scan tables and use indexes
27- Deciding whether to add an index
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✓ "How will SQLite execute this join?" → explain_query
38✗ "Run this SELECT" → use read_query
39</examples>
40
41<what_it_returns>
42A JSON array of EXPLAIN QUERY PLAN rows showing how SQLite will scan tables, use indexes, and order operations.
43</what_it_returns>"#;
44}
45
46impl ToolBase for ExplainQueryTool {
47 type Parameter = ExplainQueryRequest;
48 type Output = QueryResponse;
49 type Error = ErrorData;
50
51 fn name() -> Cow<'static, str> {
52 Self::NAME.into()
53 }
54
55 fn title() -> Option<String> {
56 Some(Self::TITLE.into())
57 }
58
59 fn description() -> Option<Cow<'static, str>> {
60 Some(Self::DESCRIPTION.into())
61 }
62
63 fn annotations() -> Option<ToolAnnotations> {
64 Some(
65 ToolAnnotations::new()
66 .read_only(true)
67 .destructive(false)
68 .idempotent(true)
69 .open_world(true),
70 )
71 }
72}
73
74impl AsyncTool<SqliteHandler> for ExplainQueryTool {
75 async fn invoke(handler: &SqliteHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
76 Ok(handler.explain_query(¶ms).await?)
77 }
78}
79
80impl SqliteHandler {
81 pub async fn explain_query(&self, request: &ExplainQueryRequest) -> Result<QueryResponse, AppError> {
90 let explain_sql = format!("EXPLAIN QUERY PLAN {}", request.query);
91 let rows = self.connection.fetch(explain_sql.as_str(), None).await?;
92 Ok(QueryResponse {
93 rows: Value::Array(rows),
94 })
95 }
96}