dbmcp_postgres/tools/
create_database.rs1use 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
14pub(crate) struct CreateDatabaseTool;
16
17impl CreateDatabaseTool {
18 const NAME: &'static str = "createDatabase";
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" → createDatabase(database="analytics")
30✗ "Create a table" → use writeQuery with CREATE TABLE
31</examples>
32
33<important>
34Database name must be non-empty; backend reserved-character rules apply.
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 handler.create_database(params).await
73 }
74}
75
76impl PostgresHandler {
77 pub async fn create_database(
83 &self,
84 CreateDatabaseRequest { database }: CreateDatabaseRequest,
85 ) -> Result<MessageResponse, ErrorData> {
86 if self.config.read_only {
87 return Err(SqlError::ReadOnlyViolation.into());
88 }
89
90 let create_sql = format!("CREATE DATABASE {}", quote_ident(&database));
91 self.connection.execute(create_sql.as_str(), None).await.map_err(|e| {
92 let msg = e.to_string();
93 if msg.contains("already exists") {
94 return SqlError::Query(format!("Database '{database}' already exists."));
95 }
96 e
97 })?;
98
99 Ok(MessageResponse {
100 message: format!("Database '{database}' created successfully."),
101 })
102 }
103}