database_mcp_postgres/tools/
create_database.rs1use 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
14pub(crate) struct CreateDatabaseTool;
16
17impl CreateDatabaseTool {
18 const NAME: &'static str = "create_database";
19 const TITLE: &'static str = "Create Database";
20 const DESCRIPTION: &'static str = r#"Create a new database on the connected server.
21
22<usecase>
23Use when:
24- Setting up a new database for a project or application
25- The user asks to create a database
26</usecase>
27
28<examples>
29✓ "Create a database called analytics" → create_database(database_name="analytics")
30✗ "Create a table" → use write_query with CREATE TABLE
31</examples>
32
33<important>
34Database names must contain only alphanumeric characters and underscores.
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 title() -> Option<String> {
52 Some(Self::TITLE.into())
53 }
54
55 fn description() -> Option<Cow<'static, str>> {
56 Some(Self::DESCRIPTION.into())
57 }
58
59 fn annotations() -> Option<ToolAnnotations> {
60 Some(
61 ToolAnnotations::new()
62 .read_only(false)
63 .destructive(false)
64 .idempotent(false)
65 .open_world(false),
66 )
67 }
68}
69
70impl AsyncTool<PostgresHandler> for CreateDatabaseTool {
71 async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
72 Ok(handler.create_database(¶ms).await?)
73 }
74}
75
76impl PostgresHandler {
77 pub async fn create_database(&self, request: &CreateDatabaseRequest) -> Result<MessageResponse, AppError> {
83 if self.config.read_only {
84 return Err(AppError::ReadOnlyViolation);
85 }
86 let name = &request.database_name;
87 validate_identifier(name)?;
88
89 let create_sql = format!("CREATE DATABASE {}", self.connection.quote_identifier(name));
91 self.connection.execute(&create_sql, None).await.map_err(|e| {
92 let msg = e.to_string();
93 if msg.contains("already exists") {
94 return AppError::Query(format!("Database '{name}' already exists."));
95 }
96 e
97 })?;
98
99 Ok(MessageResponse {
100 message: format!("Database '{name}' created successfully."),
101 })
102 }
103}