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 dbmcp_sql::SqlError;
8use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
9use rmcp::model::{ErrorData, ToolAnnotations};
10
11use crate::PostgresHandler;
12
13/// Marker type for the `writeQuery` MCP tool.
14pub(crate) struct WriteQueryTool;
15
16impl WriteQueryTool {
17    const NAME: &'static str = "writeQuery";
18    const TITLE: &'static str = "Write Query";
19    const DESCRIPTION: &'static str = r#"Execute a write SQL query (INSERT, UPDATE, DELETE, CREATE, ALTER, DROP).
20
21<usecase>
22Use when:
23- Inserting, updating, or deleting rows
24- Creating or altering tables, indexes, views, or other schema objects
25- Any data modification operation
26</usecase>
27
28<when_not_to_use>
29- Read-only queries (SELECT, SHOW) → use readQuery
30- Query performance analysis → use explainQuery
31- Creating/dropping entire databases → use createDatabase or dropDatabase
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 SERIAL 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<PostgresHandler> for WriteQueryTool {
75    async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
76        Ok(handler.write_query(params).await?)
77    }
78}
79
80impl PostgresHandler {
81    /// Executes a write SQL query.
82    ///
83    /// # Errors
84    ///
85    /// Returns [`SqlError`] if the query fails.
86    pub async fn write_query(&self, QueryRequest { query, database }: QueryRequest) -> Result<QueryResponse, SqlError> {
87        let database = database.as_deref().map(str::trim).filter(|s| !s.is_empty());
88        let rows = self.connection.fetch_json(query.as_str(), database).await?;
89        Ok(QueryResponse { rows })
90    }
91}