postgres-mcp-readonly 0.1.7

Read-only MCP server for PostgreSQL and TimescaleDB
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! Command line, shared state, HTTP router, stdio serving and the local health check.

use std::collections::HashMap;
use std::io::{Read, Write};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, TcpStream};
use std::process::ExitCode;
use std::sync::Arc;
use std::time::Duration;

use axum::Router;
use axum::body::{Body, to_bytes};
use axum::error_handling::HandleErrorLayer;
use axum::extract::{Request, State};
use axum::http::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE};
use axum::http::{HeaderName, HeaderValue, Method, StatusCode};
use axum::middleware::{Next, from_fn_with_state};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use rmcp::transport::streamable_http_server::session::never::NeverSessionManager;
use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
use tower::limit::ConcurrencyLimitLayer;
use tower::timeout::TimeoutLayer;
use tower::{BoxError, ServiceBuilder};
use tower_http::cors::{AllowOrigin, CorsLayer};
use tower_http::trace::TraceLayer;
use tracing_subscriber::EnvFilter;

use crate::config::{Config, ConfigError, DatabaseConfig, LogFormat};
use crate::http_guard::{ApiKey, GuardState};
use crate::pg::pool::Pool;
use crate::tools::{PgMcp, ToolError};

const USAGE: &str = "Usage: postgres-mcp [http|stdio|healthcheck|--help|-h|--version|-V]

Commands:
  http         serve MCP over Streamable HTTP (default)
  stdio        serve MCP over stdin and stdout
  healthcheck  exit 0 when the local HTTP server answers /health

Configuration is read from environment variables, see README.";

const HEALTH_TIMEOUT: Duration = Duration::from_secs(3);
const DEFAULT_MCP_PORT: u16 = 8432;

/// Shared by every request: the configuration and one lazy pool per database.
pub struct AppState {
    pub config: Arc<Config>,
    pools: HashMap<String, Arc<Pool>>,
}

impl AppState {
    pub fn new(config: Config) -> AppState {
        let pools = config
            .databases
            .iter()
            .map(|db| {
                (
                    db.name.clone(),
                    Arc::new(
                        Pool::with_auth(db.connect.clone(), db.max_connections, db.auth.clone())
                            .with_tls(db.tls.clone())
                            .with_name(&db.name),
                    ),
                )
            })
            .collect();
        AppState {
            config: Arc::new(config),
            pools,
        }
    }

    /// The database entry and its pool; `None` selects the only configured database.
    pub fn pool(&self, database: Option<&str>) -> Result<(&DatabaseConfig, Arc<Pool>), ToolError> {
        let db = self
            .config
            .database(database)
            .map_err(|e: ConfigError| ToolError::Config(e.0))?;
        let pool = self
            .pools
            .get(&db.name)
            .cloned()
            .ok_or_else(|| ToolError::Internal(format!("no pool for database {}", db.name)))?;
        Ok((db, pool))
    }

    /// The configured name the database argument selects, or None when it selects nothing.
    pub fn resolve_name(&self, database: Option<&str>) -> Option<String> {
        self.config
            .database(database)
            .ok()
            .map(|db| db.name.clone())
    }

    /// Closes every pool; later checkouts fail.
    pub async fn close(&self) {
        for pool in self.pools.values() {
            pool.close().await;
        }
    }
}

/// Entry point of the binary: parses the command line and runs the chosen mode.
pub async fn run() -> ExitCode {
    let args: Vec<String> = std::env::args_os()
        .skip(1)
        .map(|arg| arg.to_string_lossy().into_owned())
        .collect();
    match args.as_slice() {
        [] => serve_http().await,
        [command] => match command.as_str() {
            "http" => serve_http().await,
            "stdio" => serve_stdio().await,
            "healthcheck" => healthcheck(),
            "--help" | "-h" => {
                println!("{USAGE}");
                ExitCode::SUCCESS
            }
            "--version" | "-V" => {
                println!("postgres-mcp {}", env!("CARGO_PKG_VERSION"));
                ExitCode::SUCCESS
            }
            _ => usage_error(),
        },
        _ => usage_error(),
    }
}

