dbmcp_sqlite/tools/
write_query.rs1use std::borrow::Cow;
4
5use dbmcp_server::types::QueryResponse;
6
7use dbmcp_sql::Connection as _;
8use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
9use rmcp::model::{ErrorData, ToolAnnotations};
10
11use crate::SqliteHandler;
12use crate::types::QueryRequest;
13
14pub(crate) struct WriteQueryTool;
16
17impl WriteQueryTool {
18 const NAME: &'static str = "writeQuery";
19 const TITLE: &'static str = "Write Query";
20 const DESCRIPTION: &'static str = r#"Execute a write SQL query (INSERT, UPDATE, DELETE, CREATE, ALTER, DROP).
21
22<usecase>
23Use when:
24- Inserting, updating, or deleting rows
25- Creating or altering tables, indexes, views, or other schema objects
26- Any data modification operation
27</usecase>
28
29<when_not_to_use>
30- Read-only queries (SELECT) → use readQuery
31- Query performance analysis → use explainQuery
32</when_not_to_use>
33
34<examples>
35✓ "INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')"
36✓ "UPDATE orders SET status = 'shipped' WHERE id = 42"
37✓ "CREATE TABLE logs (id INTEGER PRIMARY KEY, message TEXT)"
38✗ "SELECT * FROM users" → use readQuery
39</examples>
40
41<what_it_returns>
42A JSON array of affected/returning row objects, each keyed by column name.
43</what_it_returns>"#;
44}
45
46impl ToolBase for WriteQueryTool {
47 type Parameter = QueryRequest;
48 type Output = QueryResponse;
49 type Error = ErrorData;
50
51 fn name() -> Cow<'static, str> {
52 Self::NAME.into()
53 }
54
55 fn title() -> Option<String> {
56 Some(Self::TITLE.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(false)
67 .destructive(true)
68 .idempotent(false)
69 .open_world(true),
70 )
71 }
72}
73
74impl AsyncTool<SqliteHandler> for WriteQueryTool {
75 async fn invoke(handler: &SqliteHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
76 handler.write_query(params).await
77 }
78}
79
80impl SqliteHandler {
81 pub async fn write_query(&self, QueryRequest { query }: QueryRequest) -> Result<QueryResponse, ErrorData> {
87 let mut rows = self.connection.fetch_json(query.as_str(), None).await?;
88 if let Some(r) = &self.redactor {
89 r.apply(&mut rows)?;
90 }
91 Ok(QueryResponse { rows })
92 }
93}