lemma 0.11.0

A pure, declarative language for business rules.
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
//! Streamable HTTP transport for Lemma MCP (protocol 2026-07-28).
//!
//! Single endpoint `POST /mcp`. No SSE, no sessions, no GET listen stream.

use super::server::{
    error_response, requested_protocol_version, McpDispatcher, McpError, McpRequest, McpResponse,
    HEADER_MISMATCH, LEGACY_PROTOCOL_VERSION, MAX_REQUEST_BYTES, PROTOCOL_VERSION, SERVER_VERSION,
    UNSUPPORTED_PROTOCOL_VERSION,
};
use axum::{
    body::Bytes,
    extract::State,
    http::{header, HeaderMap, StatusCode},
    response::{IntoResponse, Response},
    routing::{get, post},
    Json, Router,
};
use lemma::Engine;
use std::net::SocketAddr;
use std::path::Path;
use tower_http::cors::CorsLayer;
use tracing::{error, info, warn};

/// Listen settings for `lemma mcp --http`.
pub struct McpHttpBind {
    pub host: String,
    pub port: u16,
    pub cors: bool,
}

#[derive(Clone)]
struct HttpState {
    dispatcher: McpDispatcher,
    /// Allowed Origin values when `cors` is false (loopback URLs for this bind).
    allowed_origins: Vec<String>,
    /// When true, any Origin is accepted (and CorsLayer is permissive).
    cors: bool,
}

/// Start Streamable HTTP MCP server. Blocks until SIGINT/SIGTERM (or Ctrl-C).
pub async fn start_http_server(
    engine: Engine,
    config: super::McpConfig,
    workdir: &Path,
    bind: McpHttpBind,
) -> anyhow::Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "lemma_mcp=info,tower_http=info".into()),
        )
        .with_writer(std::io::stderr)
        .init();

    info!(
        "Starting Lemma MCP server v{} (Streamable HTTP)",
        SERVER_VERSION
    );
    info!("Protocol version: {}", PROTOCOL_VERSION);
    if config.write {
        info!("Write mode enabled (--write)");
    } else {
        info!("Read-only mode (default)");
    }

    let request_timeout = config.request_timeout;
    let dispatcher = McpDispatcher::spawn(engine, config, workdir.to_path_buf());

    let allowed_origins = loopback_origins(&bind.host, bind.port);
    let state = HttpState {
        dispatcher,
        allowed_origins,
        cors: bind.cors,
    };

    let router = Router::new()
        .route(
            "/mcp",
            post(mcp_post)
                .get(mcp_method_not_allowed)
                .delete(mcp_method_not_allowed),
        )
        .route("/health", get(health_check))
        .fallback(fallback_404);
    let router = if bind.cors {
        info!("Permissive CORS enabled (--cors): cross-origin browser requests allowed");
        router.layer(CorsLayer::permissive())
    } else {
        router
    };
    let app = router.with_state(state);

    if !matches!(
        bind.host.as_str(),
        "127.0.0.1" | "localhost" | "::1" | "[::1]"
    ) {
        warn!(
            "Binding to non-localhost address {}: the Lemma MCP HTTP server has no \
             built-in authentication or TLS. Deploy behind a reverse proxy that \
             terminates TLS and enforces access control.",
            bind.host
        );
    }

    let addr: SocketAddr = format!("{}:{}", bind.host, bind.port).parse()?;
    let listener = tokio::net::TcpListener::bind(addr).await?;
    // Always print on stderr (tracing filter may hide info!); users need the URL.
    eprintln!("MCP endpoint: http://{}/mcp", addr);
    info!("Lemma MCP listening on http://{}/mcp", addr);
    let os_shutdown_signal = shutdown_signal()?;
    let (drain_timeout_started, drain_timeout_wait) = tokio::sync::oneshot::channel();
    let shutdown = async move {
        os_shutdown_signal.await;
        if drain_timeout_started.send(()).is_err() {
            // serve already finished; drain timer not needed
        }
    };
    let serve_result = tokio::select! {
        result = axum::serve(listener, app).with_graceful_shutdown(shutdown) => {
            if result.is_ok() {
                info!("all connections drained");
            }
            result
        }
        _ = async {
            match drain_timeout_wait.await {
                Ok(()) => {
                    tokio::time::sleep(request_timeout).await;
                    warn!(
                        "drain timeout after {}s, dropping remaining connections",
                        request_timeout.as_secs()
                    );
                }
                Err(_) => std::future::pending::<()>().await,
            }
        } => Ok(())
    };

    serve_result?;
    info!("MCP HTTP server shutting down");
    Ok(())
}

fn loopback_origins(host: &str, port: u16) -> Vec<String> {
    let mut origins = vec![
        format!("http://127.0.0.1:{port}"),
        format!("http://localhost:{port}"),
        format!("http://[::1]:{port}"),
    ];
    // Also allow the exact bind host form when it is a loopback alias.
    if matches!(host, "127.0.0.1" | "localhost" | "::1" | "[::1]") {
        origins.push(format!("http://{host}:{port}"));
    }
    origins.sort();
    origins.dedup();
    origins
}

