Skip to main content

dbmcp_postgres/tools/
drop_table.rs

1//! MCP tool: `dropTable`.
2
3use std::borrow::Cow;
4
5use dbmcp_server::types::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;
13use crate::types::DropTableRequest;
14
15/// Marker type for the `dropTable` MCP tool.
16pub(crate) struct DropTableTool;
17
18impl DropTableTool {
19    const NAME: &'static str = "dropTable";
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" → dropTable(database="mydb", table="temp_logs")
31✓ "Force drop with dependencies" → dropTable(..., cascade=true)
32✗ "Delete rows from a table" → use writeQuery with DELETE
33✗ "Drop a database" → use dropDatabase 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        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 [`SqlError::ReadOnlyViolation`] in read-only mode,
91    /// [`SqlError::InvalidIdentifier`] for invalid names,
92    /// or [`SqlError::Query`] if the backend reports an error.
93    pub async fn drop_table(
94        &self,
95        DropTableRequest {
96            database,
97            table,
98            cascade,
99        }: DropTableRequest,
100    ) -> Result<MessageResponse, ErrorData> {
101        if self.config.read_only {
102            return Err(SqlError::ReadOnlyViolation.into());
103        }
104
105        let database = database.as_deref().map(str::trim).filter(|s| !s.is_empty());
106
107        let mut drop_sql = format!("DROP TABLE {}", quote_ident(&table));
108        if cascade {
109            drop_sql.push_str(" CASCADE");
110        }
111
112        self.connection.execute(drop_sql.as_str(), database).await?;
113
114        Ok(MessageResponse {
115            message: format!("Table '{table}' dropped successfully."),
116        })
117    }
118}