Skip to main content

dbmcp_sqlite/tools/
explain_query.rs

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