Skip to main content

database_mcp_postgres/tools/
drop_table.rs

1//! MCP tool: `drop_table`.
2
3use std::borrow::Cow;
4
5use database_mcp_server::AppError;
6use database_mcp_server::types::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;
13use crate::types::DropTableRequest;
14
15/// Marker type for the `drop_table` MCP tool.
16pub(crate) struct DropTableTool;
17
18impl DropTableTool {
19    const NAME: &'static str = "drop_table";
20    const TITLE: &'static str = "Drop Table";
21    const DESCRIPTION: &'static str = r#"Drop a table from a database. Checks for foreign key dependencies via the database engine.
22
23<usecase>
24Use when:
25- Removing a table that is no longer needed
26- Cleaning up test or temporary tables
27</usecase>
28
29<examples>
30✓ "Drop the temp_logs table" → drop_table(database_name="mydb", table_name="temp_logs")
31✓ "Force drop with dependencies" → drop_table(..., cascade=true)
32✗ "Delete rows from a table" → use write_query with DELETE
33✗ "Drop a database" → use drop_database instead
34</examples>
35
36<safety>
37IMPORTANT: This permanently deletes the table and ALL its data. This action cannot be undone.
38Set `cascade` to true to also drop dependent foreign key constraints.
39Without cascade, the drop will fail if other tables reference this one.
40</safety>
41
42<what_it_returns>
43A confirmation message with the dropped table name.
44</what_it_returns>"#;
45}
46
47impl ToolBase for DropTableTool {
48    type Parameter = DropTableRequest;
49    type Output = MessageResponse;
50    type Error = ErrorData;
51
52    fn name() -> Cow<'static, str> {
53        Self::NAME.into()
54    }
55
56    fn title() -> Option<String> {
57        Some(Self::TITLE.into())
58    }
59
60    fn description() -> Option<Cow<'static, str>> {
61        Some(Self::DESCRIPTION.into())
62    }
63
64    fn annotations() -> Option<ToolAnnotations> {
65        Some(
66            ToolAnnotations::new()
67                .read_only(false)
68                .destructive(true)
69                .idempotent(false)
70                .open_world(false),
71        )
72    }
73}
74
75impl AsyncTool<PostgresHandler> for DropTableTool {
76    async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
77        Ok(handler.drop_table(&params).await?)
78    }
79}
80
81impl PostgresHandler {
82    /// Drops a table from a database.
83    ///
84    /// Validates identifiers, then executes `DROP TABLE`. When `cascade`
85    /// is true the statement uses `CASCADE` to also remove dependent
86    /// foreign-key constraints.
87    ///
88    /// # Errors
89    ///
90    /// Returns [`AppError::ReadOnlyViolation`] in read-only mode,
91    /// [`AppError::InvalidIdentifier`] for invalid names,
92    /// or [`AppError::Query`] if the backend reports an error.
93    pub async fn drop_table(&self, request: &DropTableRequest) -> Result<MessageResponse, AppError> {
94        if self.config.read_only {
95            return Err(AppError::ReadOnlyViolation);
96        }
97        let database = &request.database_name;
98        let table = &request.table_name;
99        validate_identifier(database)?;
100        validate_identifier(table)?;
101
102        let mut drop_sql = format!("DROP TABLE {}", self.connection.quote_identifier(table));
103        if request.cascade {
104            drop_sql.push_str(" CASCADE");
105        }
106
107        self.connection.execute(drop_sql.as_str(), Some(database)).await?;
108
109        Ok(MessageResponse {
110            message: format!("Table '{table}' dropped successfully."),
111        })
112    }
113}