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