Skip to main content

dbmcp_sqlite/tools/
explain_query.rs

1//! MCP tool: `explainQuery`.
2
3use std::borrow::Cow;
4
5use dbmcp_pii::MaybeRedact as _;
6use dbmcp_server::types::QueryResponse;
7
8use dbmcp_sql::Connection as _;
9use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
10use rmcp::model::{ErrorData, ToolAnnotations};
11
12use crate::SqliteHandler;
13use crate::types::ExplainQueryRequest;
14
15const NAME: &str = "explainQuery";
16const TITLE: &str = "Explain Query";
17const DESCRIPTION: &str = include_str!("../../assets/tools/explain_query.md");
18
19/// Marker type for the `explainQuery` MCP tool.
20pub(crate) struct ExplainQueryTool;
21
22impl ToolBase for ExplainQueryTool {
23    type Parameter = ExplainQueryRequest;
24    type Output = QueryResponse;
25    type Error = ErrorData;
26
27    fn name() -> Cow<'static, str> {
28        NAME.into()
29    }
30
31    fn title() -> Option<String> {
32        Some(TITLE.into())
33    }
34
35    fn description() -> Option<Cow<'static, str>> {
36        Some(DESCRIPTION.into())
37    }
38
39    fn annotations() -> Option<ToolAnnotations> {
40        Some(
41            ToolAnnotations::new()
42                .read_only(true)
43                .destructive(false)
44                .idempotent(true)
45                .open_world(true),
46        )
47    }
48}
49
50impl AsyncTool<SqliteHandler> for ExplainQueryTool {
51    async fn invoke(handler: &SqliteHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
52        handler.explain_query(params).await
53    }
54}
55
56impl SqliteHandler {
57    /// Returns the execution plan for a query.
58    ///
59    /// Always uses `EXPLAIN QUERY PLAN` — `SQLite` does not support
60    /// `EXPLAIN ANALYZE`.
61    ///
62    /// # Errors
63    ///
64    /// Returns [`SqlError::Query`] if the backend reports an error.
65    pub async fn explain_query(
66        &self,
67        ExplainQueryRequest { query }: ExplainQueryRequest,
68    ) -> Result<QueryResponse, ErrorData> {
69        let explain_sql = format!("EXPLAIN QUERY PLAN {query}");
70
71        let rows = self.connection.fetch_json(explain_sql.as_str(), None).await?;
72        let rows = self.redactor.redact_rows(rows).await?;
73
74        Ok(QueryResponse { rows })
75    }
76}