Skip to main content

postgres_mcp/
server.rs

1//! Command line, shared state, HTTP router, stdio serving and the local health check.
2
3use std::collections::HashMap;
4use std::io::{Read, Write};
5use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, TcpStream};
6use std::process::ExitCode;
7use std::sync::Arc;
8use std::time::Duration;
9
10use axum::Router;
11use axum::body::{Body, to_bytes};
12use axum::error_handling::HandleErrorLayer;
13use axum::extract::{Request, State};
14use axum::http::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE};
15use axum::http::{HeaderName, HeaderValue, Method, StatusCode};
16use axum::middleware::{Next, from_fn_with_state};
17use axum::response::{IntoResponse, Response};
18use axum::routing::get;
19use rmcp::transport::streamable_http_server::session::never::NeverSessionManager;
20use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
21use tower::limit::ConcurrencyLimitLayer;
22use tower::timeout::TimeoutLayer;
23use tower::{BoxError, ServiceBuilder};
24use tower_http::cors::{AllowOrigin, CorsLayer};
25use tower_http::trace::TraceLayer;
26use tracing_subscriber::EnvFilter;
27
28use crate::config::{Config, ConfigError, DatabaseConfig, LogFormat};
29use crate::http_guard::{ApiKey, GuardState};
30use crate::pg::pool::Pool;
31use crate::tools::{PgMcp, ToolError};
32
33const USAGE: &str = "Usage: postgres-mcp [http|stdio|healthcheck|--help|-h|--version|-V]
34
35Commands:
36  http         serve MCP over Streamable HTTP (default)
37  stdio        serve MCP over stdin and stdout
38  healthcheck  exit 0 when the local HTTP server answers /health
39
40Configuration is read from environment variables, see README.";
41
42const HEALTH_TIMEOUT: Duration = Duration::from_secs(3);
43const DEFAULT_MCP_PORT: u16 = 8432;
44
45/// Shared by every request: the configuration and one lazy pool per database.
46pub struct AppState {
47    pub config: Arc<Config>,
48    pools: HashMap<String, Arc<Pool>>,
49}
50
51impl AppState {
52    pub fn new(config: Config) -> AppState {
53        let pools = config
54            .databases
55            .iter()
56            .map(|db| {
57                (
58                    db.name.clone(),
59                    Arc::new(
60                        Pool::with_auth(db.connect.clone(), db.max_connections, db.auth.clone())
61                            .with_tls(db.tls.clone())
62                            .with_name(&db.name),
63                    ),
64                )
65            })
66            .collect();
67        AppState {
68            config: Arc::new(config),
69            pools,
70        }
71    }
72
73    /// The database entry and its pool; `None` selects the only configured database.
74    pub fn pool(&self, database: Option<&str>) -> Result<(&DatabaseConfig, Arc<Pool>), ToolError> {
75        let db = self
76            .config
77            .database(database)
78            .map_err(|e: ConfigError| ToolError::Config(e.0))?;
79        let pool = self
80            .pools
81            .get(&db.name)
82            .cloned()
83            .ok_or_else(|| ToolError::Internal(format!("no pool for database {}", db.name)))?;
84        Ok((db, pool))
85    }
86
87    /// The configured name the database argument selects, or None when it selects nothing.
88    pub fn resolve_name(&self, database: Option<&str>) -> Option<String> {
89        self.config
90            .database(database)
91            .ok()
92            .map(|db| db.name.clone())
93    }
94
95    /// Closes every pool; later checkouts fail.
96    pub async fn close(&self) {
97        for pool in self.pools.values() {
98            pool.close().await;
99        }
100    }
101}
102
103/// Entry point of the binary: parses the command line and runs the chosen mode.
104pub async fn run() -> ExitCode {
105    let args: Vec<String> = std::env::args_os()
106        .skip(1)
107        .map(|arg| arg.to_string_lossy().into_owned())
108        .collect();
109    match args.as_slice() {
110        [] => serve_http().await,
111        [command] => match command.as_str() {
112            "http" => serve_http().await,
113            "stdio" => serve_stdio().await,
114            "healthcheck" => healthcheck(),
115            "--help" | "-h" => {
116                println!("{USAGE}");
117                ExitCode::SUCCESS
118            }
119            "--version" | "-V" => {
120                println!("postgres-mcp {}", env!("CARGO_PKG_VERSION"));
121                ExitCode::SUCCESS
122            }
123            _ => usage_error(),
124        },
125        _ => usage_error(),
126    }
127}
128
129fn usage_error() -> ExitCode {
130    eprintln!("{USAGE}");
131    ExitCode::from(2)
132}
133
134fn config_error(message: &str) -> ExitCode {
135    eprintln!("configuration error: {message}");
136    ExitCode::from(2)
137}
138
139/// Installs the stderr subscriber. The filter comes from RUST_LOG, else LOG_LEVEL, else info.
140fn init_logging(format: LogFormat) -> Result<(), String> {
141    let (variable, directives) = match env_value("RUST_LOG")? {
142        Some(value) => ("RUST_LOG", value),
143        None => match env_value("LOG_LEVEL")? {
144            Some(value) => ("LOG_LEVEL", level_filter(&value)),
145            None => ("LOG_LEVEL", "info,rmcp=warn".to_owned()),
146        },
147    };
148    let filter = EnvFilter::try_new(&directives).map_err(|e| format!("{variable}: {e}"))?;
149    // Colour only when stderr is a terminal, so piped logs stay plain text.
150    let builder = tracing_subscriber::fmt()
151        .with_env_filter(filter)
152        .with_writer(std::io::stderr)
153        .with_ansi(std::io::IsTerminal::is_terminal(&std::io::stderr()));
154    let installed = match format {
155        LogFormat::Text => builder.try_init(),
156        LogFormat::Json => builder.json().try_init(),
157    };
158    installed.map_err(|e| format!("cannot start logging: {e}"))?;
159    if rmcp_at_debug(&directives) {
160        tracing::warn!(
161            "debug logging is on: requests and responses, including SQL text and rows, are written to the log"
162        );
163    }
164    Ok(())
165}
166
167/// The filter for LOG_LEVEL: the level, with the rmcp protocol library held at warn unless it is debug or trace.
168fn level_filter(level: &str) -> String {
169    if level.eq_ignore_ascii_case("debug") || level.eq_ignore_ascii_case("trace") {
170        level.to_owned()
171    } else {
172        format!("{level},rmcp=warn")
173    }
174}
175
176/// True when the directives make rmcp log at debug or trace. A directive for rmcp or its modules
177/// overrides the bare level, as in EnvFilter, and the last one of each kind decides.
178fn rmcp_at_debug(directives: &str) -> bool {
179    let mut bare: Option<&str> = None;
180    let mut rmcp: Option<&str> = None;
181    for part in directives.split(',').map(str::trim) {
182        match part.split_once('=') {
183            Some((target, level)) if target == "rmcp" || target.starts_with("rmcp::") => {
184                rmcp = Some(level.trim());
185            }
186            Some(_) => {}
187            None if part == "rmcp" => rmcp = Some("trace"),
188            None if !part.is_empty() => bare = Some(part),
189            None => {}
190        }
191    }
192    let level = rmcp.or(bare).unwrap_or("info");
193    level.eq_ignore_ascii_case("debug") || level.eq_ignore_ascii_case("trace")
194}
195
196/// A variable's value; unset and empty both count as unset.
197fn env_value(name: &str) -> Result<Option<String>, String> {
198    match std::env::var(name) {
199        Ok(value) if value.is_empty() => Ok(None),
200        Ok(value) => Ok(Some(value)),
201        Err(std::env::VarError::NotPresent) => Ok(None),
202        Err(std::env::VarError::NotUnicode(_)) => Err(format!("{name}: value is not valid UTF-8")),
203    }
204}
205
206/// Reads the configuration and starts logging; a failure is reported and returned as the exit code.
207fn start(config: Result<Config, ConfigError>) -> Result<Config, ExitCode> {
208    let config = config.map_err(|e| config_error(&e.0))?;
209    init_logging(config.log_format).map_err(|e| config_error(&e))?;
210    log_tls_settings(&config);
211    Ok(config)
212}
213
214/// One info line per database: its sslmode, and whether a root and a client certificate are configured.
215fn log_tls_settings(config: &Config) {
216    for db in &config.databases {
217        tracing::info!(
218            database = %db.name,
219            tls = db.connect.ssl_mode.as_str(),
220            custom_root = db.tls_sources.root.is_some(),
221            client_cert = db.tls_sources.client_cert.is_some(),
222            "database TLS settings"
223        );
224    }
225}
226
227async fn serve_http() -> ExitCode {
228    let config = match start(Config::from_env()) {
229        Ok(config) => config,
230        Err(code) => return code,
231    };
232    let host = config.host;
233    let port = config.port;
234    let api_key_set = config.api_key.is_some();
235    let names = database_names(&config);
236    let state = Arc::new(AppState::new(config));
237    let addr = SocketAddr::new(host, port);
238
239    let listener = match tokio::net::TcpListener::bind(addr).await {
240        Ok(listener) => listener,
241        Err(error) => {
242            tracing::error!(address = %addr, error = %error, "cannot bind the HTTP address");
243            state.close().await;
244            return ExitCode::FAILURE;
245        }
246    };
247    tracing::info!(
248        address = %addr,
249        databases = %names,
250        api_key = api_key_set,
251        "serving MCP over Streamable HTTP"
252    );
253    if !host.is_loopback() && !api_key_set {
254        tracing::warn!(address = %addr, "listening on a non-loopback address without an API key");
255    }
256
257    let served = axum::serve(listener, build_router(state.clone()))
258        .with_graceful_shutdown(shutdown_signal())
259        .await;
260    state.close().await;
261    match served {
262        Ok(()) => ExitCode::SUCCESS,
263        Err(error) => {
264            tracing::error!(error = %error, "HTTP server failed");
265            ExitCode::FAILURE
266        }
267    }
268}
269
270async fn serve_stdio() -> ExitCode {
271    let config = match start(Config::from_env()) {
272        Ok(config) => config,
273        Err(code) => return code,
274    };
275    let state = Arc::new(AppState::new(config));
276    let transport = rmcp::transport::io::stdio();
277    let running = match rmcp::serve_server(PgMcp::new(state.clone()), transport).await {
278        Ok(running) => running,
279        Err(error) => {
280            tracing::error!(error = %error, "cannot start the stdio session");
281            state.close().await;
282            return ExitCode::FAILURE;
283        }
284    };
285    let outcome = running.waiting().await;
286    state.close().await;
287    match outcome {
288        Ok(_) => ExitCode::SUCCESS,
289        Err(error) => {
290            tracing::error!(error = %error, "stdio session ended abnormally");
291            ExitCode::FAILURE
292        }
293    }
294}
295
296fn database_names(config: &Config) -> String {
297    config
298        .databases
299        .iter()
300        .map(|d| d.name.as_str())
301        .collect::<Vec<_>>()
302        .join(", ")
303}
304
305/// Resolves when SIGINT or SIGTERM arrives. A failed signal registration is logged and never fires.
306async fn shutdown_signal() {
307    let interrupt = async {
308        if let Err(error) = tokio::signal::ctrl_c().await {
309            tracing::error!(error = %error, "cannot listen for SIGINT");
310            std::future::pending::<()>().await;
311        }
312    };
313    #[cfg(unix)]
314    let terminate = async {
315        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
316            Ok(mut stream) => {
317                stream.recv().await;
318            }
319            Err(error) => {
320                tracing::error!(error = %error, "cannot listen for SIGTERM");
321                std::future::pending::<()>().await;
322            }
323        }
324    };
325    #[cfg(not(unix))]
326    let terminate = std::future::pending::<()>();
327    tokio::select! {
328        () = interrupt => {}
329        () = terminate => {}
330    }
331    tracing::info!("shutdown signal received");
332}
333
334/// The HTTP router: `/health` open, `/mcp` behind the guard, every other path 404.
335pub fn build_router(state: Arc<AppState>) -> Router {
336    let timeout = request_timeout(&state.config);
337    build_router_with_request_timeout(state, timeout)
338}
339
340/// The longest a /mcp request may take, body included: the largest statement timeout of any database plus 30 seconds.
341fn request_timeout(config: &Config) -> Duration {
342    let statement_ms = config
343        .databases
344        .iter()
345        .map(|db| db.statement_timeout_ms)
346        .max()
347        .unwrap_or(0);
348    Duration::from_millis(statement_ms) + Duration::from_secs(30)
349}
350
351/// The router with `timeout` as the limit for each /mcp request; a request past it gets 408.
352pub fn build_router_with_request_timeout(state: Arc<AppState>, timeout: Duration) -> Router {
353    let config = state.config.clone();
354    let limits = &config.limits;
355
356    let mut allowed_hosts = vec![
357        "localhost".to_owned(),
358        "127.0.0.1".to_owned(),
359        "::1".to_owned(),
360    ];
361    allowed_hosts.extend(config.allowed_hosts.iter().cloned());
362    let mcp_config = StreamableHttpServerConfig::default()
363        .with_legacy_session_mode(false)
364        .with_json_response(true)
365        .with_allowed_hosts(allowed_hosts)
366        .with_max_request_body_bytes(limits.max_request_bytes);
367    let factory_state = state.clone();
368    let service = StreamableHttpService::new(
369        move || Ok(PgMcp::new(factory_state.clone())),
370        Arc::new(NeverSessionManager::default()),
371        mcp_config,
372    );
373    let guard = GuardState {
374        api_key: config.api_key.as_deref().map(ApiKey::new),
375        allowed_origins: Arc::new(config.allowed_origins.clone()),
376    };
377    let mcp = Router::new()
378        .route_service("/mcp", service)
379        .layer(ConcurrencyLimitLayer::new(limits.max_concurrent_requests))
380        .layer(from_fn_with_state(
381            limits.max_request_bytes,
382            buffer_request_body,
383        ))
384        .layer(from_fn_with_state(guard, crate::http_guard::guard))
385        .layer(
386            ServiceBuilder::new()
387                .layer(HandleErrorLayer::new(request_timed_out))
388                .layer(TimeoutLayer::new(timeout)),
389        );
390
391    let mut router = Router::new().route("/health", get(health)).merge(mcp);
392    if !config.allowed_origins.is_empty() {
393        router = router.layer(cors_layer(&config.allowed_origins));
394    }
395    router.layer(TraceLayer::new_for_http())
396}
397
398/// The Display text of http_body_util's LengthLimitError, which is what `to_bytes` reports for an oversized body.
399const LENGTH_LIMIT_TEXT: &str = "length limit exceeded";
400
401/// Buffers the body up to `max` bytes, so a chunked body over the limit gets the same 413 as a sized one.
402/// Any other read failure, such as an aborted client, is a 400.
403async fn buffer_request_body(State(max): State<usize>, request: Request, next: Next) -> Response {
404    let (parts, body) = request.into_parts();
405    match to_bytes(body, max).await {
406        Ok(bytes) => {
407            next.run(Request::from_parts(parts, Body::from(bytes)))
408                .await
409        }
410        Err(error) if error.to_string() == LENGTH_LIMIT_TEXT => payload_too_large(max),
411        Err(_) => bad_request(),
412    }
413}
414
415/// The 408 for a /mcp request that ran past its timeout, including a body that never finished arriving.
416async fn request_timed_out(_error: BoxError) -> Response {
417    (
418        StatusCode::REQUEST_TIMEOUT,
419        [(CONTENT_TYPE, "application/json")],
420        r#"{"error":"request_timeout","message":"The request took too long."}"#,
421    )
422        .into_response()
423}
424
425fn bad_request() -> Response {
426    (
427        StatusCode::BAD_REQUEST,
428        [(CONTENT_TYPE, "application/json")],
429        r#"{"error":"bad_request","message":"Could not read the request body."}"#,
430    )
431        .into_response()
432}
433
434fn payload_too_large(max: usize) -> Response {
435    let body =
436        format!(r#"{{"error":"payload_too_large","message":"Request body exceeds {max} bytes."}}"#);
437    (
438        StatusCode::PAYLOAD_TOO_LARGE,
439        [(CONTENT_TYPE, "application/json")],
440        body,
441    )
442        .into_response()
443}
444
445async fn health() -> impl IntoResponse {
446    ([(CONTENT_TYPE, "text/plain; charset=utf-8")], "ok")
447}
448
449/// CORS for exactly the configured origins, normalised the way the guard compares them.
450fn cors_layer(origins: &[String]) -> CorsLayer {
451    // The config already rejected anything that is not an origin, so every entry serialises.
452    let values: Vec<HeaderValue> = origins
453        .iter()
454        .filter_map(|origin| url::Url::parse(origin).ok())
455        .filter_map(|url| HeaderValue::from_str(&url.origin().ascii_serialization()).ok())
456        .collect();
457    CorsLayer::new()
458        .allow_origin(AllowOrigin::list(values))
459        .allow_methods([Method::GET, Method::POST, Method::OPTIONS])
460        .allow_headers([
461            ACCEPT,
462            AUTHORIZATION,
463            CONTENT_TYPE,
464            HeaderName::from_static("x-api-key"),
465            HeaderName::from_static("mcp-protocol-version"),
466            HeaderName::from_static("mcp-method"),
467            HeaderName::from_static("mcp-name"),
468            HeaderName::from_static("mcp-session-id"),
469        ])
470}
471
472/// Probes `/health` on the address MCP_HOST names and exits 0 only for a 200 status line.
473fn healthcheck() -> ExitCode {
474    let port = match env_value("MCP_PORT") {
475        Ok(None) => DEFAULT_MCP_PORT,
476        Ok(Some(raw)) => match raw.parse::<u16>() {
477            Ok(port) if port > 0 => port,
478            _ => return config_error(&format!("MCP_PORT: \"{raw}\" is not a port number")),
479        },
480        Err(message) => return config_error(&message),
481    };
482    let host = match env_value("MCP_HOST") {
483        Ok(None) => IpAddr::V4(Ipv4Addr::LOCALHOST),
484        Ok(Some(raw)) => match raw.parse::<IpAddr>() {
485            Ok(host) => host,
486            Err(_) => {
487                return config_error(&format!(
488                    "MCP_HOST: \"{raw}\" is not an IP address; use 127.0.0.1 or ::1"
489                ));
490            }
491        },
492        Err(message) => return config_error(&message),
493    };
494    if probe_health(SocketAddr::new(probe_address(host), port)) {
495        ExitCode::SUCCESS
496    } else {
497        ExitCode::FAILURE
498    }
499}
500
501/// The address a local probe connects to: loopback in place of an unspecified bind address.
502fn probe_address(host: IpAddr) -> IpAddr {
503    match host {
504        IpAddr::V4(v4) if v4.is_unspecified() => IpAddr::V4(Ipv4Addr::LOCALHOST),
505        IpAddr::V6(v6) if v6.is_unspecified() => IpAddr::V6(Ipv6Addr::LOCALHOST),
506        other => other,
507    }
508}
509
510fn probe_health(addr: SocketAddr) -> bool {
511    let Ok(mut stream) = TcpStream::connect_timeout(&addr, HEALTH_TIMEOUT) else {
512        return false;
513    };
514    if stream.set_read_timeout(Some(HEALTH_TIMEOUT)).is_err()
515        || stream.set_write_timeout(Some(HEALTH_TIMEOUT)).is_err()
516    {
517        return false;
518    }
519    let request = b"GET /health HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
520    if stream.write_all(request).is_err() {
521        return false;
522    }
523    let mut received = Vec::new();
524    let mut chunk = [0_u8; 512];
525    // Stops at the end of the status line, at EOF, or on a read error or timeout (which fails the probe).
526    while !received.windows(2).any(|pair| pair == b"\r\n") {
527        match stream.read(&mut chunk) {
528            Ok(0) => break,
529            Ok(n) => received.extend_from_slice(&chunk[..n]),
530            Err(_) => return false,
531        }
532    }
533    let text = String::from_utf8_lossy(&received);
534    text.lines()
535        .next()
536        .is_some_and(|status| status.contains(" 200 "))
537}
538
539#[cfg(test)]
540mod tests {
541    use super::*;
542
543    #[test]
544    fn probe_address_maps_unspecified_hosts_to_loopback() {
545        let v4_any = IpAddr::V4(Ipv4Addr::UNSPECIFIED);
546        let v6_any = IpAddr::V6(Ipv6Addr::UNSPECIFIED);
547        let v6_loop = IpAddr::V6(Ipv6Addr::LOCALHOST);
548        let lan = IpAddr::V4(Ipv4Addr::new(10, 1, 2, 3));
549        assert_eq!(probe_address(v4_any), IpAddr::V4(Ipv4Addr::LOCALHOST));
550        assert_eq!(probe_address(v6_any), IpAddr::V6(Ipv6Addr::LOCALHOST));
551        assert_eq!(probe_address(v6_loop), IpAddr::V6(Ipv6Addr::LOCALHOST));
552        assert_eq!(probe_address(lan), lan);
553    }
554}