Skip to main content

database_mcp_sqlite/tools/
read_query.rs

1//! MCP tool: `readQuery`.
2
3use std::borrow::Cow;
4
5use database_mcp_server::pagination::Pager;
6use database_mcp_server::types::ReadQueryResponse;
7
8use database_mcp_sql::Connection as _;
9use database_mcp_sql::SqlError;
10use database_mcp_sql::StatementKind;
11use database_mcp_sql::pagination::with_limit_offset;
12use database_mcp_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
19/// Marker type for the `readQuery` MCP tool.
20pub(crate) struct ReadQueryTool;
21
22impl ReadQueryTool {
23    const NAME: &'static str = "readQuery";
24    const TITLE: &'static str = "Read Query";
25    const DESCRIPTION: &'static str = r#"Execute a read-only SQL query. Allowed statements: SELECT, EXPLAIN.
26
27<usecase>
28Use when:
29- Querying data from tables (SELECT with WHERE, JOIN, GROUP BY, etc.)
30- Aggregations: COUNT, SUM, AVG, GROUP BY, HAVING
31- Checking data existence or counts
32</usecase>
33
34<when_not_to_use>
35- Data changes (INSERT, UPDATE, DELETE) → use writeQuery
36- Query performance analysis → use explainQuery
37- Discovering tables or columns → use listTables or getTableSchema
38</when_not_to_use>
39
40<examples>
41✓ "SELECT * FROM users WHERE status = 'active'"
42✓ "SELECT COUNT(*) FROM orders GROUP BY region"
43✗ "INSERT INTO users ..." → use writeQuery
44✗ "EXPLAIN SELECT ..." → use explainQuery for structured analysis
45</examples>
46
47<what_it_returns>
48A JSON array of row objects, each keyed by column name.
49</what_it_returns>
50
51<pagination>
52`SELECT` results are paginated. Pass the prior response's `nextCursor` as `cursor` to fetch the next page. `EXPLAIN` returns a single page and ignores `cursor`.
53</pagination>"#;
54}
55
56impl ToolBase for ReadQueryTool {
57    type Parameter = ReadQueryRequest;
58    type Output = ReadQueryResponse;
59    type Error = ErrorData;
60
61    fn name() -> Cow<'static, str> {
62        Self::NAME.into()
63    }
64
65    fn title() -> Option<String> {
66        Some(Self::TITLE.into())
67    }
68
69    fn description() -> Option<Cow<'static, str>> {
70        Some(Self::DESCRIPTION.into())
71    }
72
73    fn annotations() -> Option<ToolAnnotations> {
74        Some(
75            ToolAnnotations::new()
76                .read_only(true)
77                .destructive(false)
78                .idempotent(true)
79                .open_world(true),
80        )
81    }
82}
83
84impl AsyncTool<SqliteHandler> for ReadQueryTool {
85    async fn invoke(handler: &SqliteHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
86        Ok(handler.read_query(params).await?)
87    }
88}
89
90impl SqliteHandler {
91    /// Executes a read-only SQL query, paginating `SELECT` result rows.
92    ///
93    /// Validates that the query is read-only, then dispatches on the
94    /// classified [`StatementKind`]: `Select` is wrapped in a subquery with
95    /// a server-controlled `LIMIT`/`OFFSET`; `NonSelect` (`EXPLAIN` under
96    /// the `SQLite` dialect) is executed as-is and returned in a single
97    /// page. A malformed `cursor` is rejected by the serde deserializer
98    /// before this method is called, producing JSON-RPC `-32602`.
99    ///
100    /// # Errors
101    ///
102    /// Returns [`SqlError::ReadOnlyViolation`] if the query is not
103    /// read-only, or [`SqlError::Query`] if the backend reports an error.
104    pub async fn read_query(
105        &self,
106        ReadQueryRequest { query, cursor }: ReadQueryRequest,
107    ) -> Result<ReadQueryResponse, SqlError> {
108        let kind = validate_read_only(&query, &sqlparser::dialect::SQLiteDialect {})?;
109
110        match kind {
111            StatementKind::Select => {
112                let pager = Pager::new(cursor, self.config.page_size);
113                let wrapped = with_limit_offset(&query, pager.limit(), pager.offset());
114                let rows = self.connection.fetch_json(wrapped.as_str(), None).await?;
115                let (rows, next_cursor) = pager.finalize(rows);
116                Ok(ReadQueryResponse { rows, next_cursor })
117            }
118            StatementKind::NonSelect => {
119                let rows = self.connection.fetch_json(query.as_str(), None).await?;
120                Ok(ReadQueryResponse {
121                    rows,
122                    next_cursor: None,
123                })
124            }
125        }
126    }
127}