Skip to main content

database_mcp_postgres/tools/
read_query.rs

1//! MCP tool: `read_query`.
2
3use std::borrow::Cow;
4
5use database_mcp_server::AppError;
6use database_mcp_server::types::{QueryRequest, QueryResponse};
7use database_mcp_sql::Connection as _;
8use database_mcp_sql::validation::validate_read_only_with_dialect;
9use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
10use rmcp::model::{ErrorData, ToolAnnotations};
11use serde_json::Value;
12
13use crate::PostgresHandler;
14
15/// Marker type for the `read_query` MCP tool.
16pub(crate) struct ReadQueryTool;
17
18impl ReadQueryTool {
19    const NAME: &'static str = "read_query";
20    const TITLE: &'static str = "Read Query";
21    const DESCRIPTION: &'static str = r#"Execute a read-only SQL query. Allowed statements: SELECT, SHOW, EXPLAIN. Accepts an optional `database_name` to query across databases without reconnecting.
22
23<usecase>
24Use when:
25- Querying data from tables (SELECT with WHERE, JOIN, GROUP BY, etc.)
26- Aggregations: COUNT, SUM, AVG, GROUP BY, HAVING
27- Listing server configuration parameters (SHOW)
28</usecase>
29
30<when_not_to_use>
31- Data changes (INSERT, UPDATE, DELETE) → use write_query
32- Query performance analysis → use explain_query
33- Discovering tables or columns → use list_tables or get_table_schema
34</when_not_to_use>
35
36<examples>
37✓ "SELECT * FROM users WHERE status = 'active'"
38✓ "SELECT COUNT(*) FROM orders GROUP BY region"
39✓ "SHOW server_version"
40✗ "INSERT INTO users ..." → use write_query
41✗ "EXPLAIN SELECT ..." → use explain_query for structured analysis
42</examples>
43
44<what_it_returns>
45A JSON array of row objects, each keyed by column name.
46</what_it_returns>"#;
47}
48
49impl ToolBase for ReadQueryTool {
50    type Parameter = QueryRequest;
51    type Output = QueryResponse;
52    type Error = ErrorData;
53
54    fn name() -> Cow<'static, str> {
55        Self::NAME.into()
56    }
57
58    fn title() -> Option<String> {
59        Some(Self::TITLE.into())
60    }
61
62    fn description() -> Option<Cow<'static, str>> {
63        Some(Self::DESCRIPTION.into())
64    }
65
66    fn annotations() -> Option<ToolAnnotations> {
67        Some(
68            ToolAnnotations::new()
69                .read_only(true)
70                .destructive(false)
71                .idempotent(true)
72                .open_world(true),
73        )
74    }
75}
76
77impl AsyncTool<PostgresHandler> for ReadQueryTool {
78    async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
79        Ok(handler.read_query(&params).await?)
80    }
81}
82
83impl PostgresHandler {
84    /// Executes a read-only SQL query.
85    ///
86    /// Validates that the query is read-only before executing.
87    ///
88    /// # Errors
89    ///
90    /// Returns [`AppError::ReadOnlyViolation`] if the query is not
91    /// read-only, or [`AppError::Query`] if the backend reports an error.
92    pub async fn read_query(&self, request: &QueryRequest) -> Result<QueryResponse, AppError> {
93        validate_read_only_with_dialect(&request.query, &sqlparser::dialect::PostgreSqlDialect {})?;
94        let db = Some(request.database_name.trim()).filter(|s| !s.is_empty());
95        let rows = self.connection.fetch(request.query.as_str(), db).await?;
96        Ok(QueryResponse {
97            rows: Value::Array(rows),
98        })
99    }
100}