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