Skip to main content

dbmcp_sqlite/tools/
read_query.rs

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