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 "workers": workers,
501 });
502 if doctor["capacity"].is_null() {
503 node["note"] = json!(format!(
504 "the node is not initialized; its owner runs: optimization-run --root {} node init --capacity N",
505 server.root.display()
506 ));
507 } else if node["workers"].as_array().is_some_and(Vec::is_empty) {
508 node["note"] = json!(format!(
509 "no worker is registered; its owner runs: optimization-run --root {} workers add --id ID --executable PATH",
510 server.root.display()
511 ));
512 }
513 Ok(node)
514}
515
516struct Staged {
519 spec: PathBuf,
520 job: Value,
521 request_key: String,
522 dir: Option<tempfile::TempDir>,
523}
524
525fn staging(root: &Path) -> PathBuf {
526 root.join("mcp").join("staging")
527}
528
529fn launch_logs(root: &Path) -> PathBuf {
530 root.join("mcp").join("launch")
531}
532
533fn older_than_a_day(entry: &fs::DirEntry) -> bool {
534 entry
535 .metadata()
536 .and_then(|m| m.modified())
537 .ok()
538 .and_then(|t| t.elapsed().ok())
539 .is_some_and(|age| age > Duration::from_secs(86_400))
540}
541
542pub fn clean_staging(root: &Path) {
545 for entry in fs::read_dir(staging(root)).into_iter().flatten().flatten() {
546 if older_than_a_day(&entry) {
547 let _ = fs::remove_dir_all(entry.path());
548 }
549 }
550 for entry in fs::read_dir(launch_logs(root))
551 .into_iter()
552 .flatten()
553 .flatten()
554 {
555 if older_than_a_day(&entry) && entry.metadata().is_ok_and(|m| m.len() == 0) {
556 let _ = fs::remove_file(entry.path());
557 }
558 }
559}
560
561fn stage(server: &Server, args: &Value) -> Result<Staged, Fail> {
562 let staged = match (&args["job"], &args["spec_path"]) {
563 (Value::Object(_), Value::Null) => stage_inline(server, args)?,
564 (Value::Null, Value::String(file)) => {
565 let spec = fs::canonicalize(file)
566 .map_err(|e| fail("invalid_arguments", format!("spec_path {file}: {e}")))?;
567 let job = read_json_file(&spec, MAX_INPUT_BYTES)
568 .map_err(|e| fail("invalid_arguments", format!("spec_path {file}: {e}")))?;
569 Staged {
570 request_key: String::new(),
571 spec,
572 job,
573 dir: None,
574 }
575 }
576 _ => {
577 return Err(fail(
578 "invalid_arguments",
579 "pass exactly one of job (an object) or spec_path (a string)",
580 ));
581 }
582 };
583 let request_key = staged.job["request_key"]
584 .as_str()
585 .filter(|k| !k.is_empty())
586 .ok_or_else(|| {
587 fail(
588 "invalid_job",
589 "the job needs a non-empty string request_key",
590 )
591 })?
592 .to_owned();
593 Ok(Staged {
594 request_key,
595 ..staged
596 })
597}
598
599fn read_json_file(path: &Path, cap: u64) -> Result<Value, String> {
601 serde_json::from_slice(&read_file(path, cap)?).map_err(|e| e.to_string())
602}
603
604pub(super) fn read_file(path: &Path, cap: u64) -> Result<Vec<u8>, String> {
606 use std::io::Read;
607 let metadata = fs::metadata(path).map_err(|e| e.to_string())?;
608 if !metadata.is_file() {
609 return Err("not a regular file".into());
610 }
611 if metadata.len() > cap {
612 return Err(format!("{} bytes, over the cap of {cap}", metadata.len()));
613 }
614 let mut bytes = Vec::new();
615 fs::File::open(path)
616 .and_then(|f| f.take(cap + 1).read_to_end(&mut bytes))
617 .map_err(|e| e.to_string())?;
618 if bytes.len() as u64 > cap {
619 return Err(format!("over the cap of {cap} bytes"));
620 }
621 Ok(bytes)
622}
623
624fn stage_inline(server: &Server, args: &Value) -> Result<Staged, Fail> {
627 let job = args["job"].clone();
628 let base = match &args["input_dir"] {
629 Value::Null => server.input_dir.clone(),
630 Value::String(dir) => fs::canonicalize(dir)
631 .map_err(|e| fail("invalid_arguments", format!("input_dir {dir}: {e}")))?,
632 _ => return Err(fail("invalid_arguments", "input_dir must be a string")),
633 };
634 let parent = staging(&server.root);
635 fs::create_dir_all(&parent)
636 .map_err(|e| fail("runner_error", format!("{}: {e}", parent.display())))?;
637 let dir = tempfile::Builder::new()
638 .prefix("job-")
639 .tempdir_in(&parent)
640 .map_err(|e| fail("runner_error", format!("{}: {e}", parent.display())))?;
641 let envelope_valid = serde_json::from_value::<JobSpec>(job.clone())
645 .ok()
646 .is_some_and(|spec| spec.validate().is_ok());
647 if let Some(inputs) = job["inputs"].as_array().filter(|_| envelope_valid) {
648 for value in inputs {
649 let Ok(input) = serde_json::from_value::<Input>(value.clone()) else {
651 continue;
652 };
653 let relative = Path::new(&input.file);
654 if relative
655 .components()
656 .any(|c| !matches!(c, Component::Normal(_) | Component::CurDir))
657 {
658 continue;
659 }
660 let bytes = checked_input(&base, &input).map_err(|e| {
661 fail(
662 "invalid_job",
663 format!(
664 "input {} ({}): {e}",
665 input.name,
666 base.join(relative).display()
667 ),
668 )
669 })?;
670 let target = dir.path().join(relative);
671 if let Some(parent) = target.parent() {
672 fs::create_dir_all(parent)
673 .map_err(|e| fail("runner_error", format!("{}: {e}", parent.display())))?;
674 }
675 fs::write(&target, bytes)
676 .map_err(|e| fail("runner_error", format!("{}: {e}", target.display())))?;
677 }
678 }
679 let spec = loop {
681 let spec = dir
682 .path()
683 .join(format!(".mcp-job-{}.json", &random_hex()[..12]));
684 if !spec.exists() {
685 break spec;
686 }
687 };
688 fs::write(&spec, job.to_string())
689 .map_err(|e| fail("runner_error", format!("{}: {e}", spec.display())))?;
690 Ok(Staged {
691 spec,
692 job,
693 request_key: String::new(),
694 dir: Some(dir),
695 })
696}
697
698fn submit_job(server: &Server, args: &Value, ctx: &Ctx) -> Outcome {
699 let permit = match server.validation_permit(ctx) {
701 Ok(permit) => permit,
702 Err(Fail::Tool(error)) => return Outcome::Failed(error),
703 Err(Fail::Cancelled) => return Outcome::Cancelled,
704 };
705 let submitted = stage(server, args).and_then(|staged| match server.launch {
706 Launch::Systemd => {
707 let job =
708 server.cli_mutating(&["submit", &format!("--spec={}", path(&staged.spec))])?;
709 let id = job["id"].as_str().unwrap_or_default().to_owned();
710 server.get(&id, ctx)
711 }
712 Launch::Process => launch_process(server, staged),
713 });
714 drop(permit);
715 let job = match submitted {
716 Ok(job) => job,
717 Err(Fail::Tool(error)) => return Outcome::Failed(error),
718 Err(Fail::Cancelled) => return Outcome::Cancelled,
719 };
720 if !ctx.tasks {
721 return Outcome::Done(job);
722 }
723 let job_id = job["job_id"].as_str().unwrap_or_default();
724 match tasks::create(server, job_id, &job, ctx) {
725 Ok(task) => Outcome::Task(task),
726 Err(_) => Outcome::Done(job),
728 }
729}
730
731fn uninterrupted() -> Ctx {
734 Ctx {
735 modern: false,
736 tasks: false,
737 cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
738 progress: None,
739 id: Value::Null,
740 }
741}
742
743fn launch_process(server: &Server, staged: Staged) -> Result<Value, Fail> {
752 let quiet = uninterrupted();
753 let id = digest(staged.request_key.as_bytes())[..32].to_owned();
754 let existed = server.get(&id, &quiet).is_ok();
755 let logs = launch_logs(&server.root);
756 fs::create_dir_all(&logs)
757 .map_err(|e| fail("runner_error", format!("{}: {e}", logs.display())))?;
758 let log = logs.join(format!("{id}-{}.log", &random_hex()[..8]));
759 let stderr = fs::File::create(&log)
760 .map_err(|e| fail("runner_error", format!("{}: {e}", log.display())))?;
761 let mut command = Command::new(&server.runner);
762 command
763 .arg("--root")
764 .arg(&server.root)
765 .arg("run")
766 .arg(format!("--spec={}", path(&staged.spec)))
767 .stdin(Stdio::null())
768 .stdout(Stdio::null())
769 .stderr(stderr);
770 #[cfg(unix)]
771 {
772 use std::os::unix::process::CommandExt;
773 unsafe {
776 command.pre_exec(|| {
777 libc::setsid();
778 Ok(())
779 });
780 }
781 }
782 let mut child = command.spawn().map_err(|e| {
783 fail(
784 "runner_error",
785 format!("cannot start {}: {e}", server.runner.display()),
786 )
787 })?;
788 let Staged { job, dir, .. } = staged;
789 let reap =
792 move |mut child: std::process::Child, log: PathBuf, dir: Option<tempfile::TempDir>| {
793 thread::spawn(move || {
794 let succeeded = child.wait().is_ok_and(|s| s.success());
795 drop(dir);
796 if succeeded {
797 let _ = fs::remove_file(log);
798 }
799 });
800 };
801 let start = Instant::now();
802 loop {
803 match child.try_wait() {
804 Ok(Some(status)) => {
805 let text = fs::read(&log).unwrap_or_default();
806 let _ = fs::remove_file(&log);
807 if !status.success() {
808 return Err(Fail::Tool(runner_error(&text)));
809 }
810 return server.get(&id, &quiet);
812 }
813 Ok(None) => {}
814 Err(e) => {
815 reap(child, log, dir);
816 return Err(fail("runner_error", format!("launcher: {e}")));
817 }
818 }
819 if !existed
820 && let Ok(job_now) = server.get(&id, &quiet)
821 && job_now["directory"]
822 .as_str()
823 .and_then(|d| fs::read(Path::new(d).join("submitted.json")).ok())
824 .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())
825 .is_some_and(|submitted| submitted == job)
826 {
827 reap(child, log, None);
830 drop(dir);
831 return Ok(job_now);
832 }
833 if start.elapsed() > SLOW {
834 reap(child, log, dir);
835 return Err(Fail::Tool(ToolError {
836 code: "mcp_timeout".into(),
837 message: format!(
838 "the job was not confirmed within {} s; its launcher keeps running, so check get_job {id} before submitting again",
839 SLOW.as_secs()
840 ),
841 retryable: true,
842 }));
843 }
844 thread::sleep(Duration::from_millis(100));
845 }
846}
847
848fn wait_job(server: &Server, args: &Value, ctx: &Ctx) -> Result<Value, Fail> {
849 let id = job_id(args)?;
850 let timeout = match &args["timeout_seconds"] {
851 Value::Null => 30.0,
852 v => v
853 .as_f64()
854 .filter(|t| t.is_finite() && *t > 0.0 && *t <= MAX_WAIT_SECONDS)
855 .ok_or_else(|| {
856 fail(
857 "invalid_arguments",
858 format!("timeout_seconds must be in (0, {MAX_WAIT_SECONDS}]"),
859 )
860 })?,
861 };
862 let start = Instant::now();
863 let mut reported: Option<u64> = None;
864 loop {
865 let job = server.get(&id, ctx)?;
866 if let Some(done) = job["completed_tasks"].as_u64()
867 && reported.is_none_or(|r| done > r)
868 {
869 let state = job["state"].as_str().unwrap_or_default();
870 server.progress(ctx, done, job["requested_tasks"].as_u64(), state);
871 reported = Some(done);
872 }
873 if terminal(&job["state"])
874 || !job["observed_state"].is_null()
875 || start.elapsed().as_secs_f64() >= timeout
876 {
877 return Ok(job);
878 }
879 pause(server, ctx, Duration::from_millis(500));
880 if ctx.stopped(server) {
881 return Err(Fail::Cancelled);
882 }
883 }
884}
885
886pub fn read_manifest(job: &Value) -> Result<Vec<u8>, ToolError> {
890 let id = job["job_id"].as_str().unwrap_or_default();
891 if !terminal(&job["state"]) {
892 let mut message = format!(
893 "job {id} is {}; wait_job until it ends",
894 job["state"].as_str().unwrap_or("unknown")
895 );
896 if let Some(observed) = job["observed_state"].as_str() {
897 message = format!("job {id} was observed {observed}; repair_job finalizes it");
898 }
899 return Err(ToolError {
900 code: "not_finished".into(),
901 message,
902 retryable: false,
903 });
904 }
905 let file = Path::new(job["directory"].as_str().unwrap_or_default()).join("run.json");
906 read_file(&file, MANIFEST_CAP).map_err(|e| {
909 let code = if e.contains("over the cap") {
910 "result_too_large"
911 } else {
912 "runner_error"
913 };
914 ToolError {
915 code: code.into(),
916 message: format!("{}: {e}", file.display()),
917 retryable: false,
918 }
919 })
920}
921
922#[derive(Deserialize)]
924struct ManifestView<'a> {
925 #[serde(default)]
926 status: Value,
927 #[serde(default)]
928 schema_version: Value,
929 #[serde(default)]
930 worker: Value,
931 #[serde(default)]
932 payload_schema: Value,
933 #[serde(default)]
934 completed_tasks: Value,
935 #[serde(default)]
936 requested_tasks: Value,
937 #[serde(default)]
938 elapsed_seconds: Value,
939 #[serde(default)]
940 work: Value,
941 #[serde(default)]
942 artifacts: Value,
943 #[serde(default)]
944 runner: RunnerView,
945 #[serde(borrow, default)]
946 results: Vec<&'a RawValue>,
947}
948
949#[derive(Default, Deserialize)]
950struct RunnerView {
951 #[serde(default)]
952 accounting_complete: Value,
953 #[serde(default)]
954 artifact_index: Value,
955}
956
957#[derive(Default, Deserialize)]
958struct RecordView {
959 #[serde(default)]
960 task_id: Value,
961 #[serde(default)]
962 outcome: OutcomeView,
963}
964
965#[derive(Default, Deserialize)]
966struct OutcomeView {
967 #[serde(default)]
968 claim: Value,
969 #[serde(default)]
970 termination: Value,
971 #[serde(default)]
972 feasible: Value,
973 #[serde(default)]
974 objective: Value,
975 #[serde(default)]
976 evidence: EvidenceView,
977 #[serde(default)]
978 objective_bounds: Value,
979 #[serde(default)]
980 imprecise: Value,
981}
982
983#[derive(Default, Deserialize)]
984struct EvidenceView {
985 #[serde(default)]
986 level: Value,
987 #[serde(default)]
988 refuted: Value,
989}
990
991fn view(bytes: &[u8]) -> Result<ManifestView<'_>, ToolError> {
992 serde_json::from_slice(bytes).map_err(|e| ToolError {
993 code: "runner_error".into(),
994 message: format!("unreadable result manifest: {e}"),
995 retryable: false,
996 })
997}
998
999pub fn summary(job: &Value, bytes: &[u8]) -> Result<Value, ToolError> {
1002 let manifest = view(bytes)?;
1003 let mut claims = BTreeMap::<String, u64>::new();
1004 let mut terminations = BTreeMap::<String, u64>::new();
1005 let mut tasks = vec![];
1006 for raw in &manifest.results {
1007 let r: RecordView = serde_json::from_str(raw.get()).unwrap_or_default();
1008 let o = &r.outcome;
1009 *claims
1010 .entry(o.claim.as_str().unwrap_or("unknown").into())
1011 .or_default() += 1;
1012 *terminations
1013 .entry(o.termination.as_str().unwrap_or("unknown").into())
1014 .or_default() += 1;
1015 if tasks.len() < SUMMARY_TASKS {
1016 let mut task = json!({
1017 "task_id": r.task_id,
1018 "claim": o.claim,
1019 "termination": o.termination,
1020 "feasible": o.feasible,
1021 "objective": o.objective,
1022 "evidence": o.evidence.level,
1023 });
1024 for (key, value) in [
1025 ("objective_bounds", &o.objective_bounds),
1026 ("imprecise", &o.imprecise),
1027 ("refuted", &o.evidence.refuted),
1028 ] {
1029 if !value.is_null() {
1030 task[key] = value.clone();
1031 }
1032 }
1033 tasks.push(task);
1034 }
1035 }
1036 let mut summary = json!({
1037 "job_id": job["job_id"],
1038 "state": job["state"],
1039 "status": manifest.status,
1040 "schema_version": manifest.schema_version,
1041 "worker": manifest.worker,
1042 "payload_schema": manifest.payload_schema,
1043 "completed_tasks": manifest.completed_tasks,
1044 "requested_tasks": manifest.requested_tasks,
1045 "elapsed_seconds": manifest.elapsed_seconds,
1046 "work": manifest.work,
1047 "accounting_complete": manifest.runner.accounting_complete,
1048 "claims": claims,
1049 "terminations": terminations,
1050 "tasks": tasks,
1051 "tasks_omitted": manifest.results.len().saturating_sub(SUMMARY_TASKS),
1052 "artifacts": manifest.artifacts,
1053 "directory": job["directory"],
1054 });
1055 if !manifest.runner.artifact_index.is_null() {
1056 summary["artifact_index"] = manifest.runner.artifact_index;
1057 }
1058 Ok(summary)
1059}
1060
1061fn get_result(server: &Server, args: &Value, ctx: &Ctx) -> Result<Value, Fail> {
1062 let id = job_id(args)?;
1063 let job = server.get(&id, ctx)?;
1064 let bytes = read_manifest(&job).map_err(Fail::Tool)?;
1065 let too_large = |size: usize| {
1066 fail(
1067 "result_too_large",
1068 format!(
1069 "the result manifest has {size} bytes, over the 1 MiB inline cap; pass tasks, or read {}/run.json",
1070 job["directory"].as_str().unwrap_or_default()
1071 ),
1072 )
1073 };
1074 if args["full"].as_bool() == Some(true) {
1075 if bytes.len() > 4 * FULL_CAP {
1077 return Err(too_large(bytes.len()));
1078 }
1079 let manifest: Value = serde_json::from_slice(&bytes)
1080 .map_err(|e| fail("runner_error", format!("unreadable result manifest: {e}")))?;
1081 let size = manifest.to_string().len();
1082 if size > FULL_CAP {
1083 return Err(too_large(size));
1084 }
1085 return Ok(manifest);
1086 }
1087 match &args["tasks"] {
1088 Value::Null => summary(&job, &bytes).map_err(Fail::Tool),
1089 Value::Array(ids) => {
1090 let wanted: Vec<u64> = ids.iter().filter_map(Value::as_u64).collect();
1091 if wanted.len() != ids.len() || wanted.len() > 100 {
1092 return Err(fail(
1093 "invalid_arguments",
1094 "tasks must be at most 100 non-negative integer task IDs",
1095 ));
1096 }
1097 let manifest = view(&bytes).map_err(Fail::Tool)?;
1098 let mut records = vec![];
1099 for raw in &manifest.results {
1100 #[derive(Deserialize)]
1101 struct Id {
1102 task_id: Option<u64>,
1103 }
1104 let selected = serde_json::from_str::<Id>(raw.get())
1105 .ok()
1106 .and_then(|r| r.task_id)
1107 .is_some_and(|t| wanted.contains(&t));
1108 if selected && let Ok(record) = serde_json::from_str::<Value>(raw.get()) {
1109 records.push(record);
1110 }
1111 }
1112 Ok(json!({"job_id":id,"state":job["state"],"tasks":records}))
1113 }
1114 _ => Err(fail("invalid_arguments", "tasks must be an array")),
1115 }
1116}
1117
1118fn get_artifact(server: &Server, args: &Value, ctx: &Ctx) -> Result<Value, Fail> {
1119 let id = job_id(args)?;
1120 let name = string(args, "name")?;
1121 let mut argv = vec!["jobs".to_string(), "artifact".into()];
1122 for (key, low, high) in [("offset", 0, u32::MAX as u64), ("limit", 1, 10_000)] {
1123 match &args[key] {
1124 Value::Null => {}
1125 v => {
1126 let n = v
1127 .as_u64()
1128 .filter(|n| (low..=high).contains(n))
1129 .ok_or_else(|| {
1130 fail(
1131 "invalid_arguments",
1132 format!("{key} must be an integer from {low} to {high}"),
1133 )
1134 })?;
1135 argv.push(format!("--{key}={n}"));
1136 }
1137 }
1138 }
1139 argv.extend(["--".into(), id, name]);
1140 let argv: Vec<&str> = argv.iter().map(String::as_str).collect();
1141 server.cli(&argv, QUICK, ctx)
1142}
1143
1144fn get_events(server: &Server, args: &Value, ctx: &Ctx) -> Result<Value, Fail> {
1145 let id = job_id(args)?;
1146 let limit = limit(args, 50)?;
1147 let events = server.cli(&["jobs", "events", "--", &id], QUICK, ctx)?;
1148 let events = events.as_array().cloned().unwrap_or_default();
1149 let skip = events.len().saturating_sub(limit);
1150 Ok(json!({"job_id":id,"total":events.len(),"events":events[skip..]}))
1151}
1152
1153fn list_jobs(server: &Server, args: &Value, ctx: &Ctx) -> Result<Value, Fail> {
1154 let limit = limit(args, 50)?;
1155 let active_only = args["active_only"].as_bool() == Some(true);
1156 let jobs = server.cli(&["jobs", "list"], SLOW, ctx)?;
1157 let mut jobs: Vec<Value> = jobs
1158 .as_array()
1159 .cloned()
1160 .unwrap_or_default()
1161 .into_iter()
1162 .filter(|j| !active_only || !terminal(&j["state"]))
1163 .map(|j| {
1164 let mut job = json!({"job_id":j["id"],"state":j["state"]});
1165 for key in [
1166 "observed_state",
1167 "error",
1168 "completed_tasks",
1169 "requested_tasks",
1170 "submitted_at",
1171 "finished_at",
1172 "cancel_requested",
1173 ] {
1174 if !j[key].is_null() {
1175 job[key] = j[key].clone();
1176 }
1177 }
1178 job
1179 })
1180 .collect();
1181 jobs.sort_by(|a, b| {
1182 let t = |j: &Value| j["submitted_at"].as_f64().unwrap_or(0.0);
1183 t(b).total_cmp(&t(a))
1184 });
1185 let total = jobs.len();
1186 jobs.truncate(limit);
1187 Ok(json!({"total":total,"jobs":jobs}))
1188}
1189
1190pub fn cancel(server: &Server, id: &str, now: bool) -> Result<Value, Fail> {
1191 let mut args = vec!["jobs", "cancel"];
1192 if now {
1193 args.push("--now");
1194 }
1195 args.extend(["--", id]);
1196 let mut job = server.cli_mutating(&args)?;
1197 job["job_id"] = json!(id);
1198 Ok(job)
1199}
1200
1201pub fn repair(server: &Server, id: &str) -> Result<Value, Fail> {
1202 let mut job = server.cli_mutating(&["jobs", "repair", "--", id])?;
1203 job["job_id"] = json!(id);
1204 Ok(job)
1205}
1206
1207#[cfg(test)]
1208mod tests {
1209 #[test]
1212 fn embedded_job_schema_matches_the_published_one() {
1213 let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
1214 let published =
1215 manifest.join("../../docs/job-api/schemas/optimization.job-0.1.schema.json");
1216 if let Ok(published) = std::fs::read_to_string(published) {
1217 assert_eq!(
1218 published,
1219 include_str!("../../schemas/optimization.job-0.1.schema.json"),
1220 "copy docs/job-api/schemas/optimization.job-0.1.schema.json to crates/optimization-runner/schemas/"
1221 );
1222 }
1223 }
1224}