Skip to main content

optimization_runner/mcp/
mod.rs

1//! `optimization-mcp`: a Model Context Protocol server over one node root.
2//!
3//! The server speaks MCP over stdio, one JSON-RPC message per line. It is
4//! dual-era: requests that carry `io.modelcontextprotocol/protocolVersion`
5//! in `_meta` are served statelessly under revision 2026-07-28, with the
6//! Tasks extension (`io.modelcontextprotocol/tasks`); an `initialize`
7//! request selects a legacy revision (2025-11-25 and earlier) for the
8//! process. Every tool drives the `optimization-run` command line, the
9//! runner's documented interface, so the runner's validation, idempotency,
10//! admission and recovery rules apply unchanged. The server registers no
11//! workers and initializes no node: that stays with the person who owns the
12//! node.
13//!
14//! See the guide's section [Agents and MCP](https://github.com/dietmarwo/optimization-jobs/blob/main/docs/job-api.md#agents-and-mcp) for the tools
15//! and their mapping onto the runner.
16mod guide;
17mod inputs;
18mod tasks;
19mod tools;
20
21use clap::{Parser, ValueEnum};
22use serde_json::{Map, Value, json};
23use std::{
24    collections::HashMap,
25    io::{self, BufRead, Read, Write},
26    path::PathBuf,
27    sync::{
28        Arc, Condvar, Mutex,
29        atomic::{AtomicBool, AtomicUsize, Ordering},
30    },
31    thread,
32    time::Duration,
33};
34
35/// Protocol revisions served statelessly, with per-request `_meta`.
36const MODERN: [&str; 1] = ["2026-07-28"];
37/// Protocol revisions served after an `initialize` handshake, newest first.
38const LEGACY: [&str; 4] = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
39const PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
40const CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
41const SERVER_INFO: &str = "io.modelcontextprotocol/serverInfo";
42const SUBSCRIPTION: &str = "io.modelcontextprotocol/subscriptionId";
43/// The Tasks extension (SEP-2663).
44const TASKS: &str = "io.modelcontextprotocol/tasks";
45/// MCP error codes of revision 2026-07-28.
46const MISSING_CAPABILITY: i64 = -32021;
47const UNSUPPORTED_VERSION: i64 = -32022;
48const INVALID_PARAMS: i64 = -32602;
49const METHOD_NOT_FOUND: i64 = -32601;
50const INVALID_REQUEST: i64 = -32600;
51const PARSE_ERROR: i64 = -32700;
52const INTERNAL_ERROR: i64 = -32603;
53/// The server is at one of its limits below; the request may be retried.
54const SERVER_BUSY: i64 = -32000;
55/// Largest message, in bytes: the input files of a job are files, not part
56/// of it. A longer line is skipped unread and answered with an error.
57const MAX_MESSAGE: usize = 64 * 1024 * 1024;
58/// Requests answered at the same time (each runs on a thread of its own).
59const MAX_REQUESTS: usize = 64;
60/// Of these, requests that wait (`wait_job`, `subscriptions/listen`): the
61/// rest stays free for status, cancellation and other short calls.
62const MAX_WAITING: usize = 32;
63/// Calls that run worker validation (`validate_job`, `submit_job`) at the
64/// same time; further ones queue. Validation runs before CPU-slot admission.
65const MAX_VALIDATIONS: usize = 4;
66/// How long clients may cache `tools/list` and `server/discover`.
67const CACHE_MS: u64 = 3_600_000;
68
69const INSTRUCTIONS: &str = "Runs durable optimization jobs on this node with its registered native \
70workers (fcmaes, LP-IP, SQP and application workers). If no solver or profile has been chosen \
71yet, call get_guide first: it says which solver and profile fit the problem (its section \
72argument returns one part). Then call describe_node, and describe_worker for a worker's profiles \
73and options, the JSON Schemas of its payloads and runnable examples. Write an \
74optimization.job/0.1 envelope, check it with validate_job and start it with submit_job. Input \
75files that are not on this machine yet, such as a new LP model, go through put_input, which \
76returns the file, sha256 and input_dir for the job. The request_key makes \
77submission idempotent: the same key with the same content returns the existing job, other \
78content under that key is rejected, so choose a new key for a new job. Jobs run detached from \
79this server and survive its restart. Follow a job with wait_job or get_job and read get_result \
80when it has ended. cancel_job stops it gracefully and keeps completed work; kill_job stops it \
81at once. Every task result carries a claim (what the worker asserts) and evidence (how much of \
82it was independently rechecked); there is no automatic winner across tasks or jobs.";
83
84#[derive(Parser)]
85#[command(
86    name = "optimization-mcp",
87    version,
88    about = "MCP server (stdio) for the durable optimization jobs of one optimization-run node (Linux)"
89)]
90struct Args {
91    /// Node root, as for optimization-run.
92    #[arg(
93        long,
94        env = "OPTIMIZATION_RUN_ROOT",
95        default_value = ".optimization-jobs"
96    )]
97    root: PathBuf,
98    /// The optimization-run executable; by default the one next to this
99    /// server.
100    #[arg(long)]
101    runner: Option<PathBuf>,
102    /// How submit_job starts jobs: `process` runs `optimization-run run` in a
103    /// session of its own, which outlives this server; `systemd` uses
104    /// `optimization-run submit` (a systemd user manager is required).
105    #[arg(long, value_enum, default_value_t = Launch::Process)]
106    launch: Launch,
107    /// Directory that relative input files of inline jobs are read from, by
108    /// default the working directory.
109    #[arg(long)]
110    input_dir: Option<PathBuf>,
111    /// Largest total size of the input store of put_input (NODE/mcp/inputs),
112    /// in bytes.
113    #[arg(long, default_value_t = inputs::DEFAULT_STORE_BYTES)]
114    input_store_bytes: u64,
115}
116
117/// How `submit_job` starts jobs (`--launch`).
118#[derive(Clone, Copy, Debug, PartialEq)]
119pub enum Launch {
120    /// `optimization-run run` in a session of its own, which outlives the
121    /// server.
122    Process,
123    /// `optimization-run submit`, which needs a systemd user manager.
124    Systemd,
125}
126
127impl Launch {
128    /// The option value: `process` or `systemd`.
129    pub fn name(self) -> &'static str {
130        match self {
131            Launch::Process => "process",
132            Launch::Systemd => "systemd",
133        }
134    }
135}
136
137// Written out rather than derived: a derived ValueEnum turns the variants'
138// doc comments into option help, which would change `--help`.
139impl ValueEnum for Launch {
140    fn value_variants<'a>() -> &'a [Self] {
141        &[Launch::Process, Launch::Systemd]
142    }
143
144    fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {
145        Some(clap::builder::PossibleValue::new(self.name()))
146    }
147}
148
149/// The MCP server over one node root.
150pub struct Server {
151    /// The node root.
152    pub root: PathBuf,
153    /// The `optimization-run` executable that every tool calls.
154    pub runner: PathBuf,
155    /// How jobs are started.
156    pub launch: Launch,
157    /// The directory that relative input files of inline jobs are read from.
158    pub input_dir: PathBuf,
159    /// Limit of the input store's total size.
160    pub input_store_bytes: u64,
161    out: Mutex<io::Stdout>,
162    inflight: Mutex<HashMap<String, Arc<AtomicBool>>>,
163    initialized: AtomicBool,
164    /// JSON-RPC batches, part of protocol 2025-03-26 only.
165    batches: AtomicBool,
166    /// Set at the end of input; waiting requests stop, jobs keep running.
167    pub shutdown: AtomicBool,
168    /// Requests counted against [`MAX_WAITING`].
169    waiting: AtomicUsize,
170    /// Running validations and the signal that one ended.
171    validations: (Mutex<usize>, Condvar),
172}
173
174/// One of the `MAX_VALIDATIONS` validation places, given back on drop.
175pub struct Permit<'a>(&'a Server);
176
177impl Drop for Permit<'_> {
178    fn drop(&mut self) {
179        let (count, ended) = &self.0.validations;
180        *count.lock().unwrap_or_else(|e| e.into_inner()) -= 1;
181        ended.notify_one();
182    }
183}
184
185/// One request: its era and whether it may be cancelled or report progress.
186pub struct Ctx {
187    /// The request is served statelessly under revision 2026-07-28.
188    pub modern: bool,
189    /// The client declared the Tasks extension on this request.
190    pub tasks: bool,
191    /// Set when the client cancels the request.
192    pub cancel: Arc<AtomicBool>,
193    /// The request's progress token, if it asked for progress.
194    pub progress: Option<Value>,
195    /// The JSON-RPC ID of the request.
196    pub id: Value,
197}
198
199/// The answer to one request.
200pub enum Reply {
201    /// A result.
202    Ok(Value),
203    /// A JSON-RPC error: its code, message and optional data.
204    Err(i64, String, Option<Value>),
205    /// No response: the request was cancelled, or it ended a subscription
206    /// the client cancelled.
207    Silent,
208}
209
210impl Ctx {
211    /// Whether the request was cancelled or the server is shutting down.
212    pub fn stopped(&self, server: &Server) -> bool {
213        self.cancel.load(Ordering::Relaxed) || server.shutdown.load(Ordering::Relaxed)
214    }
215}
216
217fn supported() -> Vec<&'static str> {
218    MODERN.iter().chain(LEGACY.iter()).copied().collect()
219}
220
221fn server_info() -> Value {
222    json!({"name":"optimization-mcp","title":"Optimization jobs","version":env!("CARGO_PKG_VERSION")})
223}
224
225fn missing_tasks_capability() -> Reply {
226    Reply::Err(
227        MISSING_CAPABILITY,
228        "Missing required client capability".into(),
229        Some(json!({"requiredCapabilities":{"extensions":{TASKS:{}}}})),
230    )
231}
232
233/// The protocol error of a task whose job cannot be read or cancelled. A job
234/// removed from the node makes its task unknown.
235fn job_error(job_id: &str, action: &str, e: &tools::ToolError) -> Reply {
236    if e.code == "unknown_job" {
237        return Reply::Err(
238            INVALID_PARAMS,
239            format!("Failed to retrieve task: its job {job_id} no longer exists on this node"),
240            None,
241        );
242    }
243    Reply::Err(
244        INTERNAL_ERROR,
245        format!("cannot {action} job {job_id}: {}: {}", e.code, e.message),
246        None,
247    )
248}
249
250impl Server {
251    /// Waits for a validation place; a cancelled request stops waiting.
252    pub fn validation_permit(&self, ctx: &Ctx) -> Result<Permit<'_>, tools::Fail> {
253        let (count, ended) = &self.validations;
254        let mut running = count.lock().unwrap_or_else(|e| e.into_inner());
255        while *running >= MAX_VALIDATIONS {
256            if ctx.stopped(self) {
257                return Err(tools::Fail::Cancelled);
258            }
259            running = ended
260                .wait_timeout(running, Duration::from_millis(100))
261                .unwrap_or_else(|e| e.into_inner())
262                .0;
263        }
264        *running += 1;
265        Ok(Permit(self))
266    }
267
268    /// Writes one message as one line; a closed stdout ends the server.
269    pub fn send(&self, message: &Value) {
270        let mut out = self.out.lock().unwrap_or_else(|e| e.into_inner());
271        let ok = serde_json::to_writer(&mut *out, message).is_ok()
272            && out.write_all(b"\n").is_ok()
273            && out.flush().is_ok();
274        if !ok {
275            std::process::exit(0);
276        }
277    }
278
279    /// Sends the notification `method` with `params`.
280    pub fn notify(&self, method: &str, params: Value) {
281        self.send(&json!({"jsonrpc":"2.0","method":method,"params":params}));
282    }
283
284    /// Reports `progress` of `total` for a request that asked for progress.
285    pub fn progress(&self, ctx: &Ctx, progress: u64, total: Option<u64>, message: &str) {
286        if let Some(token) = &ctx.progress {
287            let mut params = json!({"progressToken":token,"progress":progress,"message":message});
288            if let Some(total) = total {
289                params["total"] = json!(total);
290            }
291            self.notify("notifications/progress", params);
292        }
293    }
294
295    /// The response to a request, if it gets one.
296    fn finish(&self, id: &Value, cancel: &AtomicBool, reply: Reply, modern: bool) -> Option<Value> {
297        self.inflight
298            .lock()
299            .unwrap_or_else(|e| e.into_inner())
300            .remove(&id.to_string());
301        // A cancelled request gets no response at all.
302        if cancel.load(Ordering::Relaxed) {
303            return None;
304        }
305        Some(match reply {
306            Reply::Silent => return None,
307            Reply::Ok(mut result) => {
308                if modern {
309                    let object = result.as_object_mut().expect("results are objects");
310                    object
311                        .entry("resultType")
312                        .or_insert_with(|| json!("complete"));
313                    let meta = object.entry("_meta").or_insert_with(|| json!({}));
314                    meta[SERVER_INFO] = server_info();
315                }
316                json!({"jsonrpc":"2.0","id":id,"result":result})
317            }
318            Reply::Err(code, message, data) => {
319                let mut error = json!({"code":code,"message":message});
320                if let Some(data) = data {
321                    error["data"] = data;
322                }
323                json!({"jsonrpc":"2.0","id":id,"error":error})
324            }
325        })
326    }
327
328    /// Decides how a request is served: `(modern, tasks)`, or the error that
329    /// rejects it.
330    fn era(&self, method: &str, params: &Value) -> Result<(bool, bool), Reply> {
331        let meta = &params["_meta"];
332        if !meta[PROTOCOL_VERSION].is_null() {
333            if !meta[PROTOCOL_VERSION]
334                .as_str()
335                .is_some_and(|v| MODERN.contains(&v))
336            {
337                return Err(Reply::Err(
338                    UNSUPPORTED_VERSION,
339                    format!(
340                        "Unsupported protocol version: {} is served per request; {} only after initialize, without _meta",
341                        MODERN.join(", "),
342                        LEGACY.join(", ")
343                    ),
344                    Some(json!({"supported":supported(),"requested":meta[PROTOCOL_VERSION]})),
345                ));
346            }
347            if !meta[CLIENT_CAPABILITIES].is_object() {
348                return Err(Reply::Err(
349                    INVALID_PARAMS,
350                    format!("_meta lacks {CLIENT_CAPABILITIES}"),
351                    None,
352                ));
353            }
354            let tasks = meta[CLIENT_CAPABILITIES]["extensions"][TASKS].is_object();
355            return Ok((true, tasks));
356        }
357        if method == "initialize" || method == "ping" || self.initialized.load(Ordering::Relaxed) {
358            return Ok((false, false));
359        }
360        Err(Reply::Err(
361            INVALID_PARAMS,
362            format!(
363                "request lacks _meta {PROTOCOL_VERSION}: this server serves {} per request, and {} after initialize",
364                MODERN.join(", "),
365                LEGACY.join(", ")
366            ),
367            None,
368        ))
369    }
370
371    /// Serves one request and returns its response, if any. A panic is a
372    /// bug, but it still answers the request.
373    fn request(
374        self: &Arc<Self>,
375        id: Value,
376        method: String,
377        params: Value,
378        cancel: Arc<AtomicBool>,
379    ) -> Option<Value> {
380        let (reply, modern) = match self.era(&method, &params) {
381            Err(reply) => (reply, false),
382            Ok((modern, tasks)) => {
383                let ctx = Ctx {
384                    modern,
385                    tasks,
386                    progress: params["_meta"].get("progressToken").cloned(),
387                    cancel: cancel.clone(),
388                    id: id.clone(),
389                };
390                let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
391                    self.dispatch(&method, &params, &ctx)
392                }))
393                .unwrap_or_else(|_| {
394                    Reply::Err(
395                        INTERNAL_ERROR,
396                        "internal error of optimization-mcp; its stderr has the details".into(),
397                        None,
398                    )
399                });
400                (reply, modern)
401            }
402        };
403        self.finish(&id, &cancel, reply, modern)
404    }
405
406    fn dispatch(&self, method: &str, params: &Value, ctx: &Ctx) -> Reply {
407        match (ctx.modern, method) {
408            (true, "server/discover") => Reply::Ok(json!({
409                "supportedVersions": supported(),
410                "capabilities": {"tools": {}, "extensions": {TASKS: {}}},
411                "instructions": INSTRUCTIONS,
412                "ttlMs": CACHE_MS,
413                "cacheScope": "public",
414            })),
415            (false, "initialize") => {
416                let version = params["protocolVersion"]
417                    .as_str()
418                    .filter(|v| LEGACY.contains(v))
419                    .unwrap_or(LEGACY[0]);
420                self.initialized.store(true, Ordering::Relaxed);
421                self.batches
422                    .store(version == "2025-03-26", Ordering::Relaxed);
423                Reply::Ok(json!({
424                    "protocolVersion": version,
425                    "capabilities": {"tools": {"listChanged": false}},
426                    "serverInfo": server_info(),
427                    "instructions": INSTRUCTIONS,
428                }))
429            }
430            (false, "ping") => Reply::Ok(json!({})),
431            (_, "tools/list") => {
432                let mut result = json!({"tools": tools::definitions()});
433                if ctx.modern {
434                    result["ttlMs"] = json!(CACHE_MS);
435                    result["cacheScope"] = json!("public");
436                }
437                Reply::Ok(result)
438            }
439            (_, "tools/call") => self.call_tool(params, ctx),
440            (true, "tasks/get" | "tasks/update" | "tasks/cancel") => {
441                if !ctx.tasks {
442                    return missing_tasks_capability();
443                }
444                self.task_method(method, params, ctx)
445            }
446            (true, "subscriptions/listen") => self.listen(params, ctx),
447            _ => Reply::Err(
448                METHOD_NOT_FOUND,
449                format!("Method not found: {method}"),
450                None,
451            ),
452        }
453    }
454
455    fn call_tool(&self, params: &Value, ctx: &Ctx) -> Reply {
456        let Some(name) = params["name"].as_str() else {
457            return Reply::Err(INVALID_PARAMS, "tools/call needs a tool name".into(), None);
458        };
459        let arguments = match &params["arguments"] {
460            Value::Null => json!({}),
461            Value::Object(_) => params["arguments"].clone(),
462            _ => {
463                return Reply::Err(
464                    INVALID_PARAMS,
465                    "tool arguments must be an object".into(),
466                    None,
467                );
468            }
469        };
470        if !tools::exists(name) {
471            return Reply::Err(INVALID_PARAMS, format!("Unknown tool: {name}"), None);
472        }
473        match tools::call(self, name, &arguments, ctx) {
474            tools::Outcome::Done(value) => Reply::Ok(tools::tool_result(value, false)),
475            tools::Outcome::Failed(error) => Reply::Ok(tools::tool_result(error.value(), true)),
476            tools::Outcome::Task(task) => Reply::Ok(task),
477            tools::Outcome::Cancelled => Reply::Silent,
478        }
479    }
480
481    fn task_method(&self, method: &str, params: &Value, ctx: &Ctx) -> Reply {
482        let Some(task_id) = params["taskId"].as_str() else {
483            return Reply::Err(INVALID_PARAMS, "taskId must be a string".into(), None);
484        };
485        let job_id = match tasks::job_of(&self.root, task_id) {
486            Ok(Some(job)) => job,
487            Ok(None) => {
488                return Reply::Err(
489                    INVALID_PARAMS,
490                    "Failed to retrieve task: Task not found".into(),
491                    None,
492                );
493            }
494            Err(e) => return Reply::Err(INTERNAL_ERROR, format!("task store: {e}"), None),
495        };
496        match method {
497            "tasks/get" => match tasks::detailed(self, task_id, &job_id, ctx) {
498                Ok(task) => Reply::Ok(task),
499                Err(tools::Fail::Cancelled) => Reply::Silent,
500                Err(tools::Fail::Tool(e)) => job_error(&job_id, "read", &e),
501            },
502            // No task of this server asks for input; responses are ignored.
503            "tasks/update" => Reply::Ok(json!({})),
504            _ => match tools::cancel(self, &job_id, false) {
505                Ok(_) => Reply::Ok(json!({})),
506                // A job that already ended has nothing to cancel; the
507                // acknowledgement promises no transition.
508                Err(tools::Fail::Tool(e)) if e.code == "already_terminal" => Reply::Ok(json!({})),
509                Err(tools::Fail::Cancelled) => Reply::Silent,
510                Err(tools::Fail::Tool(e)) => job_error(&job_id, "cancel", &e),
511            },
512        }
513    }
514
515    /// `subscriptions/listen`: task status notifications for `taskIds`. The
516    /// server sends no other notification type; the stream stays open until
517    /// the client cancels it.
518    fn listen(&self, params: &Value, ctx: &Ctx) -> Reply {
519        let Some(filter) = params["notifications"].as_object() else {
520            return Reply::Err(
521                INVALID_PARAMS,
522                "subscriptions/listen needs a notifications object".into(),
523                None,
524            );
525        };
526        let wanted = filter.get("taskIds");
527        if wanted.is_some() && !ctx.tasks {
528            return missing_tasks_capability();
529        }
530        let mut tracked: Vec<(String, String)> = vec![];
531        if let Some(ids) = wanted {
532            let Some(ids) = ids.as_array() else {
533                return Reply::Err(INVALID_PARAMS, "taskIds must be an array".into(), None);
534            };
535            for id in ids.iter().filter_map(Value::as_str) {
536                if let Ok(Some(job)) = tasks::job_of(&self.root, id)
537                    && !tracked.iter().any(|(t, _)| t == id)
538                {
539                    tracked.push((id.to_owned(), job));
540                }
541            }
542        }
543        let mut agreed = Map::new();
544        if wanted.is_some() {
545            agreed.insert(
546                "taskIds".into(),
547                json!(tracked.iter().map(|(t, _)| t).collect::<Vec<_>>()),
548            );
549        }
550        self.notify(
551            "notifications/subscriptions/acknowledged",
552            json!({"_meta":{SUBSCRIPTION:ctx.id},"notifications":agreed}),
553        );
554        let mut last: HashMap<String, String> = HashMap::new();
555        while !ctx.stopped(self) {
556            tracked.retain(|(task_id, job_id)| {
557                let Ok(mut task) = tasks::detailed(self, task_id, job_id, ctx) else {
558                    return true;
559                };
560                let status = task["status"].as_str().unwrap_or_default().to_owned();
561                if last.get(task_id) != Some(&status) {
562                    if let Some(object) = task.as_object_mut() {
563                        object.remove("resultType");
564                        object.insert("_meta".into(), json!({SUBSCRIPTION:ctx.id}));
565                    }
566                    self.notify("notifications/tasks", task);
567                    last.insert(task_id.clone(), status.clone());
568                }
569                !tasks::terminal_status(&status)
570            });
571            tools::pause(self, ctx, tasks::POLL);
572        }
573        Reply::Silent
574    }
575
576    fn notification(&self, method: &str, params: &Value) {
577        if method == "notifications/cancelled" {
578            let id = params["requestId"].to_string();
579            if let Some(flag) = self
580                .inflight
581                .lock()
582                .unwrap_or_else(|e| e.into_inner())
583                .get(&id)
584            {
585                flag.store(true, Ordering::Relaxed);
586            }
587        }
588        // notifications/initialized and anything else need no action.
589    }
590
591    fn error(id: Value, code: i64, message: &str) -> Value {
592        json!({"jsonrpc":"2.0","id":id,"error":{"code":code,"message":message}})
593    }
594
595    fn busy(id: Value, message: String) -> Value {
596        json!({"jsonrpc":"2.0","id":id,"error":{"code":SERVER_BUSY,"message":message,
597            "data":{"retryable":true}}})
598    }
599
600    /// Starts one message of the input: a request runs on a thread of its
601    /// own and yields its response through the handle; a notification or a
602    /// client's response yields nothing.
603    fn accept(self: &Arc<Self>, message: Value) -> Option<thread::JoinHandle<Option<Value>>> {
604        let method = message["method"].as_str().map(str::to_owned);
605        let params = message.get("params").cloned().unwrap_or(json!({}));
606        let immediate = |reply: Value| Some(thread::spawn(move || Some(reply)));
607        match (method, message.get("id")) {
608            // Responses from the client: this server sends no requests.
609            (None, _) if message.is_object() && message.get("id").is_some() => None,
610            (Some(method), None) if message.is_object() => {
611                self.notification(&method, &params);
612                None
613            }
614            (Some(method), Some(id)) if id.is_string() || id.is_number() => {
615                let cancel = Arc::new(AtomicBool::new(false));
616                let waits = method == "subscriptions/listen"
617                    || (method == "tools/call" && params["name"] == "wait_job");
618                {
619                    let mut inflight = self.inflight.lock().unwrap_or_else(|e| e.into_inner());
620                    if inflight.contains_key(&id.to_string()) {
621                        // Answering under that ID would give it two responses.
622                        eprintln!("optimization-mcp: request id {id} is already in use");
623                        return immediate(Self::error(
624                            Value::Null,
625                            INVALID_REQUEST,
626                            &format!("request id {id} is already in use"),
627                        ));
628                    }
629                    if inflight.len() >= MAX_REQUESTS {
630                        return immediate(Self::busy(
631                            id.clone(),
632                            format!(
633                                "server busy: {MAX_REQUESTS} requests in progress; retry later"
634                            ),
635                        ));
636                    }
637                    if waits && self.waiting.fetch_add(1, Ordering::Relaxed) >= MAX_WAITING {
638                        self.waiting.fetch_sub(1, Ordering::Relaxed);
639                        return immediate(Self::busy(
640                            id.clone(),
641                            format!(
642                                "server busy: {MAX_WAITING} waiting requests (wait_job, subscriptions/listen) in progress; retry later"
643                            ),
644                        ));
645                    }
646                    inflight.insert(id.to_string(), cancel.clone());
647                }
648                let server = self.clone();
649                let id = id.clone();
650                Some(thread::spawn(move || {
651                    let response = server.request(id, method, params, cancel);
652                    if waits {
653                        server.waiting.fetch_sub(1, Ordering::Relaxed);
654                    }
655                    response
656                }))
657            }
658            _ => immediate(Self::error(Value::Null, INVALID_REQUEST, "Invalid request")),
659        }
660    }
661
662    fn serve(self: Arc<Self>) {
663        let mut input = io::stdin().lock();
664        let mut line = Vec::new();
665        loop {
666            match read_message(&mut input, &mut line) {
667                Ok(Frame::End) | Err(_) => break,
668                Ok(Frame::TooLong) => {
669                    self.send(&Self::error(
670                        Value::Null,
671                        INVALID_REQUEST,
672                        &format!("message longer than {MAX_MESSAGE} bytes; skipped"),
673                    ));
674                    continue;
675                }
676                Ok(Frame::Message) => {}
677            }
678            if line.iter().all(u8::is_ascii_whitespace) {
679                continue;
680            }
681            let message: Value = match serde_json::from_slice(&line) {
682                Ok(message) => message,
683                Err(e) => {
684                    self.send(&Self::error(
685                        Value::Null,
686                        PARSE_ERROR,
687                        &format!("Parse error: {e}"),
688                    ));
689                    continue;
690                }
691            };
692            match message {
693                // A JSON-RPC batch (protocol 2025-03-26): one array of the
694                // responses, sent when all of them are ready, so a stream
695                // that never ends cannot be part of one.
696                Value::Array(messages)
697                    if !messages.is_empty() && self.batches.load(Ordering::Relaxed) =>
698                {
699                    let handles: Vec<_> = messages
700                        .into_iter()
701                        .filter_map(|m| {
702                            if m["method"] == "subscriptions/listen" {
703                                let id = m.get("id").cloned().unwrap_or(Value::Null);
704                                let reply = Self::error(
705                                    id,
706                                    INVALID_REQUEST,
707                                    "subscriptions/listen cannot be part of a batch",
708                                );
709                                return Some(thread::spawn(move || Some(reply)));
710                            }
711                            self.accept(m)
712                        })
713                        .collect();
714                    let server = self.clone();
715                    thread::spawn(move || {
716                        let responses: Vec<Value> = handles
717                            .into_iter()
718                            .filter_map(|h| h.join().ok().flatten())
719                            .collect();
720                        if !responses.is_empty() {
721                            server.send(&Value::Array(responses));
722                        }
723                    });
724                }
725                Value::Array(messages) => self.send(&Self::error(
726                    Value::Null,
727                    INVALID_REQUEST,
728                    if messages.is_empty() {
729                        "empty batch"
730                    } else {
731                        "JSON-RPC batches are part of protocol 2025-03-26 only; initialize with it to send them"
732                    },
733                )),
734                message => {
735                    if let Some(handle) = self.accept(message) {
736                        let server = self.clone();
737                        thread::spawn(move || {
738                            if let Ok(Some(response)) = handle.join() {
739                                server.send(&response);
740                            }
741                        });
742                    }
743                }
744            }
745        }
746        // End of input is the stdio shutdown signal. Jobs keep running.
747        self.shutdown.store(true, Ordering::Relaxed);
748    }
749}
750
751enum Frame {
752    Message,
753    TooLong,
754    End,
755}
756
757/// Reads one line of at most [`MAX_MESSAGE`] bytes into `line`. The rest of
758/// a longer line is consumed without being kept.
759fn read_message(input: &mut impl BufRead, line: &mut Vec<u8>) -> io::Result<Frame> {
760    line.clear();
761    if input
762        .by_ref()
763        .take(MAX_MESSAGE as u64 + 1)
764        .read_until(b'\n', line)?
765        == 0
766    {
767        return Ok(Frame::End);
768    }
769    if line.len() <= MAX_MESSAGE || line.ends_with(b"\n") {
770        return Ok(Frame::Message);
771    }
772    line.clear();
773    line.shrink_to(1 << 16);
774    loop {
775        let buffer = input.fill_buf()?;
776        if buffer.is_empty() {
777            return Ok(Frame::TooLong);
778        }
779        match buffer.iter().position(|&b| b == b'\n') {
780            Some(end) => {
781                input.consume(end + 1);
782                return Ok(Frame::TooLong);
783            }
784            None => {
785                let all = buffer.len();
786                input.consume(all);
787            }
788        }
789    }
790}
791
792/// The `optimization-mcp` binary: parses its options and serves MCP on
793/// standard input and output until the input ends.
794pub fn main() {
795    if !cfg!(target_os = "linux") {
796        eprintln!("optimization-mcp: Linux is required");
797        std::process::exit(2);
798    }
799    // Every runner this server starts refuses command jobs, also when a
800    // spec_path changes after the server read it.
801    // SAFETY: no other thread exists yet.
802    unsafe { std::env::set_var(crate::command::REFUSE, "1") };
803    let args = Args::parse();
804    let fail = |message: String| -> ! {
805        eprintln!("optimization-mcp: {message}");
806        std::process::exit(2)
807    };
808    let runner = args.runner.unwrap_or_else(|| {
809        std::env::current_exe()
810            .ok()
811            .and_then(|exe| exe.parent().map(|dir| dir.join("optimization-run")))
812            .unwrap_or_else(|| PathBuf::from("optimization-run"))
813    });
814    let runner = std::fs::canonicalize(&runner)
815        .unwrap_or_else(|e| fail(format!("runner {}: {e}", runner.display())));
816    if let Err(e) = std::fs::create_dir_all(&args.root) {
817        fail(format!("node root {}: {e}", args.root.display()));
818    }
819    let root = std::fs::canonicalize(&args.root)
820        .unwrap_or_else(|e| fail(format!("node root {}: {e}", args.root.display())));
821    let input_dir = args
822        .input_dir
823        .map_or_else(std::env::current_dir, Ok)
824        .and_then(std::fs::canonicalize)
825        .unwrap_or_else(|e| fail(format!("input directory: {e}")));
826    tools::clean_staging(&root);
827    inputs::clean(&root);
828    eprintln!(
829        "optimization-mcp {}: node {}, runner {}, launch {}",
830        env!("CARGO_PKG_VERSION"),
831        root.display(),
832        runner.display(),
833        args.launch.name()
834    );
835    let server = Arc::new(Server {
836        root,
837        runner,
838        launch: args.launch,
839        input_dir,
840        input_store_bytes: args.input_store_bytes,
841        out: Mutex::new(io::stdout()),
842        inflight: Mutex::new(HashMap::new()),
843        initialized: AtomicBool::new(false),
844        batches: AtomicBool::new(false),
845        shutdown: AtomicBool::new(false),
846        waiting: AtomicUsize::new(0),
847        validations: (Mutex::new(0), Condvar::new()),
848    });
849    server.serve();
850}