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
14/// Marker type for the `dropDatabase` MCP tool.
15pub(crate) struct DropDatabaseTool;
16
17impl DropDatabaseTool {
18    const NAME: &'static str = "dropDatabase";
19    const TITLE: &'static str = "Drop Database";
20    const DESCRIPTION: &'static str = r#"Drop an existing database from the connected server.
21
22<usecase>
23Use when:
24- Removing a database that is no longer needed
25- Cleaning up test or temporary databases
26</usecase>
27
28<examples>
29✓ "Drop the test_db database" → dropDatabase(database="test_db")
30✗ "Drop a table" → use dropTable instead
31</examples>
32
33<safety>
34IMPORTANT: This permanently deletes the database and ALL its data. This action cannot be undone.
35Cannot drop the database you are currently connected to.
36</safety>
37
38<what_it_returns>
39A confirmation message with the dropped database name.
40</what_it_returns>"#;
41}
42
43impl ToolBase for DropDatabaseTool {
44    type Parameter = DropDatabaseRequest;
45    type Output = MessageResponse;
46    type Error = ErrorData;
47
48    fn name() -> Cow<'static, str> {
49        Self::NAME.into()
50    }
51
52    fn title() -> Option<String> {
53        Some(Self::TITLE.into())
54    }
55
56    fn description() -> Option<Cow<'static, str>> {
57        Some(Self::DESCRIPTION.into())
58    }
59
60    fn annotations() -> Option<ToolAnnotations> {
61        Some(
62            ToolAnnotations::new()
63                .read_only(false)
64                .destructive(true)
65                .idempotent(false)
66                .open_world(false),
67        )
68    }
69}
70
71impl AsyncTool<PostgresHandler> for DropDatabaseTool {
72    async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
73        handler.drop_database(params).await
74    }
75}
76
77impl PostgresHandler {
78    /// Drops an existing database.
79    ///
80    /// Refuses to drop the currently connected (default) database and
81    /// evicts the corresponding pool cache entry after a successful drop.
82    ///
83    /// # Errors
84    ///
85    /// Returns [`SqlError::ReadOnlyViolation`] in read-only mode,
86    /// [`SqlError::InvalidIdentifier`] for invalid names,
87    /// or [`SqlError::Query`] if the target is the active database
88    /// or the backend reports an error.
89    pub async fn drop_database(
90        &self,
91        DropDatabaseRequest { database }: DropDatabaseRequest,
92    ) -> Result<MessageResponse, ErrorData> {
93        if self.config.read_only {
94            return Err(SqlError::ReadOnlyViolation.into());
95        }
96
97        // Guard: prevent dropping the currently connected database.
98        if self.connection.default_database_name() == database.as_str() {
99            return Err(SqlError::Query(format!("Cannot drop the currently connected database '{database}'.")).into());
100        }
101
102        let drop_sql = format!("DROP DATABASE {}", quote_ident(&database));
103        self.connection.execute(drop_sql.as_str(), None).await?;
104
105        self.connection.invalidate(&database).await;
106
107        Ok(MessageResponse {
108            message: format!("Database '{database}' dropped successfully."),
109        })
110    }
111}