Skip to main content

database_mcp_postgres/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::{QueryRequest, 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::postgres::PgRow;
12use sqlx_to_json::RowExt;
13
14use crate::PostgresHandler;
15
16/// Marker type for the `write_query` MCP tool.
17pub(crate) struct WriteQueryTool;
18
19impl WriteQueryTool {
20    const NAME: &'static str = "write_query";
21    const DESCRIPTION: &'static str = "Execute a write SQL query (INSERT, UPDATE, DELETE, CREATE, ALTER, DROP).";
22}
23
24impl ToolBase for WriteQueryTool {
25    type Parameter = QueryRequest;
26    type Output = QueryResponse;
27    type Error = ErrorData;
28
29    fn name() -> Cow<'static, str> {
30        Self::NAME.into()
31    }
32
33    fn description() -> Option<Cow<'static, str>> {
34        Some(Self::DESCRIPTION.into())
35    }
36
37    fn annotations() -> Option<ToolAnnotations> {
38        Some(
39            ToolAnnotations::new()
40                .read_only(false)
41                .destructive(true)
42                .idempotent(false)
43                .open_world(true),
44        )
45    }
46}
47
48impl AsyncTool<PostgresHandler> for WriteQueryTool {
49    async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
50        Ok(handler.write_query(&params).await?)
51    }
52}
53
54impl PostgresHandler {
55    /// Executes a write SQL query.
56    ///
57    /// # Errors
58    ///
59    /// Returns [`AppError`] if the query fails.
60    pub async fn write_query(&self, request: &QueryRequest) -> Result<QueryResponse, AppError> {
61        let db = Some(request.database_name.trim()).filter(|s| !s.is_empty());
62        let pool = self.get_pool(db).await?;
63        let rows: Vec<PgRow> = 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}