Skip to main content

dbmcp_postgres/tools/
drop_database.rs

1//! MCP tool: `dropDatabase`.
2
3use std::borrow::Cow;
4
5use dbmcp_server::types::{DropDatabaseRequest, MessageResponse};
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;
12use crate::connection::quote_ident;
13
14const NAME: &str = "dropDatabase";
15const TITLE: &str = "Drop Database";
16const DESCRIPTION: &str = include_str!("../../assets/tools/drop_database/default.md");
17
18/// Marker type for the `dropDatabase` MCP tool.
19pub(crate) struct DropDatabaseTool;
20
21impl ToolBase for DropDatabaseTool {
22    type Parameter = DropDatabaseRequest;
23    type Output = MessageResponse;
24    type Error = ErrorData;
25
26    fn name() -> Cow<'static, str> {
27        NAME.into()
28    }
29
30    fn title() -> Option<String> {
31        Some(TITLE.into())
32    }
33
34    fn description() -> Option<Cow<'static, str>> {
35        Some(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(false),
45        )
46    }
47}
48
49impl AsyncTool<PostgresHandler> for DropDatabaseTool {
50    async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
51        handler.drop_database(params).await
52    }
53}
54
55impl PostgresHandler {
56    /// Drops an existing database.
57    ///
58    /// Refuses to drop the currently connected (default) database and
59    /// evicts the corresponding pool cache entry after a successful drop.
60    ///
61    /// # Errors
62    ///
63    /// Returns [`SqlError::ReadOnlyViolation`] in read-only mode,
64    /// [`SqlError::InvalidIdentifier`] for invalid names,
65    /// or [`SqlError::Query`] if the target is the active database
66    /// or the backend reports an error.
67    pub async fn drop_database(
68        &self,
69        DropDatabaseRequest { database }: DropDatabaseRequest,
70    ) -> Result<MessageResponse, ErrorData> {
71        if self.config.read_only {
72            return Err(SqlError::ReadOnlyViolation.into());
73        }
74
75        // Guard: prevent dropping the currently connected database.
76        if self.connection.default_database_name() == database.as_str() {
77            return Err(SqlError::Query(format!("Cannot drop the currently connected database '{database}'.")).into());
78        }
79
80        let drop_sql = format!("DROP DATABASE {}", quote_ident(&database));
81        self.connection.execute(drop_sql.as_str(), None).await?;
82
83        self.connection.invalidate(&database).await;
84
85        Ok(MessageResponse {
86            message: format!("Database '{database}' dropped successfully."),
87        })
88    }
89}