fn shutdown_signal() -> anyhow::Result<impl std::future::Future<Output = ()>> {
    #[cfg(unix)]
    {
        use tokio::signal::unix::{signal, SignalKind};
        let mut interrupt = signal(SignalKind::interrupt())?;
        let mut terminate = signal(SignalKind::terminate())?;
        Ok(async move {
            tokio::select! {
                _ = interrupt.recv() => {
                    info!("SIGINT received, draining in-flight requests");
                }
                _ = terminate.recv() => {
                    info!("SIGTERM received, draining in-flight requests");
                }
            }
        })
    }
    #[cfg(windows)]
    {
        let mut ctrl_c = tokio::signal::windows::ctrl_c()?;
        Ok(async move {
            ctrl_c.recv().await;
            info!("Ctrl-C received, draining in-flight requests");
        })
    }
    #[cfg(not(any(unix, windows)))]
    {
        anyhow::bail!("shutdown signals are not supported on this platform")
    }
}

async fn health_check() -> impl IntoResponse {
    Json(serde_json::json!({
        "status": "ok",
        "service": "lemma-mcp",
        "version": SERVER_VERSION
    }))
}

async fn mcp_method_not_allowed() -> impl IntoResponse {
    StatusCode::METHOD_NOT_ALLOWED
}

async fn fallback_404() -> impl IntoResponse {
    (
        StatusCode::NOT_FOUND,
        Json(serde_json::json!({
            "error": "Not found. MCP endpoint is POST /mcp; health is GET /health."
        })),
    )
}

async fn mcp_post(State(state): State<HttpState>, headers: HeaderMap, body: Bytes) -> Response {
    if let Some(forbidden) = check_origin(&state, &headers) {
        return forbidden;
    }
    if let Some(not_acceptable) = check_accept(&headers) {
        return not_acceptable;
    }
    if body.len() > MAX_REQUEST_BYTES {
        error!("HTTP body exceeds {} bytes, rejected", MAX_REQUEST_BYTES);
        return json_rpc_http(
            StatusCode::BAD_REQUEST,
            error_response(
                None,
                McpError::parse_error(format!("Request body exceeds {MAX_REQUEST_BYTES} bytes")),
            ),
        );
    }

    let request: McpRequest = match serde_json::from_slice(&body) {
        Ok(r) => r,
        Err(e) => {
            error!("Parse error: {}", e);
            return json_rpc_http(
                StatusCode::BAD_REQUEST,
                error_response(None, McpError::parse_error(format!("Parse error: {e}"))),
            );
        }
    };

    if request.method != "initialize" {
        if let Err(err) = validate_streamable_headers(&headers, &request) {
            return json_rpc_http(
                StatusCode::BAD_REQUEST,
                error_response(request.id.clone(), err),
            );
        }
    }

    let is_notification = request.id.is_none();
    let response = match state.dispatcher.dispatch(request) {
        Ok(r) => r,
        Err(e) => {
            error!("dispatcher error: {e}");
            return json_rpc_http(
                StatusCode::INTERNAL_SERVER_ERROR,
                error_response(
                    None,
                    McpError::internal_error("internal server error".to_string()),
                ),
            );
        }
    };

    match response {
        None => {
            if is_notification {
                StatusCode::ACCEPTED.into_response()
            } else {
                // handle_request only returns None for notifications.
                StatusCode::ACCEPTED.into_response()
            }
        }
        Some(resp) => {
            let status = http_status_for_response(&resp);
            json_rpc_http(status, resp)
        }
    }
}

fn check_origin(state: &HttpState, headers: &HeaderMap) -> Option<Response> {
    let origin = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok())?;
    if state.cors || state.allowed_origins.iter().any(|o| o == origin) {
        return None;
    }
    Some(
        (
            StatusCode::FORBIDDEN,
            Json(serde_json::json!({
                "jsonrpc": "2.0",
                "error": {
                    "code": -32600,
                    "message": format!("Origin not allowed: {origin}")
                }
            })),
        )
            .into_response(),
    )
}

fn check_accept(headers: &HeaderMap) -> Option<Response> {
    match headers.get(header::ACCEPT).and_then(|v| v.to_str().ok()) {
        None => Some(StatusCode::NOT_ACCEPTABLE.into_response()),
        Some(accept) => {
            let accepts_json = accept.split(',').any(|part| {
                let media = part
                    .split(';')
                    .next()
                    .expect("BUG: str::split yields at least one item")
                    .trim();
                media == "application/json" || media == "*/*"
            });
            if accepts_json {
                None
            } else {
                Some(StatusCode::NOT_ACCEPTABLE.into_response())
            }
        }
    }
}

