Skip to main content

database_mcp_mysql/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::MysqlHandler;
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.
34If the database already exists, returns a message indicating so without error.
35</important>
36
37<what_it_returns>
38A confirmation message with the created database name.
39</what_it_returns>"#;
40}
41
42impl ToolBase for CreateDatabaseTool {
43    type Parameter = CreateDatabaseRequest;
44    type Output = MessageResponse;
45    type Error = ErrorData;
46
47    fn name() -> Cow<'static, str> {
48        Self::NAME.into()
49    }
50
51    fn description() -> Option<Cow<'static, str>> {
52        Some(Self::DESCRIPTION.into())
53    }
54
55    fn annotations() -> Option<ToolAnnotations> {
56        Some(
57            ToolAnnotations::new()
58                .read_only(false)
59                .destructive(false)
60                .idempotent(false)
61                .open_world(false),
62        )
63    }
64}
65
66impl AsyncTool<MysqlHandler> for CreateDatabaseTool {
67    async fn invoke(handler: &MysqlHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
68        Ok(handler.create_database(&params).await?)
69    }
70}
71
72impl MysqlHandler {
73    /// Creates a database if it doesn't exist.
74    ///
75    /// # Errors
76    ///
77    /// Returns [`AppError`] if read-only or the query fails.
78    pub async fn create_database(&self, request: &CreateDatabaseRequest) -> Result<MessageResponse, AppError> {
79        if self.config.read_only {
80            return Err(AppError::ReadOnlyViolation);
81        }
82        let name = &request.database_name;
83        validate_identifier(name)?;
84
85        let check_sql = format!(
86            "SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = {}",
87            self.connection.quote_string(name),
88        );
89        let exists = self.connection.fetch_optional(check_sql.as_str(), None).await?;
90
91        if exists.is_some() {
92            return Ok(MessageResponse {
93                message: format!("Database '{name}' already exists."),
94            });
95        }
96
97        let create_sql = format!(
98            "CREATE DATABASE IF NOT EXISTS {}",
99            self.connection.quote_identifier(name)
100        );
101        self.connection.execute(create_sql.as_str(), None).await?;
102
103        Ok(MessageResponse {
104            message: format!("Database '{name}' created successfully."),
105        })
106    }
107}