Skip to main content

agentmux_mcp/tools/
schedule_tool.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Schedule: one tool for prompts injected on a schedule, with an `action`
5//! (docs/specs/SPEC_MUXAPI_TOOL_CONSOLIDATION_2026_10_15.md §4.2, slice S3). It
6//! replaces the five Cron* tools and the three Loop* tools: `create` with
7//! `cron` is a persistent job (cron.rs), with `every` a loop that lives as long
8//! as this agent's session (loops.rs). Their handlers run unchanged.
9
10use super::*;
11
12pub(super) const ACTIONS: &[&str] = &["create", "list", "pause", "resume", "delete", "history", "run_now", "report"];
13
14/// Loops are named `loop-<n>` (loops.rs); everything else is a cron job id.
15fn is_loop_id(id: &str) -> bool {
16    id.starts_with("loop-")
17}
18
19/// `create` parameters only a cron job takes, and only a loop takes.
20const CRON_ONLY: &[&str] = &["name", "max_fires", "max_age_secs", "catch_up", "tz", "policy", "template", "params"];
21const LOOP_ONLY: &[&str] = &["max_iterations", "immediate"];
22
23/// A parameter of the other kind is an error, not dropped: `max_fires` on a
24/// loop would otherwise leave it running without limit.
25fn refuse_other_kinds(args: &serde_json::Map<String, Value>, kind: &str, others: &[&str]) -> Result<()> {
26    let given: Vec<&str> = others.iter().copied().filter(|k| args.contains_key(*k)).collect();
27    if !given.is_empty() {
28        anyhow::bail!(
29            "Schedule create with {kind} doesn't take {}: {} to {}",
30            given.join(", "),
31            if given.len() == 1 { "it belongs" } else { "they belong" },
32            if kind == "cron" { "a loop (every)" } else { "a cron job (cron)" }
33        );
34    }
35    Ok(())
36}
37
38/// The handler for an action, and its arguments as that handler takes them.
39pub(super) fn route(arguments: &Value) -> Result<(&'static str, Value)> {
40    let action = arguments.get("action").and_then(|v| v.as_str()).unwrap_or("");
41    let mut args = match arguments {
42        Value::Object(m) => m.clone(),
43        _ => serde_json::Map::new(),
44    };
45    args.remove("action");
46    let id = args.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();
47    let rename = |args: &mut serde_json::Map<String, Value>, ours: &str, theirs: &str| {
48        if let Some(v) = args.remove(ours) {
49            args.insert(theirs.to_string(), v);
50        }
51    };
52    let tool = match action {
53        "create" => match (args.contains_key("cron"), args.contains_key("every")) {
54            (true, false) => {
55                refuse_other_kinds(&args, "cron", LOOP_ONLY)?;
56                rename(&mut args, "cron", "expression");
57                "CronCreate"
58            }
59            (false, true) => {
60                refuse_other_kinds(&args, "every", CRON_ONLY)?;
61                rename(&mut args, "every", "interval");
62                "Loop"
63            }
64            _ => anyhow::bail!(
65                "Schedule create needs exactly one of cron (a persistent job on a cron schedule, UTC unless tz says otherwise) or every \
66                 (a loop for as long as this session lasts)"
67            ),
68        },
69        "list" => "list",
70        "pause" | "resume" if is_loop_id(&id) => {
71            anyhow::bail!("Schedule: a loop can't be paused; delete it and create it again")
72        }
73        "pause" => "CronPause",
74        "resume" => "CronResume",
75        "delete" if is_loop_id(&id) => {
76            rename(&mut args, "id", "loop_id");
77            "LoopStop"
78        }
79        "delete" => "CronDelete",
80        // A loop writes no runs (jobs spec §3.2): it belongs to one session.
81        "history" | "run_now" if is_loop_id(&id) => {
82            anyhow::bail!("Schedule: a loop keeps no run history and can't be run now; only a cron job can")
83        }
84        "history" => "CronHistory",
85        "run_now" => "CronRunNow",
86        "report" => "CronReport",
87        "" => anyhow::bail!("Schedule: missing required parameter: action (one of {})", ACTIONS.join(", ")),
88        other => anyhow::bail!("Schedule: unknown action {other:?}: use one of {}", ACTIONS.join(", ")),
89    };
90    Ok((tool, Value::Object(args)))
91}
92
93pub(super) async fn call(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
94    match name {
95        "Schedule" => {
96            let (tool, args) = route(arguments)?;
97            match tool {
98                // Both kinds in one answer: cron jobs, then this session's loops.
99                // The loops live in this process, so srv being unreachable
100                // doesn't hide them.
101                "list" => {
102                    let jobs = cron::call("CronList", &args, cx)
103                        .await
104                        .unwrap_or_else(|e| format!("unavailable: {e:#}"));
105                    let loops = loops::call("LoopList", &args, cx).await?;
106                    Ok(format!("cron jobs:\n{jobs}\n\nloops (this session):\n{loops}"))
107                }
108                "Loop" | "LoopStop" => loops::call(tool, &args, cx).await,
109                _ => cron::call(tool, &args, cx).await,
110            }
111        }
112        _ => Err(not_in_family()),
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119
120    #[test]
121    fn a_parameter_of_the_other_kind_is_refused() {
122        let e = route(&json!({ "action": "create", "every": "5m", "prompt": "p", "max_fires": 3 })).unwrap_err().to_string();
123        assert_eq!(e, "Schedule create with every doesn't take max_fires: it belongs to a cron job (cron)");
124        let e = route(&json!({ "action": "create", "cron": "* * * * *", "prompt": "p", "to": "a", "immediate": true, "max_iterations": 2 }))
125            .unwrap_err()
126            .to_string();
127        assert_eq!(e, "Schedule create with cron doesn't take max_iterations, immediate: they belong to a loop (every)");
128    }
129
130    #[test]
131    fn create_is_a_cron_job_or_a_loop() {
132        let (tool, args) = route(&json!({ "action": "create", "cron": "0 9 * * 1-5", "name": "n", "prompt": "p", "to": "a" })).unwrap();
133        assert_eq!(tool, "CronCreate");
134        assert_eq!(args["expression"], "0 9 * * 1-5");
135        let (tool, args) = route(&json!({ "action": "create", "every": "5m", "prompt": "p" })).unwrap();
136        assert_eq!(tool, "Loop");
137        assert_eq!(args["interval"], "5m");
138        assert!(route(&json!({ "action": "create", "prompt": "p" })).is_err());
139        assert!(route(&json!({ "action": "create", "cron": "x", "every": "5m" })).is_err());
140    }
141
142    #[test]
143    fn an_id_says_whether_it_is_a_loop_or_a_cron_job() {
144        let (tool, args) = route(&json!({ "action": "delete", "id": "loop-3" })).unwrap();
145        assert_eq!((tool, args["loop_id"].as_str()), ("LoopStop", Some("loop-3")));
146        assert_eq!(route(&json!({ "action": "delete", "id": "c0ffee" })).unwrap().0, "CronDelete");
147        assert_eq!(route(&json!({ "action": "pause", "id": "c0ffee" })).unwrap().0, "CronPause");
148        assert!(route(&json!({ "action": "pause", "id": "loop-1" })).unwrap_err().to_string().contains("can't be paused"));
149        assert!(route(&json!({ "action": "stop" })).unwrap_err().to_string().contains("unknown action"));
150    }
151
152    #[test]
153    fn the_run_actions_go_to_the_cron_handlers_and_refuse_a_loop() {
154        assert_eq!(route(&json!({ "action": "history", "id": "c0ffee" })).unwrap().0, "CronHistory");
155        assert_eq!(route(&json!({ "action": "run_now", "id": "c0ffee" })).unwrap().0, "CronRunNow");
156        let (tool, args) = route(&json!({ "action": "report", "run_id": "r1", "outcome": "ok" })).unwrap();
157        assert_eq!((tool, args["run_id"].as_str()), ("CronReport", Some("r1")));
158        for action in ["history", "run_now"] {
159            let e = route(&json!({ "action": action, "id": "loop-2" })).unwrap_err().to_string();
160            assert!(e.contains("only a cron job"), "{action}: {e}");
161        }
162        let e = route(&json!({ "action": "create", "every": "5m", "prompt": "p", "catch_up": "latest" })).unwrap_err().to_string();
163        assert!(e.contains("catch_up"), "{e}");
164    }
165
166    #[test]
167    fn every_action_is_in_the_schema() {
168        let schema: Value = serde_json::from_str(crate::tool_schemas::SCHEDULE_TOOL).unwrap();
169        let mut listed: Vec<&str> = schema["inputSchema"]["properties"]["action"]["enum"]
170            .as_array()
171            .unwrap()
172            .iter()
173            .filter_map(|v| v.as_str())
174            .collect();
175        let mut want = ACTIONS.to_vec();
176        listed.sort();
177        want.sort();
178        assert_eq!(listed, want);
179    }
180}