Skip to main content

database_mcp_mysql/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::MysqlHandler;
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, DESCRIBE, USE, EXPLAIN.
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 variables or status (SHOW)
27- Viewing table structure (DESCRIBE)
28- Switching database context (USE)
29</usecase>
30
31<when_not_to_use>
32- Data changes (INSERT, UPDATE, DELETE) → use write_query
33- Query performance analysis → use explain_query
34- Discovering tables or columns → use list_tables or get_table_schema
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 TABLES" or "DESCRIBE users"
41✗ "INSERT INTO users ..." → use write_query
42✗ "EXPLAIN SELECT ..." → use explain_query 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
50impl ToolBase for ReadQueryTool {
51    type Parameter = QueryRequest;
52    type Output = QueryResponse;
53    type Error = ErrorData;
54
55    fn name() -> Cow<'static, str> {
56        Self::NAME.into()
57    }
58
59    fn description() -> Option<Cow<'static, str>> {
60        Some(Self::DESCRIPTION.into())
61    }
62
63    fn annotations() -> Option<ToolAnnotations> {
64        Some(
65            ToolAnnotations::new()
66                .read_only(true)
67                .destructive(false)
68                .idempotent(true)
69                .open_world(true),
70        )
71    }
72}
73
74impl AsyncTool<MysqlHandler> for ReadQueryTool {
75    async fn invoke(handler: &MysqlHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
76        Ok(handler.read_query(&params).await?)
77    }
78}
79
80impl MysqlHandler {
81    /// Executes a read-only SQL query.
82    ///
83    /// Validates that the query is read-only before executing.
84    ///
85    /// # Errors
86    ///
87    /// Returns [`AppError::ReadOnlyViolation`] if the query is not
88    /// read-only, or [`AppError::Query`] if the backend reports an error.
89    pub async fn read_query(&self, request: &QueryRequest) -> Result<QueryResponse, AppError> {
90        validate_read_only_with_dialect(&request.query, &sqlparser::dialect::MySqlDialect {})?;
91        let db = Some(request.database_name.trim()).filter(|s| !s.is_empty());
92        let rows = self.connection.fetch(request.query.as_str(), db).await?;
93        Ok(QueryResponse {
94            rows: Value::Array(rows),
95        })
96    }
97}