1use super::{Ctx, Launch, Server, guide, inputs, tasks};
4use optimization_job_api::{
5 Input, JobSpec, MAX_INPUT_BYTES, checked_input, process::bounded_command_until, storage::digest,
6};
7use serde::Deserialize;
8use serde_json::{Value, json, value::RawValue};
9use std::{
10 collections::BTreeMap,
11 fs,
12 io::ErrorKind,
13 path::{Component, Path, PathBuf},
14 process::{Command, Stdio},
15 thread,
16 time::{Duration, Instant, SystemTime},
17};
18
19pub const TERMINAL: [&str; 5] = [
21 "completed",
22 "failed",
23 "cancelled",
24 "timed_out",
25 "interrupted",
26];
27const QUICK: Duration = Duration::from_secs(30);
29const SLOW: Duration = Duration::from_secs(120);
30const OUTPUT_CAP: usize = 64 * 1024 * 1024;
32const SUMMARY_TASKS: usize = 100;
34const FULL_CAP: usize = 1024 * 1024;
35const MAX_WAIT_SECONDS: f64 = 600.0;
36const MUTATING: Duration = Duration::from_secs(600);
38const MANIFEST_CAP: u64 = 256 * 1024 * 1024;
40
41pub struct ToolError {
42 pub code: String,
43 pub message: String,
44 pub retryable: bool,
45}
46
47impl ToolError {
48 pub fn value(&self) -> Value {
49 json!({"error":{"code":self.code,"message":self.message,"retryable":self.retryable}})
50 }
51}
52
53pub enum Fail {
54 Tool(ToolError),
55 Cancelled,
57}
58
59pub enum Outcome {
60 Done(Value),
61 Failed(ToolError),
62 Task(Value),
64 Cancelled,
65}
66
67pub(super) fn fail(code: &str, message: impl Into<String>) -> Fail {
68 Fail::Tool(ToolError {
69 code: code.into(),
70 message: message.into(),
71 retryable: false,
72 })
73}
74
75pub fn tool_result(value: Value, is_error: bool) -> Value {
78 json!({
79 "content": [{"type":"text","text":value.to_string()}],
80 "structuredContent": value,
81 "isError": is_error,
82 })
83}
84
85pub fn terminal(state: &Value) -> bool {
86 state.as_str().is_some_and(|s| TERMINAL.contains(&s))
87}
88
89pub fn pause(server: &Server, ctx: &Ctx, duration: Duration) {
91 let start = Instant::now();
92 while start.elapsed() < duration && !ctx.stopped(server) {
93 thread::sleep(Duration::from_millis(50).min(duration));
94 }
95}
96
97fn random_hex() -> String {
98 use std::io::Read;
99 let mut bytes = [0u8; 16];
100 if fs::File::open("/dev/urandom")
101 .and_then(|mut f| f.read_exact(&mut bytes))
102 .is_err()
103 {
104 let nanos = SystemTime::now()
106 .duration_since(SystemTime::UNIX_EPOCH)
107 .map(|d| d.as_nanos())
108 .unwrap_or_default();
109 return digest(format!("{nanos}-{}", std::process::id()).as_bytes())[..32].to_owned();
110 }
111 bytes.iter().map(|b| format!("{b:02x}")).collect()
112}
113
114pub fn task_token() -> std::io::Result<String> {
115 use std::io::Read;
116 let mut bytes = [0u8; 16];
117 fs::File::open("/dev/urandom")?.read_exact(&mut bytes)?;
118 Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
119}
120
121fn object(properties: Value, required: &[&str]) -> Value {
122 json!({"type":"object","properties":properties,"required":required,"additionalProperties":false})
123}
124
125fn job_id_property() -> Value {
126 json!({"type":"string","pattern":"^[0-9a-f]{32}$","description":"Job ID, as returned by submit_job or list_jobs."})
127}
128
129fn envelope_schema() -> Value {
131 let mut schema: Value = serde_json::from_str(include_str!(
134 "../../schemas/optimization.job-0.1.schema.json"
135 ))
136 .expect("the job schema is valid JSON");
137 let object = schema.as_object_mut().expect("the job schema is an object");
138 object.remove("$schema");
139 object.remove("$id");
140 object.insert(
141 "description".into(),
142 json!("An optimization.job/0.1 envelope (fcmaes.job/0.1 legacy specifications are accepted too). The payload follows the worker profile named by payload_schema; describe_worker lists them."),
143 );
144 schema
145}
146
147fn job_properties() -> Value {
148 json!({
149 "job": envelope_schema(),
150 "spec_path": {"type":"string","description":"Path of a job file on this machine, instead of job. Its relative input files are read from the file's directory."},
151 "input_dir": {"type":"string","description":"Directory the relative input files of job are read from; by default the server's input directory. Each file must match its SHA-256."},
152 })
153}
154
155pub fn definitions() -> Vec<Value> {
157 let read = json!({"readOnlyHint":true,"openWorldHint":false});
158 let job_id = job_id_property();
159 let tools = [
160 (
161 "get_guide",
162 "Read the guide for agents",
163 read.clone(),
164 "The guide for agents (ai-context.md of optimization-jobs): which solver and profile fit a problem (LP or MIP, smooth NLP, black box, several objectives, diverse solutions, expensive simulations), library or job, installation, the job API and this server. Call it first when no solver or profile has been chosen yet. With section, only the first section whose heading contains that text (case-insensitive), with its subsections; an unknown section lists the headings.",
165 object(
166 json!({"section":{"type":"string","minLength":1,"description":"Text that a heading contains; without it, the whole guide."}}),
167 &[],
168 ),
169 ),
170 (
171 "describe_node",
172 "Describe the node",
173 read.clone(),
174 "The node's CPU capacity (slots), how jobs are launched, the CPUs and memory the host gives its jobs (host: affinity, cgroup quota and limit, physical cores, NUMA nodes) with warnings such as a capacity above the usable CPUs, and its registered workers with their profiles and builds. Start here once a solver is chosen.",
175 object(json!({}), &[]),
176 ),
177 (
178 "describe_worker",
179 "Describe a worker",
180 read.clone(),
181 "Everything a registered worker declares: its profiles (payload_schema values), problems, optimizers or backends and their options, claims, cancellation and resource rules. Read it before writing a payload.",
182 object(
183 json!({"worker":{"type":"string","description":"ID of a registered worker, from describe_node."}}),
184 &["worker"],
185 ),
186 ),
187 (
188 "put_input",
189 "Store an input file",
190 json!({"readOnlyHint":false,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false}),
191 "Stores data that a job reads as an input file, such as a new LP model, in this node's content-addressed input store, and returns file, sha256, bytes and input_dir. A job then lists {\"name\": NAME, \"file\": file, \"sha256\": sha256} in inputs and is passed to validate_job and submit_job with input_dir; inputs stored this way share input_dir, so one job can use several. Pass exactly one of content (text, stored as its UTF-8 bytes; a JSON input as its serialized text), content_base64 (bytes) or from_artifact (a file of an existing job, to use it together with other stored inputs). Storing the same content again returns the same file. At most 64 MiB per input; the store holds data, never code.",
192 object(
193 json!({
194 "content": {"type":"string","description":"Text, stored as its UTF-8 bytes; a JSON input as the text a JSON serializer wrote."},
195 "content_base64": {"type":"string","contentEncoding":"base64","description":"Bytes in base64 (RFC 4648)."},
196 "from_artifact": {
197 "type":"object",
198 "description":"An artifact of an existing job, copied into the store as get_artifact reads it whole.",
199 "properties":{"job_id":job_id,"name":{"type":"string","description":"Artifact name from artifact_index of get_job or the result."}},
200 "required":["job_id","name"],
201 "additionalProperties":false,
202 },
203 }),
204 &[],
205 ),
206 ),
207 (
208 "validate_job",
209 "Validate a job",
210 read.clone(),
211 "Checks a job without starting it: the envelope, the input files and the worker's own validation of the payload. Returns the resolved job with its task_count, or an invalid_job error explaining the problem. Pass exactly one of job or spec_path.",
212 object(job_properties(), &[]),
213 ),
214 (
215 "submit_job",
216 "Submit a job",
217 json!({"readOnlyHint":false,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false}),
218 "Starts a job and returns its handle (job_id, state, directory) once the job exists durably. Submission is idempotent: the same request_key with the same content returns the existing job; other content under a used key fails with request_key_conflict. A job that needs more CPU slots than are free waits; one that needs more than the node has fails with capacity_exceeded. The job runs detached from this server and survives its restart. Clients with the MCP Tasks extension get a task that completes with the job's result. Pass exactly one of job or spec_path.",
219 object(job_properties(), &[]),
220 ),
221 (
222 "get_job",
223 "Get a job's state",
224 read.clone(),
225 "The job's state (submitted, starting, waiting, running, completed, failed, cancelled, timed_out or interrupted), its progress (completed and requested tasks, known work) and its directory. observed_state reports a launcher lost or an attempt interrupted by a reboot; repair_job finalizes those.",
226 object(json!({"job_id":job_id}), &["job_id"]),
227 ),
228 (
229 "wait_job",
230 "Wait for a job",
231 read.clone(),
232 "Waits until the job ends, is observed interrupted, or timeout_seconds pass, and returns get_job's answer. Call again to keep waiting. Reports progress (completed tasks) when the client asks for it.",
233 object(
234 json!({"job_id":job_id,"timeout_seconds":{"type":"number","exclusiveMinimum":0,"maximum":MAX_WAIT_SECONDS,"default":30,"description":"At most 600."}}),
235 &["job_id"],
236 ),
237 ),
238 (
239 "get_result",
240 "Get a job's result",
241 read.clone(),
242 "The result of an ended job. By default a summary: status, accounting, counts of claims and terminations, and per task its claim, termination, feasibility, objective and evidence (the first 100 tasks; no points). tasks returns the complete records (points, details) of the given task IDs; full returns the whole result manifest if it is under 1 MiB. A job that has not ended returns not_finished.",
243 object(
244 json!({
245 "job_id": job_id,
246 "tasks": {"type":"array","items":{"type":"integer","minimum":0},"maxItems":100,"description":"Task IDs whose complete records to return."},
247 "full": {"type":"boolean","default":false,"description":"Return the whole result manifest."},
248 }),
249 &["job_id"],
250 ),
251 ),
252 (
253 "get_events",
254 "Get a job's events",
255 read.clone(),
256 "The job's lifecycle journal (admission, start, cancellation, deadline, finish), newest last.",
257 object(
258 json!({"job_id":job_id,"limit":{"type":"integer","minimum":1,"maximum":1000,"default":50,"description":"Return the last limit events."}}),
259 &["job_id"],
260 ),
261 ),
262 (
263 "get_artifact",
264 "Read a job artifact",
265 read.clone(),
266 "A file of a job, also while it runs: results (the result journal) or an artifact its worker declared, such as an evaluation log or a warm-start snapshot. get_job lists them with format and size (artifact_index); the result adds their SHA-256. Without offset and limit, the whole content up to 1 MiB; with them, a page of the checked records of a records artifact, continued from next_offset while it is below available.",
267 object(
268 json!({
269 "job_id":job_id,
270 "name":{"type":"string","description":"Artifact name from artifact_index of get_job or the result."},
271 "offset":{"type":"integer","minimum":0,"description":"First record of the page; records artifacts only."},
272 "limit":{"type":"integer","minimum":1,"maximum":10000,"description":"Records of the page (default 100); records artifacts only."},
273 }),
274 &["job_id", "name"],
275 ),
276 ),
277 (
278 "list_jobs",
279 "List jobs",
280 read,
281 "The jobs on this node, newest first: ID, state, progress and timestamps.",
282 object(
283 json!({
284 "active_only": {"type":"boolean","default":false,"description":"Only jobs that have not ended."},
285 "limit": {"type":"integer","minimum":1,"maximum":1000,"default":50},
286 }),
287 &[],
288 ),
289 ),
290 (
291 "cancel_job",
292 "Cancel a job",
293 json!({"readOnlyHint":false,"destructiveHint":true,"idempotentHint":true,"openWorldHint":false}),
294 "Stops a job gracefully: running tasks finish their current unit of work (a retry, a generation, a solve) and every completed task stays in the result; the job ends cancelled. A job that has already ended returns already_terminal.",
295 object(json!({"job_id":job_id}), &["job_id"]),
296 ),
297 (
298 "kill_job",
299 "Kill a job",
300 json!({"readOnlyHint":false,"destructiveHint":true,"idempotentHint":true,"openWorldHint":false}),
301 "Stops a job immediately: the worker is killed after one second and the work in progress is lost; committed task results stay. Prefer cancel_job.",
302 object(json!({"job_id":job_id}), &["job_id"]),
303 ),
304 (
305 "repair_job",
306 "Repair an interrupted job",
307 json!({"readOnlyHint":false,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false}),
308 "Finalizes a job whose launcher was lost or that a reboot interrupted (get_job shows observed_state), keeping every committed task result and the exact accounting where it is known. Refuses (attempt_active, liveness_unknown) while a process may still own the job.",
309 object(json!({"job_id":job_id}), &["job_id"]),
310 ),
311 ];
312 tools
313 .into_iter()
314 .map(|(name, title, annotations, description, schema)| {
315 let mut annotations = annotations;
316 annotations["title"] = json!(title);
317 json!({"name":name,"title":title,"description":description,"inputSchema":schema,"annotations":annotations})
318 })
319 .collect()
320}
321
322pub fn exists(name: &str) -> bool {
323 definitions().iter().any(|t| t["name"] == name)
324}
325
326pub fn call(server: &Server, name: &str, args: &Value, ctx: &Ctx) -> Outcome {
327 let result = match name {
328 "get_guide" => guide::get(args),
329 "describe_node" => describe_node(server, ctx),
330 "describe_worker" => string(args, "worker")
331 .and_then(|worker| server.cli(&["problems", "describe", "--", &worker], QUICK, ctx)),
332 "validate_job" => server.validation_permit(ctx).and_then(|_permit| {
333 let staged = stage(server, args)?;
334 server.cli(
335 &["validate", &format!("--spec={}", path(&staged.spec))],
336 SLOW,
337 ctx,
338 )
339 }),
340 "put_input" => inputs::put(server, args, ctx),
341 "submit_job" => return submit_job(server, args, ctx),
342 "get_job" => job_id(args).and_then(|id| server.get(&id, ctx)),
343 "wait_job" => wait_job(server, args, ctx),
344 "get_result" => get_result(server, args, ctx),
345 "get_events" => get_events(server, args, ctx),
346 "get_artifact" => get_artifact(server, args, ctx),
347 "list_jobs" => list_jobs(server, args, ctx),
348 "cancel_job" => job_id(args).and_then(|id| cancel(server, &id, false)),
349 "kill_job" => job_id(args).and_then(|id| cancel(server, &id, true)),
350 "repair_job" => job_id(args).and_then(|id| repair(server, &id)),
351 _ => Err(fail("invalid_arguments", format!("unknown tool {name}"))),
352 };
353 match result {
354 Ok(value) => Outcome::Done(value),
355 Err(Fail::Tool(error)) => Outcome::Failed(error),
356 Err(Fail::Cancelled) => Outcome::Cancelled,
357 }
358}
359
360fn path(p: &Path) -> String {
361 p.to_string_lossy().into_owned()
362}
363
364pub(super) fn string(args: &Value, key: &str) -> Result<String, Fail> {
365 args[key]
366 .as_str()
367 .filter(|s| !s.is_empty())
368 .map(str::to_owned)
369 .ok_or_else(|| {
370 fail(
371 "invalid_arguments",
372 format!("{key} must be a non-empty string"),
373 )
374 })
375}
376
377pub(super) fn job_id(args: &Value) -> Result<String, Fail> {
378 let id = string(args, "job_id")?;
379 if id.len() != 32 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
380 return Err(fail(
381 "invalid_arguments",
382 format!("job_id {id:?} is not a 32-digit hexadecimal job ID"),
383 ));
384 }
385 Ok(id)
386}
387
388fn limit(args: &Value, default: usize) -> Result<usize, Fail> {
389 match &args["limit"] {
390 Value::Null => Ok(default),
391 v => v
392 .as_u64()
393 .filter(|n| (1..=1000).contains(n))
394 .map(|n| n as usize)
395 .ok_or_else(|| {
396 fail(
397 "invalid_arguments",
398 "limit must be an integer from 1 to 1000",
399 )
400 }),
401 }
402}
403
404fn runner_error(stderr: &[u8]) -> ToolError {
406 let text = String::from_utf8_lossy(stderr);
407 for line in text.lines().rev() {
408 if let Ok(v) = serde_json::from_str::<Value>(line)
409 && let Some(code) = v["error"]["code"].as_str()
410 {
411 return ToolError {
412 code: code.into(),
413 message: v["error"]["message"].as_str().unwrap_or_default().into(),
414 retryable: v["error"]["retryable"].as_bool().unwrap_or(false),
415 };
416 }
417 }
418 ToolError {
419 code: "runner_error".into(),
420 message: format!("optimization-run failed: {}", text.trim()),
421 retryable: false,
422 }
423}
424
425impl Server {
426 pub fn cli(&self, args: &[&str], timeout: Duration, ctx: &Ctx) -> Result<Value, Fail> {
429 self.invoke(args, timeout, Some(&|| ctx.stopped(self)))
430 }
431
432 pub fn cli_mutating(&self, args: &[&str]) -> Result<Value, Fail> {
437 self.invoke(args, MUTATING, None)
438 }
439
440 fn invoke(
441 &self,
442 args: &[&str],
443 timeout: Duration,
444 abort: Option<&dyn Fn() -> bool>,
445 ) -> Result<Value, Fail> {
446 let mut argv = vec![path(&self.runner), "--root".into(), path(&self.root)];
447 argv.extend(args.iter().map(|a| a.to_string()));
448 let never = || false;
449 match bounded_command_until(&argv, vec![], timeout, OUTPUT_CAP, abort.unwrap_or(&never)) {
450 Ok((status, out, _)) if status.success() => serde_json::from_slice(&out)
451 .map_err(|e| fail("runner_error", format!("unreadable runner output: {e}"))),
452 Ok((_, _, err)) => Err(Fail::Tool(runner_error(&err))),
453 Err(e) if e.kind() == ErrorKind::Interrupted => Err(Fail::Cancelled),
454 Err(e) if e.kind() == ErrorKind::TimedOut => Err(Fail::Tool(ToolError {
455 code: "mcp_timeout".into(),
456 message: format!(
457 "optimization-run {} did not answer within {} s",
458 args.first().copied().unwrap_or_default(),
459 timeout.as_secs()
460 ),
461 retryable: true,
462 })),
463 Err(e) => Err(fail(
464 "runner_error",
465 format!("cannot run {}: {e}", self.runner.display()),
466 )),
467 }
468 }
469
470 pub fn get(&self, id: &str, ctx: &Ctx) -> Result<Value, Fail> {
472 let mut job = self.cli(&["jobs", "get", "--", id], QUICK, ctx)?;
473 job["job_id"] = json!(id);
474 Ok(job)
475 }
476}
477
478fn describe_node(server: &Server, ctx: &Ctx) -> Result<Value, Fail> {
479 let doctor = server.cli(&["node", "doctor"], QUICK, ctx)?;
480 let registry = server.cli(&["workers", "list"], QUICK, ctx)?;
481 let workers: Vec<Value> = registry
482 .as_object()
483 .map(|workers| {
484 workers
485 .iter()
486 .map(|(id, w)| {
487 let d = &w["description"];
488 json!({"worker":id,"protocol":d["protocol"],"profiles":d["profiles"],"engine":d["engine"],"build":d["build"]})
489 })
490 .collect()
491 })
492 .unwrap_or_default();
493 let mut node = json!({
494 "root": path(&server.root),
495 "capacity": doctor["capacity"],
496 "launch": server.launch.name(),
497 "systemd_user_manager": doctor["systemd_user_manager"],
498 "host": doctor["host"],
499 "warnings": doctor["warnings"],
500 "capabilities": doctor["capabilities"],
501 "workers": workers,
502 });
503 if doctor["capacity"].is_null() {
504 node["note"] = json!(format!(
505 "the node is not initialized; its owner runs: optimization-run --root {} node init --capacity N",
506 server.root.display()
507 ));
508 } else if node["workers"].as_array().is_some_and(Vec::is_empty) {
509 node["note"] = json!(format!(
510 "no worker is registered; its owner runs: optimization-run --root {} workers add --id ID --executable PATH",
511 server.root.display()
512 ));
513 }
514 Ok(node)
515}
516
517struct Staged {
520 spec: PathBuf,
521 job: Value,
522 request_key: String,
523 dir: Option<tempfile::TempDir>,
524}
525
526fn staging(root: &Path) -> PathBuf {
527 root.join("mcp").join("staging")
528}
529
530fn launch_logs(root: &Path) -> PathBuf {
531 root.join("mcp").join("launch")
532}
533
534fn older_than_a_day(entry: &fs::DirEntry) -> bool {
535 entry
536 .metadata()
537 .and_then(|m| m.modified())
538 .ok()
539 .and_then(|t| t.elapsed().ok())
540 .is_some_and(|age| age > Duration::from_secs(86_400))
541}
542
543pub fn clean_staging(root: &Path) {
546 for entry in fs::read_dir(staging(root)).into_iter().flatten().flatten() {
547 if older_than_a_day(&entry) {
548 let _ = fs::remove_dir_all(entry.path());
549 }
550 }
551 for entry in fs::read_dir(launch_logs(root))
552 .into_iter()
553 .flatten()
554 .flatten()
555 {
556 if older_than_a_day(&entry) && entry.metadata().is_ok_and(|m| m.len() == 0) {
557 let _ = fs::remove_file(entry.path());
558 }
559 }
560}
561
562fn stage(server: &Server, args: &Value) -> Result<Staged, Fail> {
563 let staged = match (&args["job"], &args["spec_path"]) {
564 (Value::Object(_), Value::Null) => stage_inline(server, args)?,
565 (Value::Null, Value::String(file)) => {
566 let spec = fs::canonicalize(file)
567 .map_err(|e| fail("invalid_arguments", format!("spec_path {file}: {e}")))?;
568 let job = read_json_file(&spec, MAX_INPUT_BYTES)
569 .map_err(|e| fail("invalid_arguments", format!("spec_path {file}: {e}")))?;
570 Staged {
571 request_key: String::new(),
572 spec,
573 job,
574 dir: None,
575 }
576 }
577 _ => {
578 return Err(fail(
579 "invalid_arguments",
580 "pass exactly one of job (an object) or spec_path (a string)",
581 ));
582 }
583 };
584 if staged.job["schema_version"] == crate::command::SCHEMA {
585 return Err(fail(
586 "unsupported_job_kind",
587 "command jobs are CLI-only: the node owner runs them with optimization-run",
588 ));
589 }
590 let request_key = staged.job["request_key"]
591 .as_str()
592 .filter(|k| !k.is_empty())
593 .ok_or_else(|| {
594 fail(
595 "invalid_job",
596 "the job needs a non-empty string request_key",
597 )
598 })?
599 .to_owned();
600 Ok(Staged {
601 request_key,
602 ..staged
603 })
604}
605
606fn read_json_file(path: &Path, cap: u64) -> Result<Value, String> {
608 serde_json::from_slice(&read_file(path, cap)?).map_err(|e| e.to_string())
609}
610
611pub(super) fn read_file(path: &Path, cap: u64) -> Result<Vec<u8>, String> {
613 use std::io::Read;
614 let metadata = fs::metadata(path).map_err(|e| e.to_string())?;
615 if !metadata.is_file() {
616 return Err("not a regular file".into());
617 }
618 if metadata.len() > cap {
619 return Err(format!("{} bytes, over the cap of {cap}", metadata.len()));
620 }
621 let mut bytes = Vec::new();
622 fs::File::open(path)
623 .and_then(|f| f.take(cap + 1).read_to_end(&mut bytes))
624 .map_err(|e| e.to_string())?;
625 if bytes.len() as u64 > cap {
626 return Err(format!("over the cap of {cap} bytes"));
627 }
628 Ok(bytes)
629}
630
631fn stage_inline(server: &Server, args: &Value) -> Result<Staged, Fail> {
634 let job = args["job"].clone();
635 let base = match &args["input_dir"] {
636 Value::Null => server.input_dir.clone(),
637 Value::String(dir) => fs::canonicalize(dir)
638 .map_err(|e| fail("invalid_arguments", format!("input_dir {dir}: {e}")))?,
639 _ => return Err(fail("invalid_arguments", "input_dir must be a string")),
640 };
641 let parent = staging(&server.root);
642 fs::create_dir_all(&parent)
643 .map_err(|e| fail("runner_error", format!("{}: {e}", parent.display())))?;
644 let dir = tempfile::Builder::new()
645 .prefix("job-")
646 .tempdir_in(&parent)
647 .map_err(|e| fail("runner_error", format!("{}: {e}", parent.display())))?;
648 let envelope_valid = serde_json::from_value::<JobSpec>(job.clone())
652 .ok()
653 .is_some_and(|spec| spec.validate().is_ok());
654 if let Some(inputs) = job["inputs"].as_array().filter(|_| envelope_valid) {
655 for value in inputs {
656 let Ok(input) = serde_json::from_value::<Input>(value.clone()) else {
658 continue;
659 };
660 let relative = Path::new(&input.file);
661 if relative
662 .components()
663 .any(|c| !matches!(c, Component::Normal(_) | Component::CurDir))
664 {
665 continue;
666 }
667 let bytes = checked_input(&base, &input).map_err(|e| {
668 fail(
669 "invalid_job",
670 format!(
671 "input {} ({}): {e}",
672 input.name,
673 base.join(relative).display()
674 ),
675 )
676 })?;
677 let target = dir.path().join(relative);
678 if let Some(parent) = target.parent() {
679 fs::create_dir_all(parent)
680 .map_err(|e| fail("runner_error", format!("{}: {e}", parent.display())))?;
681 }
682 fs::write(&target, bytes)
683 .map_err(|e| fail("runner_error", format!("{}: {e}", target.display())))?;
684 }
685 }
686 let spec = loop {
688 let spec = dir
689 .path()
690 .join(format!(".mcp-job-{}.json", &random_hex()[..12]));
691 if !spec.exists() {
692 break spec;
693 }
694 };
695 fs::write(&spec, job.to_string())
696 .map_err(|e| fail("runner_error", format!("{}: {e}", spec.display())))?;
697 Ok(Staged {
698 spec,
699 job,
700 request_key: String::new(),
701 dir: Some(dir),
702 })
703}
704
705fn submit_job(server: &Server, args: &Value, ctx: &Ctx) -> Outcome {
706 let permit = match server.validation_permit(ctx) {
708 Ok(permit) => permit,
709 Err(Fail::Tool(error)) => return Outcome::Failed(error),
710 Err(Fail::Cancelled) => return Outcome::Cancelled,
711 };
712 let submitted = stage(server, args).and_then(|staged| match server.launch {
713 Launch::Systemd => {
714 let job =
715 server.cli_mutating(&["submit", &format!("--spec={}", path(&staged.spec))])?;
716 let id = job["id"].as_str().unwrap_or_default().to_owned();
717 server.get(&id, ctx)
718 }
719 Launch::Process => launch_process(server, staged),
720 });
721 drop(permit);
722 let job = match submitted {
723 Ok(job) => job,
724 Err(Fail::Tool(error)) => return Outcome::Failed(error),
725 Err(Fail::Cancelled) => return Outcome::Cancelled,
726 };
727 if !ctx.tasks {
728 return Outcome::Done(job);
729 }
730 let job_id = job["job_id"].as_str().unwrap_or_default();
731 match tasks::create(server, job_id, &job, ctx) {
732 Ok(task) => Outcome::Task(task),
733 Err(_) => Outcome::Done(job),
735 }
736}
737
738fn uninterrupted() -> Ctx {
741 Ctx {
742 modern: false,
743 tasks: false,
744 cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
745 progress: None,
746 id: Value::Null,
747 }
748}
749
750fn launch_process(server: &Server, staged: Staged) -> Result<Value, Fail> {
759 let quiet = uninterrupted();
760 let id = digest(staged.request_key.as_bytes())[..32].to_owned();
761 let existed = server.get(&id, &quiet).is_ok();
762 let logs = launch_logs(&server.root);
763 fs::create_dir_all(&logs)
764 .map_err(|e| fail("runner_error", format!("{}: {e}", logs.display())))?;
765 let log = logs.join(format!("{id}-{}.log", &random_hex()[..8]));
766 let stderr = fs::File::create(&log)
767 .map_err(|e| fail("runner_error", format!("{}: {e}", log.display())))?;
768 let mut command = Command::new(&server.runner);
769 command
770 .arg("--root")
771 .arg(&server.root)
772 .arg("run")
773 .arg(format!("--spec={}", path(&staged.spec)))
774 .stdin(Stdio::null())
775 .stdout(Stdio::null())
776 .stderr(stderr);
777 #[cfg(unix)]
778 {
779 use std::os::unix::process::CommandExt;
780 unsafe {
783 command.pre_exec(|| {
784 libc::setsid();
785 Ok(())
786 });
787 }
788 }
789 let mut child = command.spawn().map_err(|e| {
790 fail(
791 "runner_error",
792 format!("cannot start {}: {e}", server.runner.display()),
793 )
794 })?;
795 let Staged { job, dir, .. } = staged;
796 let reap =
799 move |mut child: std::process::Child, log: PathBuf, dir: Option<tempfile::TempDir>| {
800 thread::spawn(move || {
801 let succeeded = child.wait().is_ok_and(|s| s.success());
802 drop(dir);
803 if succeeded {
804 let _ = fs::remove_file(log);
805 }
806 });
807 };
808 let start = Instant::now();
809 loop {
810 match child.try_wait() {
811 Ok(Some(status)) => {
812 let text = fs::read(&log).unwrap_or_default();
813 let _ = fs::remove_file(&log);
814 if !status.success() {
815 return Err(Fail::Tool(runner_error(&text)));
816 }
817 return server.get(&id, &quiet);
819 }
820 Ok(None) => {}
821 Err(e) => {
822 reap(child, log, dir);
823 return Err(fail("runner_error", format!("launcher: {e}")));
824 }
825 }
826 if !existed
827 && let Ok(job_now) = server.get(&id, &quiet)
828 && job_now["directory"]
829 .as_str()
830 .and_then(|d| fs::read(Path::new(d).join("submitted.json")).ok())
831 .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())
832 .is_some_and(|submitted| submitted == job)
833 {
834 reap(child, log, None);
837 drop(dir);
838 return Ok(job_now);
839 }
840 if start.elapsed() > SLOW {
841 reap(child, log, dir);
842 return Err(Fail::Tool(ToolError {
843 code: "mcp_timeout".into(),
844 message: format!(
845 "the job was not confirmed within {} s; its launcher keeps running, so check get_job {id} before submitting again",
846 SLOW.as_secs()
847 ),
848 retryable: true,
849 }));
850 }
851 thread::sleep(Duration::from_millis(100));
852 }
853}
854
855fn wait_job(server: &Server, args: &Value, ctx: &Ctx) -> Result<Value, Fail> {
856 let id = job_id(args)?;
857 let timeout = match &args["timeout_seconds"] {
858 Value::Null => 30.0,
859 v => v
860 .as_f64()
861 .filter(|t| t.is_finite() && *t > 0.0 && *t <= MAX_WAIT_SECONDS)
862 .ok_or_else(|| {
863 fail(
864 "invalid_arguments",
865 format!("timeout_seconds must be in (0, {MAX_WAIT_SECONDS}]"),
866 )
867 })?,
868 };
869 let start = Instant::now();
870 let mut reported: Option<u64> = None;
871 loop {
872 let job = server.get(&id, ctx)?;
873 if let Some(done) = job["completed_tasks"].as_u64()
874 && reported.is_none_or(|r| done > r)
875 {
876 let state = job["state"].as_str().unwrap_or_default();
877 server.progress(ctx, done, job["requested_tasks"].as_u64(), state);
878 reported = Some(done);
879 }
880 if terminal(&job["state"])
881 || !job["observed_state"].is_null()
882 || start.elapsed().as_secs_f64() >= timeout
883 {
884 return Ok(job);
885 }
886 pause(server, ctx, Duration::from_millis(500));
887 if ctx.stopped(server) {
888 return Err(Fail::Cancelled);
889 }
890 }
891}
892
893pub fn read_manifest(job: &Value) -> Result<Vec<u8>, ToolError> {
897 if job["kind"] == "command" {
898 return Err(ToolError {code:"unsupported_job_kind".into(), message:"command results are available through optimization-run result; binary outputs through jobs collect".into(), retryable:false});
899 }
900 let id = job["job_id"].as_str().unwrap_or_default();
901 if !terminal(&job["state"]) {
902 let mut message = format!(
903 "job {id} is {}; wait_job until it ends",
904 job["state"].as_str().unwrap_or("unknown")
905 );
906 if let Some(observed) = job["observed_state"].as_str() {
907 message = format!("job {id} was observed {observed}; repair_job finalizes it");
908 }
909 return Err(ToolError {
910 code: "not_finished".into(),
911 message,
912 retryable: false,
913 });
914 }
915 let file = Path::new(job["directory"].as_str().unwrap_or_default()).join("run.json");
916 read_file(&file, MANIFEST_CAP).map_err(|e| {
919 let code = if e.contains("over the cap") {
920 "result_too_large"
921 } else {
922 "runner_error"
923 };
924 ToolError {
925 code: code.into(),
926 message: format!("{}: {e}", file.display()),
927 retryable: false,
928 }
929 })
930}
931
932#[derive(Deserialize)]
934struct ManifestView<'a> {
935 #[serde(default)]
936 status: Value,
937 #[serde(default)]
938 schema_version: Value,
939 #[serde(default)]
940 worker: Value,
941 #[serde(default)]
942 payload_schema: Value,
943 #[serde(default)]
944 completed_tasks: Value,
945 #[serde(default)]
946 requested_tasks: Value,
947 #[serde(default)]
948 elapsed_seconds: Value,
949 #[serde(default)]
950 work: Value,
951 #[serde(default)]
952 artifacts: Value,
953 #[serde(default)]
954 runner: RunnerView,
955 #[serde(borrow, default)]
956 results: Vec<&'a RawValue>,
957}
958
959#[derive(Default, Deserialize)]
960struct RunnerView {
961 #[serde(default)]
962 accounting_complete: Value,
963 #[serde(default)]
964 artifact_index: Value,
965}
966
967#[derive(Default, Deserialize)]
968struct RecordView {
969 #[serde(default)]
970 task_id: Value,
971 #[serde(default)]
972 outcome: OutcomeView,
973}
974
975#[derive(Default, Deserialize)]
976struct OutcomeView {
977 #[serde(default)]
978 claim: Value,
979 #[serde(default)]
980 termination: Value,
981 #[serde(default)]
982 feasible: Value,
983 #[serde(default)]
984 objective: Value,
985 #[serde(default)]
986 evidence: EvidenceView,
987 #[serde(default)]
988 objective_bounds: Value,
989 #[serde(default)]
990 imprecise: Value,
991}
992
993#[derive(Default, Deserialize)]
994struct EvidenceView {
995 #[serde(default)]
996 level: Value,
997 #[serde(default)]
998 refuted: Value,
999}
1000
1001fn view(bytes: &[u8]) -> Result<ManifestView<'_>, ToolError> {
1002 serde_json::from_slice(bytes).map_err(|e| ToolError {
1003 code: "runner_error".into(),
1004 message: format!("unreadable result manifest: {e}"),
1005 retryable: false,
1006 })
1007}
1008
1009pub fn summary(job: &Value, bytes: &[u8]) -> Result<Value, ToolError> {
1012 let manifest = view(bytes)?;
1013 let mut claims = BTreeMap::<String, u64>::new();
1014 let mut terminations = BTreeMap::<String, u64>::new();
1015 let mut tasks = vec![];
1016 for raw in &manifest.results {
1017 let r: RecordView = serde_json::from_str(raw.get()).unwrap_or_default();
1018 let o = &r.outcome;
1019 *claims
1020 .entry(o.claim.as_str().unwrap_or("unknown").into())
1021 .or_default() += 1;
1022 *terminations
1023 .entry(o.termination.as_str().unwrap_or("unknown").into())
1024 .or_default() += 1;
1025 if tasks.len() < SUMMARY_TASKS {
1026 let mut task = json!({
1027 "task_id": r.task_id,
1028 "claim": o.claim,
1029 "termination": o.termination,
1030 "feasible": o.feasible,
1031 "objective": o.objective,
1032 "evidence": o.evidence.level,
1033 });
1034 for (key, value) in [
1035 ("objective_bounds", &o.objective_bounds),
1036 ("imprecise", &o.imprecise),
1037 ("refuted", &o.evidence.refuted),
1038 ] {
1039 if !value.is_null() {
1040 task[key] = value.clone();
1041 }
1042 }
1043 tasks.push(task);
1044 }
1045 }
1046 let mut summary = json!({
1047 "job_id": job["job_id"],
1048 "state": job["state"],
1049 "status": manifest.status,
1050 "schema_version": manifest.schema_version,
1051 "worker": manifest.worker,
1052 "payload_schema": manifest.payload_schema,
1053 "completed_tasks": manifest.completed_tasks,
1054 "requested_tasks": manifest.requested_tasks,
1055 "elapsed_seconds": manifest.elapsed_seconds,
1056 "work": manifest.work,
1057 "accounting_complete": manifest.runner.accounting_complete,
1058 "claims": claims,
1059 "terminations": terminations,
1060 "tasks": tasks,
1061 "tasks_omitted": manifest.results.len().saturating_sub(SUMMARY_TASKS),
1062 "artifacts": manifest.artifacts,
1063 "directory": job["directory"],
1064 });
1065 if !manifest.runner.artifact_index.is_null() {
1066 summary["artifact_index"] = manifest.runner.artifact_index;
1067 }
1068 Ok(summary)
1069}
1070
1071fn get_result(server: &Server, args: &Value, ctx: &Ctx) -> Result<Value, Fail> {
1072 let id = job_id(args)?;
1073 let job = server.get(&id, ctx)?;
1074 let bytes = read_manifest(&job).map_err(Fail::Tool)?;
1075 let too_large = |size: usize| {
1076 fail(
1077 "result_too_large",
1078 format!(
1079 "the result manifest has {size} bytes, over the 1 MiB inline cap; pass tasks, or read {}/run.json",
1080 job["directory"].as_str().unwrap_or_default()
1081 ),
1082 )
1083 };
1084 if args["full"].as_bool() == Some(true) {
1085 if bytes.len() > 4 * FULL_CAP {
1087 return Err(too_large(bytes.len()));
1088 }
1089 let manifest: Value = serde_json::from_slice(&bytes)
1090 .map_err(|e| fail("runner_error", format!("unreadable result manifest: {e}")))?;
1091 let size = manifest.to_string().len();
1092 if size > FULL_CAP {
1093 return Err(too_large(size));
1094 }
1095 return Ok(manifest);
1096 }
1097 match &args["tasks"] {
1098 Value::Null => summary(&job, &bytes).map_err(Fail::Tool),
1099 Value::Array(ids) => {
1100 let wanted: Vec<u64> = ids.iter().filter_map(Value::as_u64).collect();
1101 if wanted.len() != ids.len() || wanted.len() > 100 {
1102 return Err(fail(
1103 "invalid_arguments",
1104 "tasks must be at most 100 non-negative integer task IDs",
1105 ));
1106 }
1107 let manifest = view(&bytes).map_err(Fail::Tool)?;
1108 let mut records = vec![];
1109 for raw in &manifest.results {
1110 #[derive(Deserialize)]
1111 struct Id {
1112 task_id: Option<u64>,
1113 }
1114 let selected = serde_json::from_str::<Id>(raw.get())
1115 .ok()
1116 .and_then(|r| r.task_id)
1117 .is_some_and(|t| wanted.contains(&t));
1118 if selected && let Ok(record) = serde_json::from_str::<Value>(raw.get()) {
1119 records.push(record);
1120 }
1121 }
1122 Ok(json!({"job_id":id,"state":job["state"],"tasks":records}))
1123 }
1124 _ => Err(fail("invalid_arguments", "tasks must be an array")),
1125 }
1126}
1127
1128fn get_artifact(server: &Server, args: &Value, ctx: &Ctx) -> Result<Value, Fail> {
1129 let id = job_id(args)?;
1130 let name = string(args, "name")?;
1131 let mut argv = vec!["jobs".to_string(), "artifact".into()];
1132 for (key, low, high) in [("offset", 0, u32::MAX as u64), ("limit", 1, 10_000)] {
1133 match &args[key] {
1134 Value::Null => {}
1135 v => {
1136 let n = v
1137 .as_u64()
1138 .filter(|n| (low..=high).contains(n))
1139 .ok_or_else(|| {
1140 fail(
1141 "invalid_arguments",
1142 format!("{key} must be an integer from {low} to {high}"),
1143 )
1144 })?;
1145 argv.push(format!("--{key}={n}"));
1146 }
1147 }
1148 }
1149 argv.extend(["--".into(), id, name]);
1150 let argv: Vec<&str> = argv.iter().map(String::as_str).collect();
1151 server.cli(&argv, QUICK, ctx)
1152}
1153
1154fn get_events(server: &Server, args: &Value, ctx: &Ctx) -> Result<Value, Fail> {
1155 let id = job_id(args)?;
1156 let limit = limit(args, 50)?;
1157 let events = server.cli(&["jobs", "events", "--", &id], QUICK, ctx)?;
1158 let events = events.as_array().cloned().unwrap_or_default();
1159 let skip = events.len().saturating_sub(limit);
1160 Ok(json!({"job_id":id,"total":events.len(),"events":events[skip..]}))
1161}
1162
1163fn list_jobs(server: &Server, args: &Value, ctx: &Ctx) -> Result<Value, Fail> {
1164 let limit = limit(args, 50)?;
1165 let active_only = args["active_only"].as_bool() == Some(true);
1166 let jobs = server.cli(&["jobs", "list"], SLOW, ctx)?;
1167 let mut jobs: Vec<Value> = jobs
1168 .as_array()
1169 .cloned()
1170 .unwrap_or_default()
1171 .into_iter()
1172 .filter(|j| !active_only || !terminal(&j["state"]))
1173 .map(|j| {
1174 let mut job = json!({"job_id":j["id"],"state":j["state"]});
1175 for key in [
1176 "observed_state",
1177 "error",
1178 "completed_tasks",
1179 "requested_tasks",
1180 "submitted_at",
1181 "finished_at",
1182 "cancel_requested",
1183 ] {
1184 if !j[key].is_null() {
1185 job[key] = j[key].clone();
1186 }
1187 }
1188 job
1189 })
1190 .collect();
1191 jobs.sort_by(|a, b| {
1192 let t = |j: &Value| j["submitted_at"].as_f64().unwrap_or(0.0);
1193 t(b).total_cmp(&t(a))
1194 });
1195 let total = jobs.len();
1196 jobs.truncate(limit);
1197 Ok(json!({"total":total,"jobs":jobs}))
1198}
1199
1200pub fn cancel(server: &Server, id: &str, now: bool) -> Result<Value, Fail> {
1201 let mut args = vec!["jobs", "cancel"];
1202 if now {
1203 args.push("--now");
1204 }
1205 args.extend(["--", id]);
1206 let mut job = server.cli_mutating(&args)?;
1207 job["job_id"] = json!(id);
1208 Ok(job)
1209}
1210
1211pub fn repair(server: &Server, id: &str) -> Result<Value, Fail> {
1212 let mut job = server.cli_mutating(&["jobs", "repair", "--", id])?;
1213 job["job_id"] = json!(id);
1214 Ok(job)
1215}
1216
1217#[cfg(test)]
1218mod tests {
1219 #[test]
1220 fn command_results_are_never_summarized_as_optimization() {
1221 let error = super::read_manifest(
1222 &serde_json::json!({"kind":"command","state":"completed","directory":"/missing"}),
1223 )
1224 .unwrap_err();
1225 assert_eq!(error.code, "unsupported_job_kind");
1226 }
1227
1228 #[test]
1231 fn embedded_job_schema_matches_the_published_one() {
1232 let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
1233 let published =
1234 manifest.join("../../docs/job-api/schemas/optimization.job-0.1.schema.json");
1235 if let Ok(published) = std::fs::read_to_string(published) {
1236 assert_eq!(
1237 published,
1238 include_str!("../../schemas/optimization.job-0.1.schema.json"),
1239 "copy docs/job-api/schemas/optimization.job-0.1.schema.json to crates/optimization-runner/schemas/"
1240 );
1241 }
1242 }
1243}