mcp-postgres 4.1.0

High-performance MCP server for PostgreSQL with CPU-aware connection pooling and optimized buffers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
use crate::errors::Result as MCPResult;
use serde_json::{Value, json};
use tokio_postgres::Client;

const MAX_IDENTIFIER_LEN: usize = 255;
const MAX_PASSWORD_LEN: usize = 1024;

/// Reject passwords containing control characters (NUL, newline, carriage
/// return). They are escaped for quotes when interpolated into CREATE/ALTER
/// statements, but control characters can still corrupt the statement, so they
/// are disallowed outright.
fn validate_password(pw: &str) -> MCPResult<()> {
    if pw.len() > MAX_PASSWORD_LEN {
        return Err(crate::errors::MCPError::InvalidParams(format!(
            "'password' exceeds maximum length of {MAX_PASSWORD_LEN} characters"
        )));
    }
    if pw.chars().any(|c| c.is_control()) {
        return Err(crate::errors::MCPError::InvalidParams(
            "'password' must not contain control characters".into(),
        ));
    }
    Ok(())
}

pub async fn create_user(client: &Client, params: &Option<&Value>) -> MCPResult<Value> {
    let username = params
        .as_ref()
        .and_then(|p| p.get("username").and_then(|v| v.as_str()))
        .ok_or_else(|| {
            crate::errors::MCPError::InvalidParams("Missing 'username' parameter".into())
        })?;

    if username.is_empty() || username.len() > MAX_IDENTIFIER_LEN {
        return Err(crate::errors::MCPError::InvalidParams(format!(
            "'username' must be 1-{MAX_IDENTIFIER_LEN} characters"
        )));
    }

    let password = params
        .as_ref()
        .and_then(|p| p.get("password").and_then(|v| v.as_str()));
    let valid_until = params
        .as_ref()
        .and_then(|p| p.get("valid_until").and_then(|v| v.as_str()));
    let connection_limit = params
        .as_ref()
        .and_then(|p| p.get("connection_limit").and_then(|v| v.as_i64()));
    let can_login = params
        .as_ref()
        .and_then(|p| p.get("can_login").and_then(|v| v.as_bool()));

    let mut sql = format!("CREATE USER {}", quote_ident(username));
    if let Some(pw) = password {
        validate_password(pw)?;
        sql.push_str(&format!(" PASSWORD '{}'", pw.replace('\'', "''")));
    }
    if let Some(limit) = connection_limit {
        sql.push_str(&format!(" CONNECTION LIMIT {}", limit));
    }
    if let Some(login) = can_login {
        if login {
            sql.push_str(" LOGIN");
        } else {
            sql.push_str(" NOLOGIN");
        }
    }
    if let Some(until) = valid_until {
        sql.push_str(&format!(" VALID UNTIL '{}'", until.replace('\'', "''")));
    }

    client.execute(&sql, &[]).await?;
    Ok(json!({ "success": true, "user": username }))
}

pub async fn alter_user(client: &Client, params: &Option<&Value>) -> MCPResult<Value> {
    let username = params
        .as_ref()
        .and_then(|p| p.get("username").and_then(|v| v.as_str()))
        .ok_or_else(|| {
            crate::errors::MCPError::InvalidParams("Missing 'username' parameter".into())
        })?;

    if username.is_empty() || username.len() > MAX_IDENTIFIER_LEN {
        return Err(crate::errors::MCPError::InvalidParams(format!(
            "'username' must be 1-{MAX_IDENTIFIER_LEN} characters"
        )));
    }

    let password = params
        .as_ref()
        .and_then(|p| p.get("password").and_then(|v| v.as_str()));
    let valid_until = params
        .as_ref()
        .and_then(|p| p.get("valid_until").and_then(|v| v.as_str()));
    let connection_limit = params
        .as_ref()
        .and_then(|p| p.get("connection_limit").and_then(|v| v.as_i64()));
    let can_login = params
        .as_ref()
        .and_then(|p| p.get("can_login").and_then(|v| v.as_bool()));
    let new_name = params
        .as_ref()
        .and_then(|p| p.get("new_name").and_then(|v| v.as_str()));

    if password.is_none()
        && valid_until.is_none()
        && connection_limit.is_none()
        && can_login.is_none()
        && new_name.is_none()
    {
        return Err(crate::errors::MCPError::InvalidParams(
            "No attributes specified to alter".into(),
        ));
    }

    let mut sql = format!("ALTER USER {}", quote_ident(username));
    if let Some(pw) = password {
        validate_password(pw)?;
        sql.push_str(&format!(" PASSWORD '{}'", pw.replace('\'', "''")));
    }
    if let Some(limit) = connection_limit {
        sql.push_str(&format!(" CONNECTION LIMIT {}", limit));
    }
    if let Some(login) = can_login {
        if login {
            sql.push_str(" LOGIN");
        } else {
            sql.push_str(" NOLOGIN");
        }
    }
    if let Some(until) = valid_until {
        sql.push_str(&format!(" VALID UNTIL '{}'", until.replace('\'', "''")));
    }
    if let Some(name) = new_name {
        sql.push_str(&format!(" RENAME TO {}", quote_ident(name)));
    }

    client.execute(&sql, &[]).await?;
    Ok(json!({ "success": true, "user": username }))
}

