database_mcp_sqlite/tools/
write_query.rs1use std::borrow::Cow;
4
5use database_mcp_server::AppError;
6use database_mcp_server::types::QueryResponse;
7use database_mcp_sql::Connection as _;
8use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
9use rmcp::model::{ErrorData, ToolAnnotations};
10use serde_json::Value;
11
12use crate::SqliteHandler;
13use crate::types::QueryRequest;
14
15pub(crate) struct WriteQueryTool;
17
18impl WriteQueryTool {
19 const NAME: &'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 read_query
31- Query performance analysis → use explain_query
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 read_query
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 description() -> Option<Cow<'static, str>> {
56 Some(Self::DESCRIPTION.into())
57 }
58
59 fn annotations() -> Option<ToolAnnotations> {
60 Some(
61 ToolAnnotations::new()
62 .read_only(false)
63 .destructive(true)
64 .idempotent(false)
65 .open_world(true),
66 )
67 }
68}
69
70impl AsyncTool<SqliteHandler> for WriteQueryTool {
71 async fn invoke(handler: &SqliteHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
72 Ok(handler.write_query(¶ms).await?)
73 }
74}
75
76impl SqliteHandler {
77 pub async fn write_query(&self, request: &QueryRequest) -> Result<QueryResponse, AppError> {
83 let rows = self.connection.fetch(request.query.as_str(), None).await?;
84 Ok(QueryResponse {
85 rows: Value::Array(rows),
86 })
87 }
88}