fn usage_error() -> ExitCode {
    eprintln!("{USAGE}");
    ExitCode::from(2)
}

fn config_error(message: &str) -> ExitCode {
    eprintln!("configuration error: {message}");
    ExitCode::from(2)
}

/// Installs the stderr subscriber. The filter comes from RUST_LOG, else LOG_LEVEL, else info.
fn init_logging(format: LogFormat) -> Result<(), String> {
    let (variable, directives) = match env_value("RUST_LOG")? {
        Some(value) => ("RUST_LOG", value),
        None => match env_value("LOG_LEVEL")? {
            Some(value) => ("LOG_LEVEL", level_filter(&value)),
            None => ("LOG_LEVEL", "info,rmcp=warn".to_owned()),
        },
    };
    let filter = EnvFilter::try_new(&directives).map_err(|e| format!("{variable}: {e}"))?;
    // Colour only when stderr is a terminal, so piped logs stay plain text.
    let builder = tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_writer(std::io::stderr)
        .with_ansi(std::io::IsTerminal::is_terminal(&std::io::stderr()));
    let installed = match format {
        LogFormat::Text => builder.try_init(),
        LogFormat::Json => builder.json().try_init(),
    };
    installed.map_err(|e| format!("cannot start logging: {e}"))?;
    if rmcp_at_debug(&directives) {
        tracing::warn!(
            "debug logging is on: requests and responses, including SQL text and rows, are written to the log"
        );
    }
    Ok(())
}

/// The filter for LOG_LEVEL: the level, with the rmcp protocol library held at warn unless it is debug or trace.
fn level_filter(level: &str) -> String {
    if level.eq_ignore_ascii_case("debug") || level.eq_ignore_ascii_case("trace") {
        level.to_owned()
    } else {
        format!("{level},rmcp=warn")
    }
}

/// True when the directives make rmcp log at debug or trace. A directive for rmcp or its modules
/// overrides the bare level, as in EnvFilter, and the last one of each kind decides.
fn rmcp_at_debug(directives: &str) -> bool {
    let mut bare: Option<&str> = None;
    let mut rmcp: Option<&str> = None;
    for part in directives.split(',').map(str::trim) {
        match part.split_once('=') {
            Some((target, level)) if target == "rmcp" || target.starts_with("rmcp::") => {
                rmcp = Some(level.trim());
            }
            Some(_) => {}
            None if part == "rmcp" => rmcp = Some("trace"),
            None if !part.is_empty() => bare = Some(part),
            None => {}
        }
    }
    let level = rmcp.or(bare).unwrap_or("info");
    level.eq_ignore_ascii_case("debug") || level.eq_ignore_ascii_case("trace")
}

/// A variable's value; unset and empty both count as unset.
fn env_value(name: &str) -> Result<Option<String>, String> {
    match std::env::var(name) {
        Ok(value) if value.is_empty() => Ok(None),
        Ok(value) => Ok(Some(value)),
        Err(std::env::VarError::NotPresent) => Ok(None),
        Err(std::env::VarError::NotUnicode(_)) => Err(format!("{name}: value is not valid UTF-8")),
    }
}

/// Reads the configuration and starts logging; a failure is reported and returned as the exit code.
fn start(config: Result<Config, ConfigError>) -> Result<Config, ExitCode> {
    let config = config.map_err(|e| config_error(&e.0))?;
    init_logging(config.log_format).map_err(|e| config_error(&e))?;
    log_tls_settings(&config);
    Ok(config)
}

/// One info line per database: its sslmode, and whether a root and a client certificate are configured.
fn log_tls_settings(config: &Config) {
    for db in &config.databases {
        tracing::info!(
            database = %db.name,
            tls = db.connect.ssl_mode.as_str(),
            custom_root = db.tls_sources.root.is_some(),
            client_cert = db.tls_sources.client_cert.is_some(),
            "database TLS settings"
        );
    }
}

