1use anyhow::{Context as _, Result};
2use cli_clipboard::{ClipboardContext, ClipboardProvider};
3use dialoguer::{Input, Select};
4use indicatif::{ProgressBar, ProgressStyle};
5use notify_rust::Notification;
6use serde_json::{json, Value};
7
8pub struct InputModule;
9
10impl Default for InputModule {
11 fn default() -> Self {
12 Self::new()
13 }
14}
15
16impl InputModule {
17 pub fn new() -> Self {
18 Self
19 }
20
21 pub fn get_tools(&self) -> Vec<Value> {
22 vec![
23 json!({
24 "name": "input_notify",
25 "description": "Send notifications (terminal and desktop)",
26 "inputSchema": {
27 "type": "object",
28 "properties": {
29 "title": {
30 "type": "string",
31 "description": "Notification title"
32 },
33 "message": {
34 "type": "string",
35 "description": "Notification message"
36 },
37 "type": {
38 "type": "string",
39 "enum": ["terminal", "desktop", "both"],
40 "description": "Notification type (default: both)"
41 },
42 "urgency": {
43 "type": "string",
44 "enum": ["low", "normal", "critical"],
45 "description": "Desktop notification urgency (default: normal)"
46 },
47 "timeout": {
48 "type": "number",
49 "description": "Notification timeout in milliseconds (desktop only)"
50 }
51 },
52 "required": ["message"]
53 }
54 }),
55 json!({
56 "name": "input_prompt",
57 "description": "Interactive user prompts (supports MCP and terminal)",
58 "inputSchema": {
59 "type": "object",
60 "properties": {
61 "prompt": {
62 "type": "string",
63 "description": "Prompt message"
64 },
65 "default": {
66 "type": "string",
67 "description": "Default value"
68 },
69 "mode": {
70 "type": "string",
71 "enum": ["terminal", "mcp"],
72 "description": "Input mode (default: terminal)"
73 }
74 },
75 "required": ["prompt"]
76 }
77 }),
78 json!({
79 "name": "input_select",
80 "description": "Selection menus (supports MCP and terminal)",
81 "inputSchema": {
82 "type": "object",
83 "properties": {
84 "prompt": {
85 "type": "string",
86 "description": "Prompt message"
87 },
88 "options": {
89 "type": "array",
90 "items": {
91 "type": "string"
92 },
93 "description": "List of options to choose from"
94 },
95 "default": {
96 "type": "number",
97 "description": "Default option index"
98 },
99 "mode": {
100 "type": "string",
101 "enum": ["terminal", "mcp"],
102 "description": "Input mode (default: terminal)"
103 }
104 },
105 "required": ["prompt", "options"]
106 }
107 }),
108 json!({
109 "name": "input_progress",
110 "description": "Display progress indicators",
111 "inputSchema": {
112 "type": "object",
113 "properties": {
114 "action": {
115 "type": "string",
116 "enum": ["start", "update", "finish"],
117 "description": "Progress action"
118 },
119 "id": {
120 "type": "string",
121 "description": "Progress bar identifier"
122 },
123 "total": {
124 "type": "number",
125 "description": "Total steps (for start)"
126 },
127 "current": {
128 "type": "number",
129 "description": "Current step (for update)"
130 },
131 "message": {
132 "type": "string",
133 "description": "Progress message"
134 }
135 },
136 "required": ["action"]
137 }
138 }),
139 json!({
140 "name": "input_clipboard_read",
141 "description": "Read from clipboard",
142 "inputSchema": {
143 "type": "object",
144 "properties": {}
145 }
146 }),
147 json!({
148 "name": "input_clipboard_write",
149 "description": "Write to clipboard",
150 "inputSchema": {
151 "type": "object",
152 "properties": {
153 "content": {
154 "type": "string",
155 "description": "Content to write to clipboard"
156 }
157 },
158 "required": ["content"]
159 }
160 }),
161 ]
162 }
163
164 pub async fn notify(&self, args: Value) -> Result<Value> {
165 let title = args["title"].as_str().unwrap_or("Poly MCP");
166 let message = args["message"]
167 .as_str()
168 .context("Missing 'message' parameter")?;
169 let notification_type = args["type"].as_str().unwrap_or("both");
170 let urgency = args["urgency"].as_str().unwrap_or("normal");
171 let timeout = args["timeout"].as_u64().map(|t| t as i32);
172
173 let mut results = json!({
174 "title": title,
175 "message": message
176 });
177
178 if notification_type == "terminal" || notification_type == "both" {
180 let border_len = title.len().max(message.len());
181 let border = "─".repeat(border_len);
182 println!("\n┌─ {} ─┐", border);
183 println!("│ {} │", title);
184 println!("├─{}─┤", border);
185 println!("│ {} │", message);
186 println!("└─{}─┘\n", border);
187
188 results["terminal"] = json!(true);
189 }
190
191 if notification_type == "desktop" || notification_type == "both" {
193 let mut notification = Notification::new();
194 notification.summary(title);
195 notification.body(message);
196
197 #[cfg(target_os = "linux")]
199 match urgency {
200 "low" => {
201 notification.urgency(notify_rust::Urgency::Low);
202 }
203 "critical" => {
204 notification.urgency(notify_rust::Urgency::Critical);
205 }
206 _ => {
207 notification.urgency(notify_rust::Urgency::Normal);
208 }
209 }
210 #[cfg(not(target_os = "linux"))]
211 let _ = urgency; if let Some(t) = timeout {
214 notification.timeout(t);
215 }
216
217 match notification.show() {
218 Ok(_) => {
219 results["desktop"] = json!(true);
220 }
221 Err(e) => {
222 results["desktop"] = json!(false);
223 results["desktop_error"] = json!(e.to_string());
224 }
225 }
226 }
227
228 Ok(results)
229 }
230
231 pub async fn prompt_user(&self, args: Value) -> Result<Value> {
232 let prompt = args["prompt"]
233 .as_str()
234 .context("Missing 'prompt' parameter")?;
235 let default_value = args["default"].as_str();
236 let mode = args["mode"].as_str().unwrap_or("terminal");
237
238 match mode {
239 "terminal" => {
240 let input = Input::<String>::new().with_prompt(prompt);
241
242 let input = if let Some(default) = default_value {
243 input.default(default.to_string())
244 } else {
245 input
246 };
247
248 let result = input.interact_text()?;
249
250 Ok(json!({
251 "prompt": prompt,
252 "response": result,
253 "mode": "terminal"
254 }))
255 }
256 "mcp" => {
257 Ok(json!({
260 "prompt": prompt,
261 "mode": "mcp",
262 "message": "MCP sampling would be triggered here",
263 "default": default_value
264 }))
265 }
266 _ => Err(anyhow::anyhow!("Unknown mode: {}", mode)),
267 }
268 }
269
270 pub async fn select(&self, args: Value) -> Result<Value> {
271 let prompt = args["prompt"]
272 .as_str()
273 .context("Missing 'prompt' parameter")?;
274 let options = args["options"]
275 .as_array()
276 .context("Missing 'options' parameter")?;
277 let default_idx = args["default"].as_u64().map(|i| i as usize);
278 let mode = args["mode"].as_str().unwrap_or("terminal");
279
280 let option_strs: Vec<String> = options
281 .iter()
282 .filter_map(|v| v.as_str().map(|s| s.to_string()))
283 .collect();
284
285 if option_strs.is_empty() {
286 return Err(anyhow::anyhow!("No valid options provided"));
287 }
288
289 match mode {
290 "terminal" => {
291 let select = Select::new().with_prompt(prompt).items(&option_strs);
292
293 let select = if let Some(idx) = default_idx {
294 select.default(idx)
295 } else {
296 select
297 };
298
299 let selection_idx = select.interact()?;
300 let selected = &option_strs[selection_idx];
301
302 Ok(json!({
303 "prompt": prompt,
304 "selected": selected,
305 "index": selection_idx,
306 "mode": "terminal"
307 }))
308 }
309 "mcp" => {
310 Ok(json!({
312 "prompt": prompt,
313 "options": option_strs,
314 "mode": "mcp",
315 "message": "MCP sampling would be triggered here",
316 "default": default_idx
317 }))
318 }
319 _ => Err(anyhow::anyhow!("Unknown mode: {}", mode)),
320 }
321 }
322
323 pub async fn progress(&self, args: Value) -> Result<Value> {
324 let action = args["action"]
325 .as_str()
326 .context("Missing 'action' parameter")?;
327 let id = args["id"].as_str().unwrap_or("default");
328
329 match action {
330 "start" => {
331 let total = args["total"]
332 .as_u64()
333 .context("Missing 'total' parameter for start action")?;
334 let message = args["message"].as_str().unwrap_or("Processing...");
335
336 let pb = ProgressBar::new(total);
337 pb.set_style(
338 ProgressStyle::default_bar()
339 .template("{msg} [{bar:40.cyan/blue}] {pos}/{len} ({eta})")
340 .unwrap()
341 .progress_chars("#>-"),
342 );
343 pb.set_message(message.to_string());
344
345 pb.finish_with_message("Started");
348
349 Ok(json!({
350 "action": "start",
351 "id": id,
352 "total": total,
353 "message": message
354 }))
355 }
356 "update" => {
357 let current = args["current"]
358 .as_u64()
359 .context("Missing 'current' parameter for update action")?;
360 let message = args["message"].as_str();
361
362 Ok(json!({
364 "action": "update",
365 "id": id,
366 "current": current,
367 "message": message
368 }))
369 }
370 "finish" => {
371 let message = args["message"].as_str().unwrap_or("Done!");
372
373 Ok(json!({
375 "action": "finish",
376 "id": id,
377 "message": message
378 }))
379 }
380 _ => Err(anyhow::anyhow!("Unknown action: {}", action)),
381 }
382 }
383
384 pub async fn clipboard_read(&self, _args: Value) -> Result<Value> {
385 let mut ctx = ClipboardContext::new()
386 .map_err(|e| anyhow::anyhow!("Failed to access clipboard: {}", e))?;
387
388 let content = ctx
389 .get_contents()
390 .map_err(|e| anyhow::anyhow!("Failed to read clipboard: {}", e))?;
391
392 Ok(json!({
393 "content": content,
394 "length": content.len()
395 }))
396 }
397
398 pub async fn clipboard_write(&self, args: Value) -> Result<Value> {
399 let content = args["content"]
400 .as_str()
401 .context("Missing 'content' parameter")?;
402
403 let mut ctx = ClipboardContext::new()
404 .map_err(|e| anyhow::anyhow!("Failed to access clipboard: {}", e))?;
405
406 ctx.set_contents(content.to_string())
407 .map_err(|e| anyhow::anyhow!("Failed to write to clipboard: {}", e))?;
408
409 Ok(json!({
410 "success": true,
411 "content_length": content.len()
412 }))
413 }
414}