Skip to main content

database_mcp_postgres/tools/
drop_database.rs

1//! MCP tool: `drop_database`.
2
3use std::borrow::Cow;
4
5use database_mcp_server::AppError;
6use database_mcp_server::types::{DropDatabaseRequest, MessageResponse};
7use database_mcp_sql::Connection as _;
8use database_mcp_sql::identifier::validate_identifier;
9use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
10use rmcp::model::{ErrorData, ToolAnnotations};
11
12use crate::PostgresHandler;
13
14/// Marker type for the `drop_database` MCP tool.
15pub(crate) struct DropDatabaseTool;
16
17impl DropDatabaseTool {
18    const NAME: &'static str = "drop_database";
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" → drop_database(database_name="test_db")
30✗ "Drop a table" → use drop_table 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        Ok(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 [`AppError::ReadOnlyViolation`] in read-only mode,
86    /// [`AppError::InvalidIdentifier`] for invalid names,
87    /// or [`AppError::Query`] if the target is the active database
88    /// or the backend reports an error.
89    pub async fn drop_database(&self, request: &DropDatabaseRequest) -> Result<MessageResponse, AppError> {
90        if self.config.read_only {
91            return Err(AppError::ReadOnlyViolation);
92        }
93        let name = &request.database_name;
94        validate_identifier(name)?;
95
96        // Guard: prevent dropping the currently connected database.
97        if self.connection.default_database_name() == name.as_str() {
98            return Err(AppError::Query(format!(
99                "Cannot drop the currently connected database '{name}'."
100            )));
101        }
102
103        let drop_sql = format!("DROP DATABASE {}", self.connection.quote_identifier(name));
104        self.connection.execute(drop_sql.as_str(), None).await?;
105
106        // Evict the pool for the dropped database so stale connections
107        // are not reused.
108        self.connection.invalidate(name).await;
109
110        Ok(MessageResponse {
111            message: format!("Database '{name}' dropped successfully."),
112        })
113    }
114}