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