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