Skip to main content

lean_ctx/tools/registered/
ctx_agent.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_bool, get_str};
7use crate::tool_defs::tool_def;
8
9pub struct CtxAgentTool;
10
11impl McpTool for CtxAgentTool {
12    fn name(&self) -> &'static str {
13        "ctx_agent"
14    }
15
16    fn tool_def(&self) -> Tool {
17        tool_def(
18            "ctx_agent",
19            "Local multi-agent coordination helper for explicit opt-in sessions. It is not a hosted workflow service.\n\
20             Active presence uses a bounded lease; read or status=active renews it.\n\
21             Actions: register, list, post, read, status, info, handoff, sync, poll_events, export,\n\
22              claim/release, lease_acquire/lease_renew/lease_release, brief/return, diary/recall_diary/diaries,\n\
23              share_knowledge/receive_knowledge, control_status. Directed events require an agent filter when read.\n\
24             Leases (message=path or symbol:<name>; renew/release take category=lease_ref) are machine-wide:\n\
25              every lean-ctx process sharing the data dir sees the same holder.",
26            json!({
27                "type": "object",
28                "properties": {
29                    "action": {
30                        "type": "string",
31                        "enum": crate::tools::ctx_agent::ACTIONS,
32                        "description": crate::tools::ctx_agent::ACTIONS.join("|")
33                    },
34                    "agent_type": {
35                        "type": "string",
36                        "description": "cursor|claude|codex|gemini|crush|subagent"
37                    },
38                    "role": {
39                        "type": "string",
40                        "description": "dev|review|test|plan"
41                    },
42                    "durable_identity_id": {
43                        "type": "string",
44                        "description": "Explicit durable identity ID to bind on register; never inferred"
45                    },
46                    "message": {
47                        "type": "string",
48                        "description": "Post text or status detail"
49                    },
50                    "category": {
51                        "type": "string",
52                        "description": "finding|warning|request|status"
53                    },
54                    "to_agent": {
55                        "type": "string",
56                        "description": "Target agent ID"
57                    },
58                    "status": {
59                        "type": "string",
60                        "enum": ["active", "idle", "finished"],
61                        "description": "active|idle|finished"
62                    },
63                    "privacy": {
64                        "type": "string",
65                        "description": "public|team|private; poll_events accepts comma-separated event kinds"
66                    },
67                    "priority": {
68                        "type": "string",
69                        "description": "low|normal|high|critical; brief also accepts a numeric token budget"
70                    },
71                    "ttl_hours": {
72                        "type": "integer",
73                        "minimum": 0,
74                        "description": "message TTL in hours; lease_acquire/lease_renew: 0 = 10 min (default), 1 = 1 h"
75                    },
76                    "format": {
77                        "type": "string",
78                        "enum": ["json", "text"],
79                        "description": "export output format"
80                    },
81                    "write": {
82                        "type": "boolean",
83                        "description": "export a proof snapshot under the project proofs directory"
84                    },
85                    "filename": {
86                        "type": "string",
87                        "description": "plain proof filename for export (no directories)"
88                    }
89                },
90                "allOf": [
91                    { "if": { "properties": { "action": { "const": "post" } }, "required": ["action"] }, "then": { "required": ["action", "message"] } },
92                    { "if": { "properties": { "action": { "const": "status" } }, "required": ["action"] }, "then": { "required": ["action", "status"] } },
93                    { "if": { "properties": { "action": { "const": "handoff" } }, "required": ["action"] }, "then": { "required": ["action", "to_agent"] } },
94                    { "if": { "properties": { "action": { "const": "claim" } }, "required": ["action"] }, "then": { "required": ["action", "message"] } },
95                    { "if": { "properties": { "action": { "const": "release" } }, "required": ["action"] }, "then": { "required": ["action", "message"] } },
96                    { "if": { "properties": { "action": { "const": "brief" } }, "required": ["action"] }, "then": { "required": ["action", "message"] } },
97                    { "if": { "properties": { "action": { "const": "return" } }, "required": ["action"] }, "then": { "required": ["action", "message"] } },
98                    { "if": { "properties": { "action": { "const": "diary" } }, "required": ["action"] }, "then": { "required": ["action", "message"] } },
99                    { "if": { "properties": { "action": { "const": "share_knowledge" } }, "required": ["action"] }, "then": { "required": ["action", "message"] } },
100                    { "if": { "properties": { "action": { "const": "lease_acquire" } }, "required": ["action"] }, "then": { "required": ["action", "message"] } },
101                    { "if": { "properties": { "action": { "const": "lease_renew" } }, "required": ["action"] }, "then": { "required": ["action", "message", "category"] } },
102                    { "if": { "properties": { "action": { "const": "lease_release" } }, "required": ["action"] }, "then": { "required": ["action", "message", "category"] } }
103                ],
104                "required": ["action"]
105            }),
106        )
107    }
108
109    fn handle(
110        &self,
111        args: &Map<String, Value>,
112        ctx: &ToolContext,
113    ) -> Result<ToolOutput, ErrorData> {
114        let action = get_str(args, "action")
115            .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
116        let agent_type = get_str(args, "agent_type");
117        let role = get_str(args, "role");
118        let durable_identity_id = if action == "register" {
119            get_str(args, "durable_identity_id")
120        } else {
121            None
122        };
123        let message = get_str(args, "message");
124        let category = get_str(args, "category");
125        let to_agent = get_str(args, "to_agent");
126        let status = get_str(args, "status");
127        let privacy = get_str(args, "privacy");
128        let priority = get_str(args, "priority");
129        let ttl_hours: Option<u64> = args.get("ttl_hours").and_then(serde_json::Value::as_u64);
130        let format = get_str(args, "format");
131        let write = get_bool(args, "write").unwrap_or(false);
132        let filename = get_str(args, "filename");
133
134        let project_root = ctx.project_root.clone();
135
136        let agent_id_handle = ctx.agent_id.as_ref();
137        let current_agent_id = agent_id_handle
138            .map(|a| a.blocking_read().clone())
139            .unwrap_or_default();
140
141        let result = crate::tools::ctx_agent::handle(
142            &action,
143            agent_type.as_deref(),
144            role.as_deref(),
145            durable_identity_id.as_deref(),
146            &project_root,
147            current_agent_id.as_deref(),
148            message.as_deref(),
149            category.as_deref(),
150            to_agent.as_deref(),
151            status.as_deref(),
152            privacy.as_deref(),
153            priority.as_deref(),
154            ttl_hours,
155            format.as_deref(),
156            write,
157            filename.as_deref(),
158        );
159
160        if action == "register" {
161            if let Some(id) = result.split(':').nth(1) {
162                let id = id.split_whitespace().next().unwrap_or("").to_string();
163                if !id.is_empty()
164                    && let Some(handle) = agent_id_handle
165                {
166                    let mut guard = handle.blocking_write();
167                    *guard = Some(id);
168                }
169            }
170
171            let agent_role =
172                crate::core::agents::AgentRole::from_str_loose(role.as_deref().unwrap_or("coder"));
173            let depth = crate::core::agents::ContextDepthConfig::for_role(agent_role);
174            let depth_hint = format!(
175                "\n[context] role={:?} preferred_mode={} max_full={} max_sig={} budget_ratio={:.0}%",
176                agent_role,
177                depth.preferred_mode,
178                depth.max_files_full,
179                depth.max_files_signatures,
180                depth.context_budget_ratio * 100.0,
181            );
182            return Ok(ToolOutput {
183                text: format!("{result}{depth_hint}"),
184                original_tokens: 0,
185                saved_tokens: 0,
186                mode: Some(action),
187                path: None,
188                changed: false,
189                shell_outcome: None,
190                content_blocks: None,
191            });
192        }
193
194        Ok(ToolOutput {
195            text: result,
196            original_tokens: 0,
197            saved_tokens: 0,
198            mode: Some(action),
199            path: None,
200            changed: false,
201            shell_outcome: None,
202            content_blocks: None,
203        })
204    }
205}
206
207#[cfg(test)]
208mod schema_tests {
209    use super::*;
210    use crate::server::tool_trait::McpTool;
211    use crate::tools::ctx_agent::ACTIONS;
212
213    #[test]
214    fn schema_advertises_optional_durable_identity_binding() {
215        let schema = serde_json::to_string(&CtxAgentTool.tool_def()).expect("tool schema");
216        assert!(schema.contains("durable_identity_id"));
217        assert!(schema.contains("Explicit durable identity ID"));
218    }
219
220    #[test]
221    fn schema_exposes_each_bus_action_without_combined_enum_values() {
222        let schema = serde_json::to_value(CtxAgentTool.tool_def()).expect("tool schema");
223        let action_enum = schema["inputSchema"]["properties"]["action"]["enum"]
224            .as_array()
225            .expect("action enum");
226        for action in [
227            "poll_events",
228            "export",
229            "control_status",
230            "lease_acquire",
231            "lease_renew",
232            "lease_release",
233        ] {
234            assert!(
235                action_enum.iter().any(|value| value == action),
236                "missing action {action}"
237            );
238        }
239        assert!(
240            !action_enum
241                .iter()
242                .any(|value| value.as_str().is_some_and(|value| value.contains('|')))
243        );
244        assert!(schema["inputSchema"]["properties"]["privacy"].is_object());
245        assert!(schema["inputSchema"]["properties"]["ttl_hours"].is_object());
246    }
247
248    /// #1913: a merged `a|b|c` entry advertised an action no client could send.
249    #[test]
250    fn action_enum_lists_each_dispatched_action_once() {
251        let tool = CtxAgentTool.tool_def();
252        let schema = serde_json::Value::Object((*tool.input_schema).clone());
253        let listed: Vec<&str> = schema["properties"]["action"]["enum"]
254            .as_array()
255            .expect("action enum")
256            .iter()
257            .map(|v| v.as_str().expect("string entry"))
258            .collect();
259        assert_eq!(listed, ACTIONS);
260        let mut unique = listed.clone();
261        unique.sort_unstable();
262        unique.dedup();
263        assert_eq!(unique.len(), listed.len(), "no duplicate entries");
264        for action in &listed {
265            assert!(
266                action.bytes().all(|b| b.is_ascii_lowercase() || b == b'_'),
267                "enum entry {action:?} must be a single action name"
268            );
269            let arm = format!("\"{action}\"");
270            assert!(
271                DISPATCH_SOURCE.lines().any(|line| {
272                    let line = line.trim_start();
273                    line.starts_with(&arm) && line.contains("=>")
274                }),
275                "advertised action {action:?} is not dispatched"
276            );
277        }
278    }
279
280    const DISPATCH_SOURCE: &str = include_str!("../ctx_agent.rs");
281}