Skip to main content

database_mcp_sqlite/tools/
write_query.rs

1//! MCP tool: `write_query`.
2
3use std::borrow::Cow;
4
5use database_mcp_server::AppError;
6use database_mcp_server::types::QueryResponse;
7use database_mcp_sql::timeout::execute_with_timeout;
8use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
9use rmcp::model::{ErrorData, ToolAnnotations};
10use serde_json::Value;
11use sqlx::sqlite::SqliteRow;
12use sqlx_to_json::RowExt;
13
14use crate::SqliteHandler;
15use crate::types::QueryRequest;
16
17/// Marker type for the `write_query` MCP tool.
18pub(crate) struct WriteQueryTool;
19
20impl WriteQueryTool {
21    const NAME: &'static str = "write_query";
22    const DESCRIPTION: &'static str = "Execute a write SQL query (INSERT, UPDATE, DELETE, CREATE, ALTER, DROP).";
23}
24
25impl ToolBase for WriteQueryTool {
26    type Parameter = QueryRequest;
27    type Output = QueryResponse;
28    type Error = ErrorData;
29
30    fn name() -> Cow<'static, str> {
31        Self::NAME.into()
32    }
33
34    fn description() -> Option<Cow<'static, str>> {
35        Some(Self::DESCRIPTION.into())
36    }
37
38    fn annotations() -> Option<ToolAnnotations> {
39        Some(
40            ToolAnnotations::new()
41                .read_only(false)
42                .destructive(true)
43                .idempotent(false)
44                .open_world(true),
45        )
46    }
47}
48
49impl AsyncTool<SqliteHandler> for WriteQueryTool {
50    async fn invoke(handler: &SqliteHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
51        Ok(handler.write_query(&params).await?)
52    }
53}
54
55impl SqliteHandler {
56    /// Executes a write SQL query.
57    ///
58    /// # Errors
59    ///
60    /// Returns [`AppError`] if the query fails.
61    pub async fn write_query(&self, request: &QueryRequest) -> Result<QueryResponse, AppError> {
62        let pool = self.pool.clone();
63        let rows: Vec<SqliteRow> = execute_with_timeout(
64            self.config.query_timeout,
65            &request.query,
66            sqlx::query(&request.query).fetch_all(&pool),
67        )
68        .await?;
69        Ok(QueryResponse {
70            rows: Value::Array(rows.iter().map(RowExt::to_json).collect()),
71        })
72    }
73}