Skip to main content

lean_ctx/tools/registered/
ctx_work_graph.rs

1// SPDX-License-Identifier: Apache-2.0
2use rmcp::ErrorData;
3use rmcp::model::Tool;
4use serde_json::{Map, Value, json};
5
6use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput, get_str};
7use crate::tool_defs::tool_def;
8
9pub struct CtxWorkGraphTool;
10
11impl McpTool for CtxWorkGraphTool {
12    fn name(&self) -> &'static str {
13        "ctx_work_graph"
14    }
15
16    fn tool_def(&self) -> Tool {
17        tool_def(
18            "ctx_work_graph",
19            "Free persistent project-scoped bounded local Work Graph for multi-agent execution. Actions: create|delegate|claim|execute|consume|complete|receipt|accept|fuse|attribution|value_report|cancel|get|observe|list. Observe returns compact state without context payloads or execution fences.",
20            json!({
21                "type": "object",
22                "properties": {
23                    "action": {"type":"string","enum":["create","delegate","claim","execute","consume","complete","receipt","accept","fuse","attribution","value_report","cancel","get","observe","list"]},
24                    "graph_id": {"type":"string","minLength":1,"maxLength":128},
25                    "if_revision": {"type":"string","pattern":"^[0-9a-f]{64}$","description":"For observe: return only unchanged=true and revision if state matches. Authorization is still enforced."},
26                    "node_id": {"type":"string","minLength":1,"maxLength":128},
27                    "parent_node_id": {"type":"string","minLength":1,"maxLength":128},
28                    "to_agent": {"type":"string","minLength":1,"maxLength":128},
29                    "capsule_ref": {"type":"string","minLength":1,"maxLength":4096},
30                    "outcome_ref": {"type":"string","minLength":1,"maxLength":4096},
31                    "tokens": {"type":"integer","minimum":0},
32                    "cost_micros": {"type":"integer","minimum":0}
33                    ,"max_concurrency": {"type":"integer","minimum":1,"maximum":16}
34                    ,"receipt_id": {"type":"string","minLength":1,"maxLength":128}
35                    ,"execution_fence": {"type":"string","pattern":"^fence:[0-9a-f]{64}$"}
36                    ,"outcome": {"type":"string","enum":["accepted","rejected","partial"]}
37                    ,"claims": {"type":"array","maxItems":64,"items":{"type":"object","properties":{"key":{"type":"string","minLength":1,"maxLength":128},"value":{"type":"string","maxLength":4096}},"required":["key","value"],"additionalProperties":false}}
38                    ,"accepted_nodes": {"type":"array","minItems":1,"maxItems":256,"items":{"type":"string","minLength":1,"maxLength":128}}
39                    ,"stop_reason": {"type":"string","enum":["manual_stop","stale","redundant","policy_denied","lease_lost","duplicate","low_value","execution_failed"]}
40                    ,"connector": {"type":"string","enum":["codex"]}
41                    ,"model": {"type":"string","minLength":1,"maxLength":128}
42                    ,"timeout_ms": {"type":"integer","minimum":1,"maximum":1800000}
43                    ,"max_attempts": {"type":"integer","minimum":1,"maximum":2}
44                    ,"path_claims": {"type":"array","maxItems":64,"items":{"type":"string","pattern":"^path:[^/\\\\](?:[^\\r\\n]*[^/\\\\])?$","maxLength":517}}
45                    ,"task_ref": {"type":"string","minLength":1,"maxLength":128}
46                    ,"policy_ref": {"type":"string","minLength":1,"maxLength":128}
47                    ,"expected_outcome_ref": {"type":"string","minLength":1,"maxLength":128}
48                },
49                "required": ["action"],
50                "additionalProperties": false
51            }),
52        )
53    }
54
55    fn handle(
56        &self,
57        args: &Map<String, Value>,
58        ctx: &ToolContext,
59    ) -> Result<ToolOutput, ErrorData> {
60        let action = get_str(args, "action")
61            .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
62        // Free local reference behavior has no billing dependency. Registration,
63        // project scope, ownership, bounded execution and policy still apply.
64        let graph_id = get_str(args, "graph_id").unwrap_or_default();
65        let agent_id = ctx
66            .agent_id
67            .as_ref()
68            .map(|agent| agent.blocking_read().clone())
69            .unwrap_or_default();
70        let changed = matches!(
71            action.as_str(),
72            "create"
73                | "delegate"
74                | "claim"
75                | "execute"
76                | "consume"
77                | "complete"
78                | "receipt"
79                | "accept"
80                | "cancel"
81        );
82        let result = crate::tools::ctx_work_graph::handle(crate::tools::ctx_work_graph::Request {
83            action: &action,
84            project_root: &ctx.project_root,
85            agent_id: agent_id.as_deref().unwrap_or_default(),
86            graph_id: &graph_id,
87            if_revision: get_str(args, "if_revision").as_deref(),
88            node_id: get_str(args, "node_id").as_deref(),
89            parent_node_id: get_str(args, "parent_node_id").as_deref(),
90            to_agent: get_str(args, "to_agent").as_deref(),
91            capsule_ref: get_str(args, "capsule_ref").as_deref(),
92            outcome_ref: get_str(args, "outcome_ref").as_deref(),
93            tokens: args.get("tokens").and_then(Value::as_u64),
94            cost_micros: args.get("cost_micros").and_then(Value::as_u64),
95            max_concurrency: args
96                .get("max_concurrency")
97                .and_then(Value::as_u64)
98                .and_then(|value| usize::try_from(value).ok()),
99            receipt_id: get_str(args, "receipt_id").as_deref(),
100            execution_fence: get_str(args, "execution_fence").as_deref(),
101            outcome: get_str(args, "outcome").as_deref(),
102            claims: args.get("claims"),
103            accepted_nodes: args.get("accepted_nodes"),
104            stop_reason: get_str(args, "stop_reason").as_deref(),
105            connector: get_str(args, "connector").as_deref(),
106            model: get_str(args, "model").as_deref(),
107            timeout_ms: args.get("timeout_ms").and_then(Value::as_u64),
108            max_attempts: args
109                .get("max_attempts")
110                .and_then(Value::as_u64)
111                .and_then(|value| u8::try_from(value).ok()),
112            path_claims: args.get("path_claims"),
113            task_ref: get_str(args, "task_ref").as_deref(),
114            policy_ref: get_str(args, "policy_ref").as_deref(),
115            expected_outcome_ref: get_str(args, "expected_outcome_ref").as_deref(),
116        })
117        .map_err(|error| ErrorData::invalid_params(error, None))?;
118        Ok(ToolOutput {
119            text: result,
120            original_tokens: 0,
121            saved_tokens: 0,
122            mode: Some(action),
123            path: None,
124            changed,
125            shell_outcome: None,
126            content_blocks: None,
127        })
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134    use base64::{Engine as _, engine::general_purpose::STANDARD};
135    use ed25519_dalek::{Signer as _, SigningKey};
136    use lean_ctx_protocol::{
137        EntitlementDeploymentV1, EntitlementEnvelopeV1, EntitlementKindV1, EntitlementPlanV1,
138        EntitlementSignerV1, Sha256Digest,
139    };
140    use sha2::{Digest as _, Sha256};
141
142    #[test]
143    fn work_graph_stays_free_after_entitlement_removal_and_preserves_security() {
144        let isolated = crate::core::data_dir::isolated_data_dir();
145        let cloud = isolated.path().join("cloud");
146        std::fs::create_dir_all(&cloud).unwrap();
147        let trust_path = isolated.path().join("entitlement-trust.json");
148        let credentials_path = cloud.join("credentials.json");
149        let cache_path = cloud.join("entitlement-v1.json");
150        let key = SigningKey::from_bytes(&[47; 32]);
151        let public_key = key.verifying_key().to_bytes();
152        let digest = crate::core::agent_identity::hex_encode(&Sha256::digest(public_key));
153        let now = std::time::SystemTime::now()
154            .duration_since(std::time::UNIX_EPOCH)
155            .unwrap()
156            .as_secs();
157        let mut envelope = EntitlementEnvelopeV1 {
158            schema_version: 1,
159            entitlement_id: "handler-entitlement".into(),
160            kind: EntitlementKindV1::OnlineSubscription,
161            account_id: Some("handler-account".into()),
162            plan: EntitlementPlanV1::Pro,
163            seats: 1,
164            capabilities: vec![crate::core::billing::PRO_LOCAL_WORK_GRAPH.into()],
165            issued_at: now - 10,
166            not_before: now - 10,
167            expires_at: now + 600,
168            grace_until: now + 1_200,
169            allowed_deployments: vec![EntitlementDeploymentV1::Hosted],
170            deployment_id: None,
171            org_id: None,
172            workspace_id: None,
173            signer: EntitlementSignerV1 {
174                algorithm: "ed25519".into(),
175                key_id: "handler-key".into(),
176                public_key_digest: Sha256Digest::new(format!("sha256:{digest}")).unwrap(),
177            },
178            signature: String::new(),
179        };
180        envelope.signature =
181            STANDARD.encode(key.sign(&envelope.signing_bytes().unwrap()).to_bytes());
182        std::fs::write(
183            &trust_path,
184            serde_json::to_vec(&json!({
185                "schema_version": 1,
186                "keys": [{
187                    "key_id": "handler-key",
188                    "public_key_base64": STANDARD.encode(public_key)
189                }],
190                "revoked_entitlement_ids": [],
191                "deployment": "hosted"
192            }))
193            .unwrap(),
194        )
195        .unwrap();
196        std::fs::write(
197            &credentials_path,
198            br#"{"api_key":"handler-secret","user_id":"handler-account","email":"handler@example.invalid"}"#,
199        )
200        .unwrap();
201        #[cfg(unix)]
202        std::fs::set_permissions(
203            &credentials_path,
204            std::os::unix::fs::PermissionsExt::from_mode(0o600),
205        )
206        .unwrap();
207        let envelope_bytes = envelope.canonical_bytes().unwrap();
208        std::fs::write(&cache_path, &envelope_bytes).unwrap();
209        let _guard = crate::cloud_client::install_test_signed_entitlement_paths(
210            trust_path,
211            credentials_path,
212            cache_path,
213            vec![("handler-key".into(), public_key)],
214        );
215        crate::cloud_client::accept_test_signed_entitlement("handler-account", &envelope_bytes);
216        let args = Map::from_iter([("action".into(), Value::String("list".into()))]);
217        let context = ToolContext {
218            project_root: isolated.path().to_string_lossy().into_owned(),
219            ..ToolContext::default()
220        };
221
222        let Err(error) = CtxWorkGraphTool.handle(&args, &context) else {
223            panic!("the dispatcher must enforce agent registration after the paid gate");
224        };
225        assert_eq!(
226            error.message,
227            "agent must be registered first via ctx_agent"
228        );
229
230        let mut registry = crate::core::agents::AgentRegistry::new();
231        let agent = registry
232            .register(
233                "codex",
234                Some("signed graph test"),
235                &context.project_root,
236                None,
237            )
238            .unwrap();
239        registry.save().unwrap();
240        let context = ToolContext {
241            agent_id: Some(std::sync::Arc::new(tokio::sync::RwLock::new(Some(agent)))),
242            ..context
243        };
244        let create = json!({
245            "action": "create", "graph_id": "paid-graph", "node_id": "root",
246            "capsule_ref": "capsule:root", "task_ref": "task:root",
247            "policy_ref": "policy:root", "expected_outcome_ref": "outcome:root",
248            "tokens": 100, "cost_micros": 50
249        });
250        let created = CtxWorkGraphTool
251            .handle(create.as_object().unwrap(), &context)
252            .unwrap();
253        assert!(created.changed);
254        let listed = CtxWorkGraphTool.handle(&args, &context).unwrap();
255        assert!(!listed.changed);
256        let listed: Value = serde_json::from_str(&listed.text).unwrap();
257        assert_eq!(listed["graph_ids"], json!(["paid-graph"]));
258        let get = json!({"action": "get", "graph_id": "paid-graph"});
259        let before = CtxWorkGraphTool
260            .handle(get.as_object().unwrap(), &context)
261            .unwrap();
262        let observe = json!({"action": "observe", "graph_id": "paid-graph"});
263        let observed = CtxWorkGraphTool
264            .handle(observe.as_object().unwrap(), &context)
265            .unwrap();
266        assert!(!observed.changed);
267        let observation: Value = serde_json::from_str(&observed.text).unwrap();
268        assert!(observation.get("nodes").is_some());
269        assert!(!observed.text.contains("capsule:root"));
270        let conditional = json!({
271            "action": "observe", "graph_id": "paid-graph",
272            "if_revision": observation["revision"]
273        });
274        let unchanged = CtxWorkGraphTool
275            .handle(conditional.as_object().unwrap(), &context)
276            .unwrap();
277        assert!(!unchanged.changed);
278        let unchanged: Value = serde_json::from_str(&unchanged.text).unwrap();
279        assert_eq!(unchanged["unchanged"], true);
280        assert!(unchanged.get("nodes").is_none());
281        let wrong_project = ToolContext {
282            project_root: isolated
283                .path()
284                .join("other-project")
285                .to_string_lossy()
286                .into_owned(),
287            agent_id: context.agent_id.clone(),
288            ..ToolContext::default()
289        };
290        assert!(
291            CtxWorkGraphTool
292                .handle(conditional.as_object().unwrap(), &wrong_project)
293                .is_err()
294        );
295        assert_eq!(
296            before.text,
297            CtxWorkGraphTool
298                .handle(get.as_object().unwrap(), &context)
299                .unwrap()
300                .text
301        );
302        let policy_dir = std::path::Path::new(&context.project_root).join(".lean-ctx");
303        std::fs::create_dir_all(&policy_dir).unwrap();
304        std::fs::write(policy_dir.join("policy.toml"),
305            "name = \"deny-execution\"\nversion = \"1.0.0\"\ndescription = \"test\"\n[context]\ndeny_tools = [\"ctx_work_graph\"]\n").unwrap();
306        let execute = json!({
307            "action": "execute", "graph_id": "paid-graph", "node_id": "root",
308            "connector": "codex"
309        });
310        let error = CtxWorkGraphTool
311            .handle(execute.as_object().unwrap(), &context)
312            .err()
313            .expect("project policy must deny execution even with a valid paid entitlement");
314        assert_eq!(error.message, "project policy denies Work Graph execution");
315        let after = CtxWorkGraphTool
316            .handle(get.as_object().unwrap(), &context)
317            .unwrap();
318        assert_eq!(
319            before.text, after.text,
320            "denial must not claim or mutate the graph"
321        );
322        std::fs::write(policy_dir.join("policy.toml"),
323            "name = \"model-ceiling\"\nversion = \"1.0.0\"\ndescription = \"test\"\n[routing]\nallowed_models = [\"claude-*\"]\nmodel_ceiling_groups = [[\"*-opus-*\"]]\n").unwrap();
324        for model in [None, Some(""), Some("gpt-5"), Some("claude-sonnet-5")] {
325            let mut request = execute.clone();
326            if let Some(model) = model {
327                request["model"] = json!(model);
328            }
329            let error = CtxWorkGraphTool
330                .handle(request.as_object().unwrap(), &context)
331                .err()
332                .expect("unproven or forbidden model must be denied before dispatch");
333            assert_eq!(
334                error.message,
335                "project policy denies Work Graph model selection"
336            );
337            let unchanged = CtxWorkGraphTool
338                .handle(get.as_object().unwrap(), &context)
339                .unwrap();
340            assert_eq!(before.text, unchanged.text);
341        }
342        drop(_guard);
343        let _denied = crate::cloud_client::install_test_signed_entitlement_paths(
344            isolated.path().join("missing-trust.json"),
345            cloud.join("missing-credentials.json"),
346            cloud.join("missing-entitlement.json"),
347            Vec::new(),
348        );
349        let mut free_create = create.clone();
350        free_create["graph_id"] = json!("free-graph");
351        assert!(
352            CtxWorkGraphTool
353                .handle(free_create.as_object().unwrap(), &context)
354                .expect("registered agents can create local graphs without a paid account")
355                .changed
356        );
357        assert!(
358            CtxWorkGraphTool
359                .handle(conditional.as_object().unwrap(), &context)
360                .is_ok()
361        );
362        let cancel = json!({
363            "action": "cancel", "graph_id": "paid-graph", "node_id": "root",
364            "stop_reason": "manual_stop"
365        });
366        let unregistered = ToolContext {
367            project_root: context.project_root.clone(),
368            ..ToolContext::default()
369        };
370        let error = CtxWorkGraphTool
371            .handle(cancel.as_object().unwrap(), &unregistered)
372            .err()
373            .expect("cancel still requires registration");
374        assert_eq!(
375            error.message,
376            "agent must be registered first via ctx_agent"
377        );
378        let other_project = ToolContext {
379            project_root: isolated
380                .path()
381                .join("other-project")
382                .to_string_lossy()
383                .into_owned(),
384            agent_id: context.agent_id.clone(),
385            ..ToolContext::default()
386        };
387        let error = CtxWorkGraphTool
388            .handle(cancel.as_object().unwrap(), &other_project)
389            .err()
390            .expect("cancel must preserve project isolation");
391        assert!(
392            error
393                .message
394                .contains("agent is not active in this project")
395        );
396        assert!(
397            CtxWorkGraphTool
398                .handle(cancel.as_object().unwrap(), &context)
399                .unwrap()
400                .changed
401        );
402    }
403
404    #[test]
405    fn forged_legacy_plan_files_never_bypass_agent_registration() {
406        let isolated = crate::core::data_dir::isolated_data_dir();
407        let cloud = isolated.path().join("cloud");
408        std::fs::create_dir_all(&cloud).unwrap();
409        std::fs::write(cloud.join("plan.txt"), "enterprise").unwrap();
410        std::fs::write(
411            cloud.join("plan.json"),
412            br#"{"plan":"enterprise","verified_at":9007199254740991}"#,
413        )
414        .unwrap();
415        let _guard = crate::cloud_client::install_test_signed_entitlement_paths(
416            isolated.path().join("missing-trust.json"),
417            cloud.join("missing-credentials.json"),
418            cloud.join("missing-entitlement.json"),
419            Vec::new(),
420        );
421        let args = Map::from_iter([("action".into(), Value::String("list".into()))]);
422        let context = ToolContext {
423            project_root: isolated.path().to_string_lossy().into_owned(),
424            ..ToolContext::default()
425        };
426
427        let Err(error) = CtxWorkGraphTool.handle(&args, &context) else {
428            panic!("forged plan files must not bypass agent registration");
429        };
430
431        assert_eq!(
432            error.message,
433            "agent must be registered first via ctx_agent"
434        );
435    }
436}