async fn serve_http() -> ExitCode {
    let config = match start(Config::from_env()) {
        Ok(config) => config,
        Err(code) => return code,
    };
    let host = config.host;
    let port = config.port;
    let api_key_set = config.api_key.is_some();
    let names = database_names(&config);
    let state = Arc::new(AppState::new(config));
    let addr = SocketAddr::new(host, port);

    let listener = match tokio::net::TcpListener::bind(addr).await {
        Ok(listener) => listener,
        Err(error) => {
            tracing::error!(address = %addr, error = %error, "cannot bind the HTTP address");
            state.close().await;
            return ExitCode::FAILURE;
        }
    };
    tracing::info!(
        address = %addr,
        databases = %names,
        api_key = api_key_set,
        "serving MCP over Streamable HTTP"
    );
    if !host.is_loopback() && !api_key_set {
        tracing::warn!(address = %addr, "listening on a non-loopback address without an API key");
    }

    let served = axum::serve(listener, build_router(state.clone()))
        .with_graceful_shutdown(shutdown_signal())
        .await;
    state.close().await;
    match served {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            tracing::error!(error = %error, "HTTP server failed");
            ExitCode::FAILURE
        }
    }
}

async fn serve_stdio() -> ExitCode {
    let config = match start(Config::from_env()) {
        Ok(config) => config,
        Err(code) => return code,
    };
    let state = Arc::new(AppState::new(config));
    let transport = rmcp::transport::io::stdio();
    let running = match rmcp::serve_server(PgMcp::new(state.clone()), transport).await {
        Ok(running) => running,
        Err(error) => {
            tracing::error!(error = %error, "cannot start the stdio session");
            state.close().await;
            return ExitCode::FAILURE;
        }
    };
    let outcome = running.waiting().await;
    state.close().await;
    match outcome {
        Ok(_) => ExitCode::SUCCESS,
        Err(error) => {
            tracing::error!(error = %error, "stdio session ended abnormally");
            ExitCode::FAILURE
        }
    }
}

fn database_names(config: &Config) -> String {
    config
        .databases
        .iter()
        .map(|d| d.name.as_str())
        .collect::<Vec<_>>()
        .join(", ")
}

/// Resolves when SIGINT or SIGTERM arrives. A failed signal registration is logged and never fires.
async fn shutdown_signal() {
    let interrupt = async {
        if let Err(error) = tokio::signal::ctrl_c().await {
            tracing::error!(error = %error, "cannot listen for SIGINT");
            std::future::pending::<()>().await;
        }
    };
    #[cfg(unix)]
    let terminate = async {
        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
            Ok(mut stream) => {
                stream.recv().await;
            }
            Err(error) => {
                tracing::error!(error = %error, "cannot listen for SIGTERM");
                std::future::pending::<()>().await;
            }
        }
    };
    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();
    tokio::select! {
        () = interrupt => {}
        () = terminate => {}
    }
    tracing::info!("shutdown signal received");
}

/// The HTTP router: `/health` open, `/mcp` behind the guard, every other path 404.
pub fn build_router(state: Arc<AppState>) -> Router {
    let timeout = request_timeout(&state.config);
    build_router_with_request_timeout(state, timeout)
}

/// The longest a /mcp request may take, body included: the largest statement timeout of any database plus 30 seconds.
fn request_timeout(config: &Config) -> Duration {
    let statement_ms = config
        .databases
        .iter()
        .map(|db| db.statement_timeout_ms)
        .max()
        .unwrap_or(0);
    Duration::from_millis(statement_ms) + Duration::from_secs(30)
}

