Skip to main content

dbmcp_postgres/tools/
write_query.rs

1//! MCP tool: `writeQuery`.
2
3use std::borrow::Cow;
4
5use dbmcp_server::types::{QueryRequest, QueryResponse};
6use dbmcp_sql::Connection as _;
7use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
8use rmcp::model::{ErrorData, ToolAnnotations};
9
10use crate::PostgresHandler;
11
12/// Marker type for the `writeQuery` MCP tool.
13pub(crate) struct WriteQueryTool;
14
15impl WriteQueryTool {
16    const NAME: &'static str = "writeQuery";
17    const TITLE: &'static str = "Write Query";
18    const DESCRIPTION: &'static str = include_str!("../../assets/tools/write_query.md");
19}
20
21impl ToolBase for WriteQueryTool {
22    type Parameter = QueryRequest;
23    type Output = QueryResponse;
24    type Error = ErrorData;
25
26    fn name() -> Cow<'static, str> {
27        Self::NAME.into()
28    }
29
30    fn title() -> Option<String> {
31        Some(Self::TITLE.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<PostgresHandler> for WriteQueryTool {
50    async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
51        handler.write_query(params).await
52    }
53}
54
55impl PostgresHandler {
56    /// Executes a write SQL query.
57    ///
58    /// # Errors
59    ///
60    /// Returns [`SqlError`] if the query fails.
61    pub async fn write_query(
62        &self,
63        QueryRequest { query, database }: QueryRequest,
64    ) -> Result<QueryResponse, ErrorData> {
65        let database = database.as_deref().map(str::trim).filter(|s| !s.is_empty());
66        let mut rows = self.connection.fetch_json(query.as_str(), database).await?;
67        if let Some(r) = &self.redactor {
68            r.apply(&mut rows)?;
69        }
70        Ok(QueryResponse { rows })
71    }
72}