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