dbmcp_sqlite/tools/
read_query.rs1use std::borrow::Cow;
4
5use dbmcp_server::pagination::Pager;
6use dbmcp_server::types::ReadQueryResponse;
7
8use dbmcp_sql::Connection as _;
9use dbmcp_sql::StatementKind;
10use dbmcp_sql::pagination::with_limit_offset;
11use dbmcp_sql::validation::validate_read_only;
12use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
13use rmcp::model::{ErrorData, ToolAnnotations};
14
15use crate::SqliteHandler;
16use crate::types::ReadQueryRequest;
17
18pub(crate) struct ReadQueryTool;
20
21impl ReadQueryTool {
22 const NAME: &'static str = "readQuery";
23 const TITLE: &'static str = "Read Query";
24 const DESCRIPTION: &'static str = r#"Execute a read-only SQL query. Allowed statements: SELECT, EXPLAIN.
25
26<usecase>
27Use when:
28- Querying data from tables (SELECT with WHERE, JOIN, GROUP BY, etc.)
29- Aggregations: COUNT, SUM, AVG, GROUP BY, HAVING
30- Checking data existence or counts
31</usecase>
32
33<when_not_to_use>
34- Data changes (INSERT, UPDATE, DELETE) → use writeQuery
35- Query performance analysis → use explainQuery
36- Discovering tables or columns → use listTables (pass `detailed: true` for columns)
37</when_not_to_use>
38
39<examples>
40✓ "SELECT * FROM users WHERE status = 'active'"
41✓ "SELECT COUNT(*) FROM orders GROUP BY region"
42✗ "INSERT INTO users ..." → use writeQuery
43✗ "EXPLAIN SELECT ..." → use explainQuery for structured analysis
44</examples>
45
46<what_it_returns>
47A JSON array of row objects, each keyed by column name.
48</what_it_returns>
49
50<pagination>
51`SELECT` results are paginated. Pass the prior response's `nextCursor` as `cursor` to fetch the next page. `EXPLAIN` returns a single page and ignores `cursor`.
52</pagination>"#;
53}
54
55impl ToolBase for ReadQueryTool {
56 type Parameter = ReadQueryRequest;
57 type Output = ReadQueryResponse;
58 type Error = ErrorData;
59
60 fn name() -> Cow<'static, str> {
61 Self::NAME.into()
62 }
63
64 fn title() -> Option<String> {
65 Some(Self::TITLE.into())
66 }
67
68 fn description() -> Option<Cow<'static, str>> {
69 Some(Self::DESCRIPTION.into())
70 }
71
72 fn annotations() -> Option<ToolAnnotations> {
73 Some(
74 ToolAnnotations::new()
75 .read_only(true)
76 .destructive(false)
77 .idempotent(true)
78 .open_world(true),
79 )
80 }
81}
82
83impl AsyncTool<SqliteHandler> for ReadQueryTool {
84 async fn invoke(handler: &SqliteHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
85 handler.read_query(params).await
86 }
87}
88
89impl SqliteHandler {
90 pub async fn read_query(
104 &self,
105 ReadQueryRequest { query, cursor }: ReadQueryRequest,
106 ) -> Result<ReadQueryResponse, ErrorData> {
107 let kind = validate_read_only(&query, &sqlparser::dialect::SQLiteDialect {})?;
108
109 match kind {
110 StatementKind::Select => {
111 let pager = Pager::new(cursor, self.config.page_size);
112 let wrapped = with_limit_offset(&query, pager.limit(), pager.offset());
113 let rows = self.connection.fetch_json(wrapped.as_str(), None).await?;
114 let (mut rows, next_cursor) = pager.paginate(rows);
115 if let Some(r) = &self.redactor {
116 r.apply(&mut rows)?;
117 }
118 Ok(ReadQueryResponse { rows, next_cursor })
119 }
120 StatementKind::NonSelect => {
121 let mut rows = self.connection.fetch_json(query.as_str(), None).await?;
122 if let Some(r) = &self.redactor {
123 r.apply(&mut rows)?;
124 }
125 Ok(ReadQueryResponse {
126 rows,
127 next_cursor: None,
128 })
129 }
130 }
131 }
132}