Skip to main content

database_mcp_postgres/tools/
drop_database.rs

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