Skip to main content

dbmcp_sqlite/tools/
read_query.rs

1//! MCP tool: `readQuery`.
2
3use std::borrow::Cow;
4
5use dbmcp_pii::MaybeRedact as _;
6use dbmcp_server::pagination::Pager;
7use dbmcp_server::types::ReadQueryResponse;
8
9use dbmcp_sql::Connection as _;
10use dbmcp_sql::StatementKind;
11use dbmcp_sql::pagination::with_limit_offset;
12use dbmcp_sql::validation::validate_read_only;
13use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
14use rmcp::model::{ErrorData, ToolAnnotations};
15
16use crate::SqliteHandler;
17use crate::types::ReadQueryRequest;
18
19const NAME: &str = "readQuery";
20const TITLE: &str = "Read Query";
21const DESCRIPTION: &str = include_str!("../../assets/tools/read_query.md");
22
23/// Marker type for the `readQuery` MCP tool.
24pub(crate) struct ReadQueryTool;
25
26impl ToolBase for ReadQueryTool {
27    type Parameter = ReadQueryRequest;
28    type Output = ReadQueryResponse;
29    type Error = ErrorData;
30
31    fn name() -> Cow<'static, str> {
32        NAME.into()
33    }
34
35    fn title() -> Option<String> {
36        Some(TITLE.into())
37    }
38
39    fn description() -> Option<Cow<'static, str>> {
40        Some(DESCRIPTION.into())
41    }
42
43    fn annotations() -> Option<ToolAnnotations> {
44        Some(
45            ToolAnnotations::new()
46                .read_only(true)
47                .destructive(false)
48                .idempotent(true)
49                .open_world(true),
50        )
51    }
52}
53
54impl AsyncTool<SqliteHandler> for ReadQueryTool {
55    async fn invoke(handler: &SqliteHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
56        handler.read_query(params).await
57    }
58}
59
60impl SqliteHandler {
61    /// Executes a read-only SQL query, paginating `SELECT` result rows.
62    ///
63    /// Validates that the query is read-only, then dispatches on the
64    /// classified [`StatementKind`]: `Select` is wrapped in a subquery with
65    /// a server-controlled `LIMIT`/`OFFSET`; `NonSelect` (`EXPLAIN` under
66    /// the `SQLite` dialect) is executed as-is and returned in a single
67    /// page. A malformed `cursor` is rejected by the serde deserializer
68    /// before this method is called, producing JSON-RPC `-32602`.
69    ///
70    /// # Errors
71    ///
72    /// Returns [`SqlError::ReadOnlyViolation`] if the query is not
73    /// read-only, or [`SqlError::Query`] if the backend reports an error.
74    pub async fn read_query(
75        &self,
76        ReadQueryRequest { query, cursor }: ReadQueryRequest,
77    ) -> Result<ReadQueryResponse, ErrorData> {
78        let kind = validate_read_only(&query, &sqlparser::dialect::SQLiteDialect {})?;
79
80        let (rows, next_cursor) = match kind {
81            StatementKind::Select => {
82                let pager = Pager::new(cursor, self.config.page_size);
83                let wrapped = with_limit_offset(&query, pager.limit(), pager.offset());
84                let rows = self.connection.fetch_json(wrapped.as_str(), None).await?;
85                pager.paginate(rows)
86            }
87            StatementKind::NonSelect => {
88                let rows = self.connection.fetch_json(query.as_str(), None).await?;
89                (rows, None)
90            }
91        };
92        let rows = self.redactor.redact_rows(rows).await?;
93        Ok(ReadQueryResponse { rows, next_cursor })
94    }
95}