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::identifier::validate_identifier;
8use database_mcp_sql::timeout::execute_with_timeout;
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 DESCRIPTION: &'static str = "Drop a table from a database. Checks for foreign key dependencies\nvia the database engine — use `cascade` to force on `PostgreSQL`.";
21}
22
23impl ToolBase for DropTableTool {
24    type Parameter = DropTableRequest;
25    type Output = MessageResponse;
26    type Error = ErrorData;
27
28    fn name() -> Cow<'static, str> {
29        Self::NAME.into()
30    }
31
32    fn description() -> Option<Cow<'static, str>> {
33        Some(Self::DESCRIPTION.into())
34    }
35
36    fn annotations() -> Option<ToolAnnotations> {
37        Some(
38            ToolAnnotations::new()
39                .read_only(false)
40                .destructive(true)
41                .idempotent(false)
42                .open_world(false),
43        )
44    }
45}
46
47impl AsyncTool<PostgresHandler> for DropTableTool {
48    async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
49        Ok(handler.drop_table(&params).await?)
50    }
51}
52
53impl PostgresHandler {
54    /// Drops a table from a database.
55    ///
56    /// Validates identifiers, then executes `DROP TABLE`. When `cascade`
57    /// is true the statement uses `CASCADE` to also remove dependent
58    /// foreign-key constraints.
59    ///
60    /// # Errors
61    ///
62    /// Returns [`AppError::ReadOnlyViolation`] in read-only mode,
63    /// [`AppError::InvalidIdentifier`] for invalid names,
64    /// or [`AppError::Query`] if the backend reports an error.
65    pub async fn drop_table(&self, request: &DropTableRequest) -> Result<MessageResponse, AppError> {
66        if self.config.read_only {
67            return Err(AppError::ReadOnlyViolation);
68        }
69        let database = &request.database_name;
70        let table = &request.table_name;
71        validate_identifier(database)?;
72        validate_identifier(table)?;
73
74        let pool = self.get_pool(Some(database)).await?;
75
76        let mut drop_sql = format!("DROP TABLE {}", Self::quote_identifier(table));
77        if request.cascade {
78            drop_sql.push_str(" CASCADE");
79        }
80
81        execute_with_timeout(
82            self.config.query_timeout,
83            &drop_sql,
84            sqlx::query(&drop_sql).execute(&pool),
85        )
86        .await?;
87
88        Ok(MessageResponse {
89            message: format!("Table '{table}' dropped successfully."),
90        })
91    }
92}