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