Skip to main content

database_mcp_sqlite/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::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::SqliteHandler;
14use crate::types::QueryRequest;
15
16/// Marker type for the `read_query` MCP tool.
17pub(crate) struct ReadQueryTool;
18
19impl ReadQueryTool {
20    const NAME: &'static str = "read_query";
21    const TITLE: &'static str = "Read Query";
22    const DESCRIPTION: &'static str = r#"Execute a read-only SQL query. Allowed statements: SELECT.
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- Checking data existence or counts
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✗ "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<SqliteHandler> for ReadQueryTool {
78    async fn invoke(handler: &SqliteHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
79        Ok(handler.read_query(&params).await?)
80    }
81}
82
83impl SqliteHandler {
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::SQLiteDialect {})?;
94        let rows = self.connection.fetch(request.query.as_str(), None).await?;
95        Ok(QueryResponse {
96            rows: Value::Array(rows),
97        })
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use serde_json::Value;
104    use sqlx::SqlitePool;
105    use sqlx::sqlite::SqlitePoolOptions;
106    use sqlx::sqlite::SqliteRow;
107    use sqlx_to_json::RowExt;
108
109    async fn mem_pool() -> SqlitePool {
110        SqlitePoolOptions::new()
111            .max_connections(1)
112            .connect("sqlite::memory:")
113            .await
114            .expect("in-memory SQLite")
115    }
116
117    async fn query_json(pool: &SqlitePool, sql: &str) -> Value {
118        let rows: Vec<SqliteRow> = sqlx::query(sql).fetch_all(pool).await.expect("query failed");
119        Value::Array(rows.iter().map(RowExt::to_json).collect())
120    }
121
122    #[tokio::test]
123    async fn rows_to_json_array_empty_result() {
124        let pool = mem_pool().await;
125        sqlx::query("CREATE TABLE t (v INTEGER)").execute(&pool).await.unwrap();
126
127        let rows = query_json(&pool, "SELECT v FROM t").await;
128        assert_eq!(rows, Value::Array(vec![]));
129    }
130
131    #[tokio::test]
132    async fn rows_to_json_array_multiple_rows() {
133        let pool = mem_pool().await;
134        sqlx::query("CREATE TABLE t (id INTEGER, name TEXT, score REAL)")
135            .execute(&pool)
136            .await
137            .unwrap();
138        sqlx::query("INSERT INTO t VALUES (1, 'alice', 9.5), (2, 'bob', 8.0)")
139            .execute(&pool)
140            .await
141            .unwrap();
142
143        let rows = query_json(&pool, "SELECT id, name, score FROM t ORDER BY id").await;
144        assert_eq!(rows.as_array().expect("should be array").len(), 2);
145
146        assert_eq!(rows[0]["id"], Value::Number(1.into()));
147        assert_eq!(rows[0]["name"], Value::String("alice".into()));
148        assert!(rows[0]["score"].is_number());
149
150        assert_eq!(rows[1]["id"], Value::Number(2.into()));
151        assert_eq!(rows[1]["name"], Value::String("bob".into()));
152    }
153}