Skip to main content

dbmcp_postgres/tools/
read_query.rs

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