Skip to main content

database_mcp_postgres/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::PostgresHandler;
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, EXPLAIN. Accepts an optional `database` to query across databases without reconnecting.
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 configuration parameters (SHOW)
31</usecase>
32
33<when_not_to_use>
34- Data changes (INSERT, UPDATE, DELETE) → use writeQuery
35- Query performance analysis → use explainQuery
36- Discovering tables or columns → use listTables or getTableSchema
37</when_not_to_use>
38
39<examples>
40✓ "SELECT * FROM users WHERE status = 'active'"
41✓ "SELECT COUNT(*) FROM orders GROUP BY region"
42✓ "SHOW server_version"
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. `SHOW` and `EXPLAIN` return a single page and ignore `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<PostgresHandler> for ReadQueryTool {
85    async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
86        Ok(handler.read_query(params).await?)
87    }
88}
89
90impl PostgresHandler {
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` (`SHOW`, `EXPLAIN`
96    /// under the PG 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 {
107            query,
108            database,
109            cursor,
110        }: ReadQueryRequest,
111    ) -> Result<ReadQueryResponse, SqlError> {
112        let kind = validate_read_only(&query, &sqlparser::dialect::PostgreSqlDialect {})?;
113        let db = Some(database.trim()).filter(|s| !s.is_empty());
114        if let Some(name) = db {
115            validate_ident(name)?;
116        }
117
118        match kind {
119            StatementKind::Select => {
120                let pager = Pager::new(cursor, self.config.page_size);
121                let wrapped = with_limit_offset(&query, pager.limit(), pager.offset());
122                let rows = self.connection.fetch_json(wrapped.as_str(), db).await?;
123                let (rows, next_cursor) = pager.finalize(rows);
124                Ok(ReadQueryResponse { rows, next_cursor })
125            }
126            StatementKind::NonSelect => {
127                let rows = self.connection.fetch_json(query.as_str(), db).await?;
128                Ok(ReadQueryResponse {
129                    rows,
130                    next_cursor: None,
131                })
132            }
133        }
134    }
135}