Skip to main content

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