pub async fn drop_user(client: &Client, params: &Option<&Value>) -> MCPResult<Value> {
    let username = params
        .as_ref()
        .and_then(|p| p.get("username").and_then(|v| v.as_str()))
        .ok_or_else(|| {
            crate::errors::MCPError::InvalidParams("Missing 'username' parameter".into())
        })?;

    if username.is_empty() || username.len() > MAX_IDENTIFIER_LEN {
        return Err(crate::errors::MCPError::InvalidParams(format!(
            "'username' must be 1-{MAX_IDENTIFIER_LEN} characters"
        )));
    }

    let if_exists = params
        .as_ref()
        .and_then(|p| p.get("if_exists").and_then(|v| v.as_bool()))
        .unwrap_or(false);

    let mut sql = "DROP USER".to_string();
    if if_exists {
        sql.push_str(" IF EXISTS");
    }
    sql.push_str(&format!(" {}", quote_ident(username)));

    client.execute(&sql, &[]).await?;
    Ok(json!({ "success": true, "user": username }))
}

pub async fn create_role(client: &Client, params: &Option<&Value>) -> MCPResult<Value> {
    let role_name = params
        .as_ref()
        .and_then(|p| p.get("role_name").and_then(|v| v.as_str()))
        .ok_or_else(|| {
            crate::errors::MCPError::InvalidParams("Missing 'role_name' parameter".into())
        })?;

    if role_name.is_empty() || role_name.len() > MAX_IDENTIFIER_LEN {
        return Err(crate::errors::MCPError::InvalidParams(format!(
            "'role_name' must be 1-{MAX_IDENTIFIER_LEN} characters"
        )));
    }

    let with_login = params
        .as_ref()
        .and_then(|p| p.get("with_login").and_then(|v| v.as_bool()))
        .unwrap_or(false);
    let mut sql = format!("CREATE ROLE {}", quote_ident(role_name));
    sql.push_str(if with_login { " LOGIN" } else { " NOLOGIN" });

    client.execute(&sql, &[]).await?;
    Ok(json!({ "success": true, "role": role_name }))
}

pub async fn alter_role(client: &Client, params: &Option<&Value>) -> MCPResult<Value> {
    let role_name = params
        .as_ref()
        .and_then(|p| p.get("role_name").and_then(|v| v.as_str()))
        .ok_or_else(|| {
            crate::errors::MCPError::InvalidParams("Missing 'role_name' parameter".into())
        })?;

    if role_name.is_empty() || role_name.len() > MAX_IDENTIFIER_LEN {
        return Err(crate::errors::MCPError::InvalidParams(format!(
            "'role_name' must be 1-{MAX_IDENTIFIER_LEN} characters"
        )));
    }

    let password = params
        .as_ref()
        .and_then(|p| p.get("password").and_then(|v| v.as_str()));
    let can_login = params
        .as_ref()
        .and_then(|p| p.get("can_login").and_then(|v| v.as_bool()));
    let superuser = params
        .as_ref()
        .and_then(|p| p.get("superuser").and_then(|v| v.as_bool()));
    let createdb = params
        .as_ref()
        .and_then(|p| p.get("createdb").and_then(|v| v.as_bool()));
    let new_name = params
        .as_ref()
        .and_then(|p| p.get("new_name").and_then(|v| v.as_str()));

    let mut sql = format!("ALTER ROLE {}", quote_ident(role_name));
    if let Some(pw) = password {
        validate_password(pw)?;
        sql.push_str(&format!(" PASSWORD '{}'", pw.replace('\'', "''")));
    }
    if let Some(login) = can_login {
        sql.push_str(if login { " LOGIN" } else { " NOLOGIN" });
    }
    if let Some(su) = superuser {
        sql.push_str(if su { " SUPERUSER" } else { " NOSUPERUSER" });
    }
    if let Some(db) = createdb {
        sql.push_str(if db { " CREATEDB" } else { " NOCREATEDB" });
    }
    if let Some(name) = new_name {
        sql.push_str(&format!(" RENAME TO {}", quote_ident(name)));
    }

    client.execute(&sql, &[]).await?;
    Ok(json!({ "success": true, "role": role_name }))
}

pub async fn drop_role(client: &Client, params: &Option<&Value>) -> MCPResult<Value> {
    let role_name = params
        .as_ref()
        .and_then(|p| p.get("role_name").and_then(|v| v.as_str()))
        .ok_or_else(|| {
            crate::errors::MCPError::InvalidParams("Missing 'role_name' parameter".into())
        })?;

    if role_name.is_empty() || role_name.len() > MAX_IDENTIFIER_LEN {
        return Err(crate::errors::MCPError::InvalidParams(format!(
            "'role_name' must be 1-{MAX_IDENTIFIER_LEN} characters"
        )));
    }

    let if_exists = params
        .as_ref()
        .and_then(|p| p.get("if_exists").and_then(|v| v.as_bool()))
        .unwrap_or(false);

    let mut sql = "DROP ROLE".to_string();
    if if_exists {
        sql.push_str(" IF EXISTS");
    }
    sql.push_str(&format!(" {}", quote_ident(role_name)));

    client.execute(&sql, &[]).await?;
    Ok(json!({ "success": true, "role": role_name }))
}

