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