/// Validate MCP-Protocol-Version / Mcp-Method / Mcp-Name against the body.
fn validate_streamable_headers(headers: &HeaderMap, request: &McpRequest) -> Result<(), McpError> {
    let header_version = header_str(headers, "mcp-protocol-version").ok_or_else(|| {
        McpError::header_mismatch("Missing required header MCP-Protocol-Version".to_string())
    })?;

    match requested_protocol_version(&request.params) {
        Some(body_version) if body_version != header_version => {
            return Err(McpError::header_mismatch(format!(
                "Header mismatch: MCP-Protocol-Version header value '{header_version}' does not match body value '{body_version}'"
            )));
        }
        Some(body_version)
            if body_version != PROTOCOL_VERSION && body_version != LEGACY_PROTOCOL_VERSION =>
        {
            return Err(McpError::unsupported_protocol_version(body_version));
        }
        None if header_version != LEGACY_PROTOCOL_VERSION && header_version != PROTOCOL_VERSION => {
            return Err(McpError::unsupported_protocol_version(header_version));
        }
        None if header_version == PROTOCOL_VERSION => {
            // Modern header without body _meta: reject as mismatch / invalid.
            return Err(McpError::header_mismatch(
                "MCP-Protocol-Version is 2026-07-28 but body is missing _meta.io.modelcontextprotocol/protocolVersion"
                    .to_string(),
            ));
        }
        _ => {}
    }

    if header_version != PROTOCOL_VERSION && header_version != LEGACY_PROTOCOL_VERSION {
        return Err(McpError::unsupported_protocol_version(header_version));
    }

    let header_method = header_str(headers, "mcp-method").ok_or_else(|| {
        McpError::header_mismatch("Missing required header Mcp-Method".to_string())
    })?;
    if header_method != request.method {
        return Err(McpError::header_mismatch(format!(
            "Header mismatch: Mcp-Method header value '{header_method}' does not match body value '{}'",
            request.method
        )));
    }

    match request.method.as_str() {
        "tools/call" => {
            let body_name = request
                .params
                .as_ref()
                .and_then(|p| p.get("name"))
                .and_then(|v| v.as_str())
                .ok_or_else(|| {
                    McpError::header_mismatch(
                        "tools/call requires params.name for Mcp-Name header validation"
                            .to_string(),
                    )
                })?;
            let header_name = header_str(headers, "mcp-name").ok_or_else(|| {
                McpError::header_mismatch("Missing required header Mcp-Name".to_string())
            })?;
            let decoded = decode_mcp_name(header_name)?;
            if decoded != body_name {
                return Err(McpError::header_mismatch(format!(
                    "Header mismatch: Mcp-Name header value '{header_name}' does not match body value '{body_name}'"
                )));
            }
        }
        "resources/read" => {
            let body_uri = request
                .params
                .as_ref()
                .and_then(|p| p.get("uri"))
                .and_then(|v| v.as_str())
                .ok_or_else(|| {
                    McpError::header_mismatch(
                        "resources/read requires params.uri for Mcp-Name header validation"
                            .to_string(),
                    )
                })?;
            let header_name = header_str(headers, "mcp-name").ok_or_else(|| {
                McpError::header_mismatch("Missing required header Mcp-Name".to_string())
            })?;
            let decoded = decode_mcp_name(header_name)?;
            if decoded != body_uri {
                return Err(McpError::header_mismatch(format!(
                    "Header mismatch: Mcp-Name header value '{header_name}' does not match body value '{body_uri}'"
                )));
            }
        }
        _ => {}
    }

    Ok(())
}

fn header_str<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
    headers.get(name).and_then(|v| v.to_str().ok())
}

/// Decode Mcp-Name: plain ASCII, or Base64 sentinel `b64:<base64url>`.
fn decode_mcp_name(raw: &str) -> Result<String, McpError> {
    if let Some(encoded) = raw.strip_prefix("b64:") {
        use base64::Engine as _;
        let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
            .decode(encoded)
            .map_err(|e| {
                McpError::header_mismatch(format!("Invalid Mcp-Name Base64 sentinel: {e}"))
            })?;
        String::from_utf8(bytes).map_err(|e| {
            McpError::header_mismatch(format!("Mcp-Name Base64 decoded to non-UTF-8: {e}"))
        })
    } else {
        Ok(raw.to_string())
    }
}

fn http_status_for_response(resp: &McpResponse) -> StatusCode {
    match resp.error.as_ref().map(|e| e.code) {
        Some(-32601) => StatusCode::NOT_FOUND,
        Some(HEADER_MISMATCH) | Some(UNSUPPORTED_PROTOCOL_VERSION) => StatusCode::BAD_REQUEST,
        Some(-32700) | Some(-32600) | Some(-32602) => StatusCode::BAD_REQUEST,
        Some(-32603) => StatusCode::INTERNAL_SERVER_ERROR,
        _ => StatusCode::OK,
    }
}

fn json_rpc_http(status: StatusCode, response: McpResponse) -> Response {
    (status, Json(response)).into_response()
}

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

    #[test]
    fn loopback_origins_include_common_forms() {
        let o = loopback_origins("127.0.0.1", 8013);
        assert!(o.contains(&"http://127.0.0.1:8013".to_string()));
        assert!(o.contains(&"http://localhost:8013".to_string()));
        assert!(o.contains(&"http://[::1]:8013".to_string()));
    }

    #[test]
    fn decode_plain_mcp_name() {
        assert_eq!(decode_mcp_name("specs").unwrap(), "specs");
    }
}