Skip to main content

database_mcp_postgres/tools/
create_database.rs

1//! MCP tool: `create_database`.
2
3use std::borrow::Cow;
4
5use database_mcp_server::AppError;
6use database_mcp_server::types::{CreateDatabaseRequest, MessageResponse};
7use database_mcp_sql::Connection as _;
8use database_mcp_sql::identifier::validate_identifier;
9use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
10use rmcp::model::{ErrorData, ToolAnnotations};
11
12use crate::PostgresHandler;
13
14/// Marker type for the `create_database` MCP tool.
15pub(crate) struct CreateDatabaseTool;
16
17impl CreateDatabaseTool {
18    const NAME: &'static str = "create_database";
19    const DESCRIPTION: &'static str = r#"Create a new database on the connected server.
20
21<usecase>
22Use when:
23- Setting up a new database for a project or application
24- The user asks to create a database
25</usecase>
26
27<examples>
28✓ "Create a database called analytics" → create_database(database_name="analytics")
29✗ "Create a table" → use write_query with CREATE TABLE
30</examples>
31
32<important>
33Database names must contain only alphanumeric characters and underscores.
34</important>
35
36<what_it_returns>
37A confirmation message with the created database name.
38</what_it_returns>"#;
39}
40
41impl ToolBase for CreateDatabaseTool {
42    type Parameter = CreateDatabaseRequest;
43    type Output = MessageResponse;
44    type Error = ErrorData;
45
46    fn name() -> Cow<'static, str> {
47        Self::NAME.into()
48    }
49
50    fn description() -> Option<Cow<'static, str>> {
51        Some(Self::DESCRIPTION.into())
52    }
53
54    fn annotations() -> Option<ToolAnnotations> {
55        Some(
56            ToolAnnotations::new()
57                .read_only(false)
58                .destructive(false)
59                .idempotent(false)
60                .open_world(false),
61        )
62    }
63}
64
65impl AsyncTool<PostgresHandler> for CreateDatabaseTool {
66    async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
67        Ok(handler.create_database(&params).await?)
68    }
69}
70
71impl PostgresHandler {
72    /// Creates a database if it doesn't exist.
73    ///
74    /// # Errors
75    ///
76    /// Returns [`AppError`] if read-only or the query fails.
77    pub async fn create_database(&self, request: &CreateDatabaseRequest) -> Result<MessageResponse, AppError> {
78        if self.config.read_only {
79            return Err(AppError::ReadOnlyViolation);
80        }
81        let name = &request.database_name;
82        validate_identifier(name)?;
83
84        // PostgreSQL CREATE DATABASE can't use parameterized queries
85        let create_sql = format!("CREATE DATABASE {}", self.connection.quote_identifier(name));
86        self.connection.execute(&create_sql, None).await.map_err(|e| {
87            let msg = e.to_string();
88            if msg.contains("already exists") {
89                return AppError::Query(format!("Database '{name}' already exists."));
90            }
91            e
92        })?;
93
94        Ok(MessageResponse {
95            message: format!("Database '{name}' created successfully."),
96        })
97    }
98}