/// The router with `timeout` as the limit for each /mcp request; a request past it gets 408.
pub fn build_router_with_request_timeout(state: Arc<AppState>, timeout: Duration) -> Router {
    let config = state.config.clone();
    let limits = &config.limits;

    let mut allowed_hosts = vec![
        "localhost".to_owned(),
        "127.0.0.1".to_owned(),
        "::1".to_owned(),
    ];
    allowed_hosts.extend(config.allowed_hosts.iter().cloned());
    let mcp_config = StreamableHttpServerConfig::default()
        .with_legacy_session_mode(false)
        .with_json_response(true)
        .with_allowed_hosts(allowed_hosts)
        .with_max_request_body_bytes(limits.max_request_bytes);
    let factory_state = state.clone();
    let service = StreamableHttpService::new(
        move || Ok(PgMcp::new(factory_state.clone())),
        Arc::new(NeverSessionManager::default()),
        mcp_config,
    );
    let guard = GuardState {
        api_key: config.api_key.as_deref().map(ApiKey::new),
        allowed_origins: Arc::new(config.allowed_origins.clone()),
    };
    let mcp = Router::new()
        .route_service("/mcp", service)
        .layer(ConcurrencyLimitLayer::new(limits.max_concurrent_requests))
        .layer(from_fn_with_state(
            limits.max_request_bytes,
            buffer_request_body,
        ))
        .layer(from_fn_with_state(guard, crate::http_guard::guard))
        .layer(
            ServiceBuilder::new()
                .layer(HandleErrorLayer::new(request_timed_out))
                .layer(TimeoutLayer::new(timeout)),
        );

    let mut router = Router::new().route("/health", get(health)).merge(mcp);
    if !config.allowed_origins.is_empty() {
        router = router.layer(cors_layer(&config.allowed_origins));
    }
    router.layer(TraceLayer::new_for_http())
}

/// The Display text of http_body_util's LengthLimitError, which is what `to_bytes` reports for an oversized body.
const LENGTH_LIMIT_TEXT: &str = "length limit exceeded";

/// Buffers the body up to `max` bytes, so a chunked body over the limit gets the same 413 as a sized one.
/// Any other read failure, such as an aborted client, is a 400.
async fn buffer_request_body(State(max): State<usize>, request: Request, next: Next) -> Response {
    let (parts, body) = request.into_parts();
    match to_bytes(body, max).await {
        Ok(bytes) => {
            next.run(Request::from_parts(parts, Body::from(bytes)))
                .await
        }
        Err(error) if error.to_string() == LENGTH_LIMIT_TEXT => payload_too_large(max),
        Err(_) => bad_request(),
    }
}

/// The 408 for a /mcp request that ran past its timeout, including a body that never finished arriving.
async fn request_timed_out(_error: BoxError) -> Response {
    (
        StatusCode::REQUEST_TIMEOUT,
        [(CONTENT_TYPE, "application/json")],
        r#"{"error":"request_timeout","message":"The request took too long."}"#,
    )
        .into_response()
}

fn bad_request() -> Response {
    (
        StatusCode::BAD_REQUEST,
        [(CONTENT_TYPE, "application/json")],
        r#"{"error":"bad_request","message":"Could not read the request body."}"#,
    )
        .into_response()
}

