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