pub async fn grant_privileges(client: &Client, params: &Option<&Value>) -> MCPResult<Value> {
    let privilege = params
        .as_ref()
        .and_then(|p| p.get("privilege").and_then(|v| v.as_str()))
        .ok_or_else(|| {
            crate::errors::MCPError::InvalidParams("Missing 'privilege' parameter".into())
        })?;
    let object_type = params
        .as_ref()
        .and_then(|p| p.get("object_type").and_then(|v| v.as_str()))
        .ok_or_else(|| {
            crate::errors::MCPError::InvalidParams("Missing 'object_type' parameter".into())
        })?;
    let object_name = params
        .as_ref()
        .and_then(|p| p.get("object_name").and_then(|v| v.as_str()))
        .ok_or_else(|| {
            crate::errors::MCPError::InvalidParams("Missing 'object_name' parameter".into())
        })?;
    let grantee = params
        .as_ref()
        .and_then(|p| p.get("grantee").and_then(|v| v.as_str()))
        .ok_or_else(|| {
            crate::errors::MCPError::InvalidParams("Missing 'grantee' parameter".into())
        })?;

    let schema = params
        .as_ref()
        .and_then(|p| p.get("schema").and_then(|v| v.as_str()))
        .unwrap_or("public");

    crate::validation::validate_privilege_list(privilege)?;

    let valid_types = [
        "table",
        "sequence",
        "schema",
        "database",
        "all_tables_in_schema",
    ];
    if !valid_types.contains(&object_type) {
        return Err(crate::errors::MCPError::InvalidParams(format!(
            "Unsupported object_type '{}'. Use: {:?}",
            object_type, valid_types
        )));
    }

    let sql = match object_type {
        "all_tables_in_schema" => format!(
            "GRANT {} ON ALL TABLES IN SCHEMA {} TO {}",
            privilege,
            quote_ident(schema),
            quote_ident(grantee)
        ),
        _ => format!(
            "GRANT {} ON {} {} TO {}",
            privilege,
            object_type.to_uppercase(),
            quote_ident(object_name),
            quote_ident(grantee)
        ),
    };

    client.execute(&sql, &[]).await?;
    Ok(json!({ "success": true, "sql": sql }))
}

pub async fn revoke_privileges(client: &Client, params: &Option<&Value>) -> MCPResult<Value> {
    let privilege = params
        .as_ref()
        .and_then(|p| p.get("privilege").and_then(|v| v.as_str()))
        .ok_or_else(|| {
            crate::errors::MCPError::InvalidParams("Missing 'privilege' parameter".into())
        })?;
    let object_type = params
        .as_ref()
        .and_then(|p| p.get("object_type").and_then(|v| v.as_str()))
        .ok_or_else(|| {
            crate::errors::MCPError::InvalidParams("Missing 'object_type' parameter".into())
        })?;
    let object_name = params
        .as_ref()
        .and_then(|p| p.get("object_name").and_then(|v| v.as_str()))
        .ok_or_else(|| {
            crate::errors::MCPError::InvalidParams("Missing 'object_name' parameter".into())
        })?;
    let revokee = params
        .as_ref()
        .and_then(|p| p.get("revokee").and_then(|v| v.as_str()))
        .ok_or_else(|| {
            crate::errors::MCPError::InvalidParams("Missing 'revokee' parameter".into())
        })?;

    let schema = params
        .as_ref()
        .and_then(|p| p.get("schema").and_then(|v| v.as_str()))
        .unwrap_or("public");

    crate::validation::validate_privilege_list(privilege)?;

    let valid_types = [
        "table",
        "sequence",
        "schema",
        "database",
        "all_tables_in_schema",
    ];
    if !valid_types.contains(&object_type) {
        return Err(crate::errors::MCPError::InvalidParams(format!(
            "Unsupported object_type '{}'. Use: {:?}",
            object_type, valid_types
        )));
    }

    let sql = match object_type {
        "all_tables_in_schema" => format!(
            "REVOKE {} ON ALL TABLES IN SCHEMA {} FROM {}",
            privilege,
            quote_ident(schema),
            quote_ident(revokee)
        ),
        _ => format!(
            "REVOKE {} ON {} {} FROM {}",
            privilege,
            object_type.to_uppercase(),
            quote_ident(object_name),
            quote_ident(revokee)
        ),
    };

    client.execute(&sql, &[]).await?;
    Ok(json!({ "success": true, "sql": sql }))
}

fn quote_ident(ident: &str) -> String {
    crate::validation::quote_ident(ident)
}