fn payload_too_large(max: usize) -> Response {
    let body =
        format!(r#"{{"error":"payload_too_large","message":"Request body exceeds {max} bytes."}}"#);
    (
        StatusCode::PAYLOAD_TOO_LARGE,
        [(CONTENT_TYPE, "application/json")],
        body,
    )
        .into_response()
}

async fn health() -> impl IntoResponse {
    ([(CONTENT_TYPE, "text/plain; charset=utf-8")], "ok")
}

/// CORS for exactly the configured origins, normalised the way the guard compares them.
fn cors_layer(origins: &[String]) -> CorsLayer {
    // The config already rejected anything that is not an origin, so every entry serialises.
    let values: Vec<HeaderValue> = origins
        .iter()
        .filter_map(|origin| url::Url::parse(origin).ok())
        .filter_map(|url| HeaderValue::from_str(&url.origin().ascii_serialization()).ok())
        .collect();
    CorsLayer::new()
        .allow_origin(AllowOrigin::list(values))
        .allow_methods([Method::GET, Method::POST, Method::OPTIONS])
        .allow_headers([
            ACCEPT,
            AUTHORIZATION,
            CONTENT_TYPE,
            HeaderName::from_static("x-api-key"),
            HeaderName::from_static("mcp-protocol-version"),
            HeaderName::from_static("mcp-method"),
            HeaderName::from_static("mcp-name"),
            HeaderName::from_static("mcp-session-id"),
        ])
}

/// Probes `/health` on the address MCP_HOST names and exits 0 only for a 200 status line.
fn healthcheck() -> ExitCode {
    let port = match env_value("MCP_PORT") {
        Ok(None) => DEFAULT_MCP_PORT,
        Ok(Some(raw)) => match raw.parse::<u16>() {
            Ok(port) if port > 0 => port,
            _ => return config_error(&format!("MCP_PORT: \"{raw}\" is not a port number")),
        },
        Err(message) => return config_error(&message),
    };
    let host = match env_value("MCP_HOST") {
        Ok(None) => IpAddr::V4(Ipv4Addr::LOCALHOST),
        Ok(Some(raw)) => match raw.parse::<IpAddr>() {
            Ok(host) => host,
            Err(_) => {
                return config_error(&format!(
                    "MCP_HOST: \"{raw}\" is not an IP address; use 127.0.0.1 or ::1"
                ));
            }
        },
        Err(message) => return config_error(&message),
    };
    if probe_health(SocketAddr::new(probe_address(host), port)) {
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    }
}

/// The address a local probe connects to: loopback in place of an unspecified bind address.
fn probe_address(host: IpAddr) -> IpAddr {
    match host {
        IpAddr::V4(v4) if v4.is_unspecified() => IpAddr::V4(Ipv4Addr::LOCALHOST),
        IpAddr::V6(v6) if v6.is_unspecified() => IpAddr::V6(Ipv6Addr::LOCALHOST),
        other => other,
    }
}

fn probe_health(addr: SocketAddr) -> bool {
    let Ok(mut stream) = TcpStream::connect_timeout(&addr, HEALTH_TIMEOUT) else {
        return false;
    };
    if stream.set_read_timeout(Some(HEALTH_TIMEOUT)).is_err()
        || stream.set_write_timeout(Some(HEALTH_TIMEOUT)).is_err()
    {
        return false;
    }
    let request = b"GET /health HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
    if stream.write_all(request).is_err() {
        return false;
    }
    let mut received = Vec::new();
    let mut chunk = [0_u8; 512];
    // Stops at the end of the status line, at EOF, or on a read error or timeout (which fails the probe).
    while !received.windows(2).any(|pair| pair == b"\r\n") {
        match stream.read(&mut chunk) {
            Ok(0) => break,
            Ok(n) => received.extend_from_slice(&chunk[..n]),
            Err(_) => return false,
        }
    }
    let text = String::from_utf8_lossy(&received);
    text.lines()
        .next()
        .is_some_and(|status| status.contains(" 200 "))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn probe_address_maps_unspecified_hosts_to_loopback() {
        let v4_any = IpAddr::V4(Ipv4Addr::UNSPECIFIED);
        let v6_any = IpAddr::V6(Ipv6Addr::UNSPECIFIED);
        let v6_loop = IpAddr::V6(Ipv6Addr::LOCALHOST);
        let lan = IpAddr::V4(Ipv4Addr::new(10, 1, 2, 3));
        assert_eq!(probe_address(v4_any), IpAddr::V4(Ipv4Addr::LOCALHOST));
        assert_eq!(probe_address(v6_any), IpAddr::V6(Ipv6Addr::LOCALHOST));
        assert_eq!(probe_address(v6_loop), IpAddr::V6(Ipv6Addr::LOCALHOST));
        assert_eq!(probe_address(lan), lan);
    }
}