Elffuss BraidHub

kikocis/continue public

main · 10.8 KiBRawPermalink
1import { Box, Text, useInput } from "ink";
2import React, { useState } from "react";
3import { quote } from "shell-quote";
4
5import { useServices } from "../hooks/useService.js";
6import {
7 MCPConnectionInfo,
8 MCPServerStatus,
9 MCPServiceState,
10 SERVICE_NAMES,
11} from "../services/types.js";
12import { logger } from "../util/logger.js";
13
14import { defaultBoxStyles } from "./styles.js";
15
16// Utility function to get status icon and color based on server connection
17const getServerStatusDisplay = (conn: MCPConnectionInfo) => {
18 let icon = "⚪️"; // note, white circle causes extra blank line bug
19 let color: "green" | "yellow" | "red" | "white" | "dim" = "white";
20 let statusText = conn.status;
21
22 if (conn.status === "connecting") {
23 icon = "🟡";
24 color = "yellow";
25 } else if (conn.status === "error") {
26 icon = "🔴";
27 color = "red";
28 } else if (conn.status === "connected") {
29 if (conn.warnings && conn.warnings.length > 0) {
30 icon = "🟡";
31 color = "yellow";
32 statusText = "connected (with warnings)" as MCPServerStatus;
33 } else {
34 icon = "🟢";
35 color = "green";
36 }
37 }
38
39 return { icon, color, statusText };
40};
41
42interface MCPSelectorProps {
43 onCancel: () => void;
44}
45
46type MCPMenuState = "main" | "server-detail";
47
48interface MCPMenuItem {
49 label: string;
50 value: string;
51}
52
53export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
54 const [menuState, setMenuState] = useState<MCPMenuState>("main");
55 const [selectedServer, setSelectedServer] = useState<string | null>(null);
56 const [selectedIndex, setSelectedIndex] = useState(0);
57 const [isLoading, setIsLoading] = useState(false);
58 const [message, setMessage] = useState<string | null>(null);
59
60 const { services } = useServices<{ mcp: MCPServiceState }>([
61 SERVICE_NAMES.MCP,
62 ]);
63 const connections = services.mcp?.connections ?? [];
64 const mcpService = services.mcp?.mcpService;
65
66 const backItem = { label: "Back", value: "back" };
67
68 const handleBack = () => {
69 if (menuState === "server-detail") {
70 setSelectedServer(null);
71 setMenuState("main");
72 setSelectedIndex(0);
73 } else {
74 onCancel();
75 }
76 setMessage(null);
77 };
78
79 // Main menu items (includes servers)
80 const getMainMenuItems = (): MCPMenuItem[] => {
81 const options: MCPMenuItem[] = [];
82
83 // Add individual servers first
84 if (connections.length > 0) {
85 connections.forEach((conn) => {
86 const { icon } = getServerStatusDisplay(conn);
87
88 let serverLabel = `${icon} ${conn.config.name}`;
89
90 // Add tools and prompts count if server is connected
91 if (conn.status === "connected") {
92 const toolsCount = conn.tools.length;
93 const promptsCount = conn.prompts.length;
94
95 const counts = [];
96 if (toolsCount > 0) {
97 counts.push(`🔧${toolsCount}`);
98 }
99 if (promptsCount > 0) {
100 counts.push(`📝${promptsCount}`);
101 }
102
103 if (counts.length > 0) {
104 serverLabel += ` (${counts.join(" ")})`;
105 }
106 }
107
108 options.push({
109 label: serverLabel,
110 value: `server:${conn.config.name}`,
111 });
112 });
113
114 // Add bulk actions
115 options.push(
116 { label: "🔄 Restart all servers", value: "restart-all" },
117 { label: "⏹️ Stop all servers", value: "stop-all" },
118 );
119 }
120 return options;
121 };
122
123 // Server detail items
124 const getServerDetailItems = (): MCPMenuItem[] => {
125 if (!selectedServer) return [];
126
127 const serverInfo = connections.find(
128 (conn) => conn.config.name === selectedServer,
129 );
130 if (!serverInfo) return [];
131
132 const items: MCPMenuItem[] = [
133 { label: "🔄 Restart server", value: "restart" },
134 ];
135
136 // Only show stop server if it's connected
137 if (serverInfo.status === "connected") {
138 items.push({ label: "⏹️ Stop server", value: "stop" });
139 }
140
141 return items;
142 };
143 const getServerInfoDisplay = () => {
144 if (menuState !== "server-detail" || !selectedServer) return null;
145
146 const serverInfo = connections.find(
147 (conn) => conn.config.name === selectedServer,
148 );
149 if (!serverInfo) return null;
150
151 return (
152 <Box flexDirection="column">
153 {/* Add error if server has error status */}
154 {serverInfo.status === "error" && serverInfo.error && (
155 <Box flexDirection="column" marginBottom={1}>
156 <Text color="red" bold>
157 🚫 Error:
158 </Text>
159 <Text color="red">{serverInfo.error}</Text>
160 </Box>
161 )}
162
163 {/* Add warnings if any */}
164 {serverInfo.warnings.length > 0 && (
165 <Box flexDirection="column" marginBottom={1}>
166 <Text color="yellow" bold>
167 ⚠️ Warnings:
168 </Text>
169 {serverInfo.warnings.map((warning, index) => (
170 <Text key={index} color="yellow">
171 • {warning}
172 </Text>
173 ))}
174 </Box>
175 )}
176
177 {/* Add prompts if any */}
178 {serverInfo.prompts.length > 0 && (
179 <Box flexDirection="column" marginBottom={1}>
180 <Text color="blue">📝 Prompts: {serverInfo.prompts.length}</Text>
181 {serverInfo.prompts.map((prompt, index) => (
182 <Text key={index} color="dim">
183 • {prompt.name}
184 </Text>
185 ))}
186 </Box>
187 )}
188
189 {/* Add tools if any */}
190 {serverInfo.tools.length > 0 && (
191 <Box flexDirection="column" marginBottom={1}>
192 <Text color="blue">🔧 Tools: {serverInfo.tools.length}</Text>
193 {serverInfo.tools.map((tool, index) => (
194 <Text key={index} color="dim">
195 • {tool.name}
196 </Text>
197 ))}
198 </Box>
199 )}
200 </Box>
201 );
202 };
203
204 let items: MCPMenuItem[] = [];
205
206 switch (menuState) {
207 case "main":
208 items = getMainMenuItems();
209 break;
210 case "server-detail":
211 items = getServerDetailItems();
212 break;
213 }
214
215 items = [...items, backItem];
216
217 const maxIndex = Math.max(0, items.length - 1);
218
219 useInput(async (input, key) => {
220 // Always allow escape/Ctrl+C so users can cancel even when loading
221 if (key.escape || (key.ctrl && input === "c")) {
222 handleBack();
223 return;
224 }
225
226 if (isLoading) return;
227
228 if (key.upArrow) {
229 setSelectedIndex(selectedIndex <= 0 ? maxIndex : selectedIndex - 1);
230 return;
231 }
232
233 if (key.downArrow) {
234 setSelectedIndex((prev) => (prev >= maxIndex ? 0 : prev + 1));
235 return;
236 }
237
238 if (key.return) {
239 const selectedItem = items[selectedIndex];
240 if (!selectedItem) return;
241
242 setIsLoading(true);
243 setMessage(null);
244
245 try {
246 switch (menuState) {
247 case "main":
248 await handleMainMenuSelect(selectedItem.value);
249 break;
250 case "server-detail":
251 await handleServerAction(selectedItem.value);
252 break;
253 }
254 } catch (error: any) {
255 setMessage(`Error: ${error.message}`);
256 } finally {
257 setIsLoading(false);
258 }
259 }
260 });
261
262 const handleMainMenuSelect = async (value: string) => {
263 if (!mcpService) return;
264
265 if (value.startsWith("server:")) {
266 // Handle server selection
267 const serverName = value.replace("server:", "");
268 setSelectedServer(serverName);
269 setMenuState("server-detail");
270 setSelectedIndex(0);
271 return;
272 }
273
274 switch (value) {
275 case "restart-all":
276 await mcpService.restartAllServers();
277 setMessage("All servers restarted");
278 break;
279 case "stop-all":
280 await mcpService.shutdownConnections();
281 setMessage("All servers stopped");
282 break;
283 case "back":
284 onCancel();
285 return;
286 }
287 };
288
289 const handleServerAction = async (action: string) => {
290 if (!mcpService || !selectedServer) return;
291 try {
292 switch (action) {
293 case "restart":
294 await mcpService.restartServer(selectedServer);
295 setMessage(`Server "${selectedServer}" restarted`);
296 break;
297 case "stop":
298 await mcpService.stopServer(selectedServer);
299 setMessage(`Server "${selectedServer}" stopped`);
300 break;
301 case "back":
302 handleBack();
303 return;
304 }
305 } catch {
306 logger.error("Error handling MCP action");
307 }
308 };
309
310 const renderHeader = () => {
311 return (
312 <Box flexDirection="column" marginBottom={1}>
313 <Text bold color="blue">
314 {menuState === "server-detail" && selectedServer
315 ? `Server: ${selectedServer}`
316 : "MCP Servers"}
317 </Text>
318 {connections.length === 0 && (
319 <Text color="gray">No servers configured</Text>
320 )}
321 {menuState === "server-detail" &&
322 selectedServer &&
323 (() => {
324 const serverInfo = connections.find(
325 (conn) => conn.config.name === selectedServer,
326 );
327 if (!serverInfo) return null;
328
329 const { color: statusColor, statusText } =
330 getServerStatusDisplay(serverInfo);
331
332 let configText = "";
333 if ("command" in serverInfo.config) {
334 const { command, args } = serverInfo.config;
335 const cmd = command ? quote([command, ...(args ?? [])]) : "";
336 if (cmd) {
337 configText = ` • Command: ${cmd}`;
338 }
339 } else {
340 const { url } = serverInfo.config;
341 configText = ` • URL: ${url}`;
342 }
343 configText = configText.replace(/\$\{\{.*\}\}/, "(secret)");
344
345 return (
346 <Text color="dim">
347 Status: <Text color={statusColor}>{statusText}</Text>
348 {configText}
349 </Text>
350 );
351 })()}
352 </Box>
353 );
354 };
355
356 return (
357 <Box {...defaultBoxStyles("blue", { minHeight: 10 })}>
358 {renderHeader()}
359
360 {message && (
361 <Box marginBottom={1}>
362 <Text color={message.startsWith("Error:") ? "red" : "green"}>
363 {message}
364 </Text>
365 </Box>
366 )}
367
368 {menuState === "server-detail" && getServerInfoDisplay()}
369
370 {isLoading ? (
371 <Box>
372 <Text color="yellow">Working...</Text>
373 </Box>
374 ) : (
375 <Box flexDirection="column">
376 {items.map((item, index) => {
377 const isSelected = index === selectedIndex;
378
379 return (
380 <Text
381 key={`${item.value}-${index}`}
382 color={isSelected ? "blue" : "white"}
383 bold={isSelected}
384 >
385 {isSelected ? "➤ " : " "}
386 {item.label}
387 </Text>
388 );
389 })}
390 </Box>
391 )}
392
393 <Box marginTop={1}>
394 <Text color="dim">
395 ↑/↓ to navigate, Enter to select, Esc to go back
396 </Text>
397 </Box>
398 </Box>
399 );
400};