Skip to main content

dbmcp_postgres/tools/
create_database.rs

1//! MCP tool: `createDatabase`.
2
3use std::borrow::Cow;
4
5use dbmcp_server::types::{CreateDatabaseRequest, 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;
13
14/// Marker type for the `createDatabase` MCP tool.
15pub(crate) struct CreateDatabaseTool;
16
17impl CreateDatabaseTool {
18    const NAME: &'static str = "createDatabase";
19    const TITLE: &'static str = "Create Database";
20    const DESCRIPTION: &'static str = include_str!("../../assets/tools/create_database.md");
21}
22
23impl ToolBase for CreateDatabaseTool {
24    type Parameter = CreateDatabaseRequest;
25    type Output = MessageResponse;
26    type Error = ErrorData;
27
28    fn name() -> Cow<'static, str> {
29        Self::NAME.into()
30    }
31
32    fn title() -> Option<String> {
33        Some(Self::TITLE.into())
34    }
35
36    fn description() -> Option<Cow<'static, str>> {
37        Some(Self::DESCRIPTION.into())
38    }
39
40    fn annotations() -> Option<ToolAnnotations> {
41        Some(
42            ToolAnnotations::new()
43                .read_only(false)
44                .destructive(false)
45                .idempotent(false)
46                .open_world(false),
47        )
48    }
49}
50
51impl AsyncTool<PostgresHandler> for CreateDatabaseTool {
52    async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
53        handler.create_database(params).await
54    }
55}
56
57impl PostgresHandler {
58    /// Creates a database if it doesn't exist.
59    ///
60    /// # Errors
61    ///
62    /// Returns [`SqlError`] if read-only or the query fails.
63    pub async fn create_database(
64        &self,
65        CreateDatabaseRequest { database }: CreateDatabaseRequest,
66    ) -> Result<MessageResponse, ErrorData> {
67        if self.config.read_only {
68            return Err(SqlError::ReadOnlyViolation.into());
69        }
70
71        let create_sql = format!("CREATE DATABASE {}", quote_ident(&database));
72        self.connection.execute(create_sql.as_str(), None).await.map_err(|e| {
73            let msg = e.to_string();
74            if msg.contains("already exists") {
75                return SqlError::Query(format!("Database '{database}' already exists."));
76            }
77            e
78        })?;
79
80        Ok(MessageResponse {
81            message: format!("Database '{database}' created successfully."),
82        })
83    }
84}