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 = include_str!("../../assets/tools/read_query.md");
23}
24
25impl ToolBase for ReadQueryTool {
26    type Parameter = ReadQueryRequest;
27    type Output = ReadQueryResponse;
28    type Error = ErrorData;
29
30    fn name() -> Cow<'static, str> {
31        Self::NAME.into()
32    }
33
34    fn title() -> Option<String> {
35        Some(Self::TITLE.into())
36    }
37
38    fn description() -> Option<Cow<'static, str>> {
39        Some(Self::DESCRIPTION.into())
40    }
41
42    fn annotations() -> Option<ToolAnnotations> {
43        Some(
44            ToolAnnotations::new()
45                .read_only(true)
46                .destructive(false)
47                .idempotent(true)
48                .open_world(true),
49        )
50    }
51}
52
53impl AsyncTool<PostgresHandler> for ReadQueryTool {
54    async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
55        handler.read_query(params).await
56    }
57}
58
59impl PostgresHandler {
60    /// Executes a read-only SQL query, paginating `SELECT` result rows.
61    ///
62    /// Validates that the query is read-only, then dispatches on the
63    /// classified [`StatementKind`]: `Select` is wrapped in a subquery with
64    /// a server-controlled `LIMIT`/`OFFSET`; `NonSelect` (`SHOW`, `EXPLAIN`
65    /// under the PG dialect) is executed as-is and returned in a single
66    /// page. A malformed `cursor` is rejected by the serde deserializer
67    /// before this method is called, producing JSON-RPC `-32602`.
68    ///
69    /// # Errors
70    ///
71    /// Returns [`SqlError::ReadOnlyViolation`] if the query is not
72    /// read-only, or [`SqlError::Query`] if the backend reports an error.
73    pub async fn read_query(
74        &self,
75        ReadQueryRequest {
76            query,
77            database,
78            cursor,
79        }: ReadQueryRequest,
80    ) -> Result<ReadQueryResponse, ErrorData> {
81        let kind = validate_read_only(&query, &sqlparser::dialect::PostgreSqlDialect {})?;
82        let database = database.as_deref().map(str::trim).filter(|s| !s.is_empty());
83
84        match kind {
85            StatementKind::Select => {
86                let pager = Pager::new(cursor, self.config.page_size);
87                let wrapped = with_limit_offset(&query, pager.limit(), pager.offset());
88                let rows = self.connection.fetch_json(wrapped.as_str(), database).await?;
89                let (mut rows, next_cursor) = pager.paginate(rows);
90                if let Some(r) = &self.redactor {
91                    r.apply(&mut rows)?;
92                }
93                Ok(ReadQueryResponse { rows, next_cursor })
94            }
95            StatementKind::NonSelect => {
96                let mut rows = self.connection.fetch_json(query.as_str(), database).await?;
97                if let Some(r) = &self.redactor {
98                    r.apply(&mut rows)?;
99                }
100                Ok(ReadQueryResponse {
101                    rows,
102                    next_cursor: None,
103                })
104            }
105        }
106    }
107}