Elffuss BraidHub

kikocis/continue public

e31fcddb0dec · 11.9 KiBRawPermalink
1import { ConfigYaml, parseConfigYaml } from "@continuedev/config-yaml";
2import {
3 ArrowPathIcon,
4 ChevronDownIcon,
5 CircleStackIcon,
6 CommandLineIcon,
7 GlobeAltIcon,
8 UserCircleIcon,
9 WrenchScrewdriverIcon,
10} from "@heroicons/react/24/outline";
11import { MCPServerStatus } from "core";
12import { useContext, useMemo, useState } from "react";
13import Alert from "../../../components/gui/Alert";
14import { ToolTip } from "../../../components/gui/Tooltip";
15import EditBlockButton from "../../../components/mainInput/Lump/EditBlockButton";
16import { Button, Card, EmptyState } from "../../../components/ui";
17import { useAuth } from "../../../context/Auth";
18import { IdeMessengerContext } from "../../../context/IdeMessenger";
19import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
20import { updateConfig } from "../../../redux/slices/configSlice";
21import { selectCurrentOrg } from "../../../redux/slices/profilesSlice";
22import { ConfigHeader } from "../components/ConfigHeader";
23import { ToolPolicies } from "../components/ToolPolicies";
24
25interface MCPServerStatusProps {
26 server: MCPServerStatus;
27 serverFromYaml?: NonNullable<ConfigYaml["mcpServers"]>[number];
28}
29
30function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
31 const [expandedSections, setExpandedSections] = useState<{
32 [key: string]: boolean;
33 }>({});
34 const ideMessenger = useContext(IdeMessengerContext);
35 const config = useAppSelector((store) => store.config.config);
36 const dispatch = useAppDispatch();
37
38 const updateMCPServerStatus = (status: MCPServerStatus["status"]) => {
39 // optimistic config update
40 dispatch(
41 updateConfig({
42 ...config,
43 mcpServerStatuses: config.mcpServerStatuses.map((s) =>
44 s.id === server.id
45 ? {
46 ...s,
47 status,
48 }
49 : s,
50 ),
51 }),
52 );
53 };
54
55 const onAuthenticate = async () => {
56 updateMCPServerStatus("authenticating");
57 await ideMessenger.request("mcp/startAuthentication", server);
58 };
59
60 const onRemoveAuth = async () => {
61 updateMCPServerStatus("authenticating");
62 await ideMessenger.request("mcp/removeAuthentication", server);
63 };
64
65 const onRefresh = async () => {
66 updateMCPServerStatus("connecting");
67 ideMessenger.post("mcp/reloadServer", {
68 id: server.id,
69 });
70 };
71
72 const toggleSection = (section: string) => {
73 setExpandedSections((prev) => ({
74 ...prev,
75 [section]: !prev[section],
76 }));
77 };
78
79 const ResourceRow = ({
80 title,
81 items,
82 icon,
83 sectionKey,
84 }: {
85 title: string;
86 items: any[];
87 icon: React.ReactNode;
88 sectionKey: string;
89 }) => {
90 const isExpanded = expandedSections[sectionKey];
91 const hasItems = items.length > 0;
92
93 return (
94 <div>
95 <div
96 className="-mx-2 flex cursor-pointer items-center justify-between rounded px-2 py-2 hover:bg-gray-50 hover:bg-opacity-5"
97 onClick={() => toggleSection(sectionKey)}
98 >
99 <div className="flex items-center gap-3">
100 <ChevronDownIcon
101 className={`text-description h-3 w-3 transition-transform ${isExpanded ? "rotate-180" : ""}`}
102 />
103 <div className="flex items-center gap-2">
104 {icon}
105 <span className="text-sm">{title}</span>
106 <div className="flex h-5 w-5 items-center justify-center rounded-full bg-gray-600 text-xs font-medium text-white">
107 {items.length}
108 </div>
109 </div>
110 </div>
111 </div>
112
113 {isExpanded && (
114 <div className="mb-3 ml-6 mt-2">
115 {hasItems ? (
116 <div className="space-y-1">
117 {items.map((item, idx) => (
118 <div
119 key={idx}
120 className="text-description rounded bg-gray-50 bg-opacity-5 px-2 py-1 text-xs"
121 >
122 <code>{item.name}</code>
123 {item.description && (
124 <div className="mt-1 text-xs text-gray-500">
125 {item.description}
126 </div>
127 )}
128 </div>
129 ))}
130 </div>
131 ) : (
132 <div className="text-xs italic text-gray-500">
133 No {title.toLowerCase()} available
134 </div>
135 )}
136 </div>
137 )}
138 </div>
139 );
140 };
141
142 return (
143 <div>
144 <div className="flex items-center justify-between py-1">
145 <div className="flex items-center gap-3">
146 <div className="flex-1">
147 <div className="flex items-center gap-3">
148 <h3 className="my-0 text-sm font-medium">{server.name}</h3>
149 <div
150 className={`h-2 w-2 flex-shrink-0 rounded-full ${
151 server.status === "connected"
152 ? "bg-success"
153 : server.status === "connecting"
154 ? "bg-warning"
155 : server.status === "not-connected"
156 ? "bg-description-muted"
157 : "bg-error"
158 }`}
159 />
160 </div>
161 </div>
162 </div>
163
164 <div className="-mr-2.5 flex items-center gap-1">
165 {server.isProtectedResource && (
166 <ToolTip
167 content={
168 server.status === "error"
169 ? "Authenticate"
170 : server.status === "authenticating"
171 ? "Authenticating..."
172 : "Remove authentication"
173 }
174 >
175 <Button
176 onClick={
177 server.status === "error"
178 ? onAuthenticate
179 : server.status === "authenticating"
180 ? undefined
181 : onRemoveAuth
182 }
183 variant="ghost"
184 size="sm"
185 className="text-description-muted hover:enabled:text-foreground my-0 h-6 w-6 p-0"
186 disabled={server.status === "authenticating"}
187 >
188 {server.status === "authenticating" ? (
189 <GlobeAltIcon className="animate-spin-slow h-4 w-4 flex-shrink-0" />
190 ) : (
191 <UserCircleIcon className="h-4 w-4 flex-shrink-0" />
192 )}
193 </Button>
194 </ToolTip>
195 )}
196
197 <ToolTip content="Edit server configuration">
198 <div>
199 <EditBlockButton
200 blockType={"mcpServers"}
201 block={serverFromYaml}
202 sourceFile={server.sourceFile}
203 />
204 </div>
205 </ToolTip>
206
207 <ToolTip content="Refresh server">
208 <Button
209 onClick={onRefresh}
210 variant="ghost"
211 size="sm"
212 className="text-description-muted hover:enabled:text-foreground my-0 h-6 w-6 p-0"
213 >
214 <ArrowPathIcon className="h-4 w-4 flex-shrink-0" />
215 </Button>
216 </ToolTip>
217 </div>
218 </div>
219
220 {/* Individual resource rows */}
221 <div className="mt-1">
222 <ResourceRow
223 title="Tools"
224 items={server.tools}
225 icon={
226 <WrenchScrewdriverIcon className="text-description h-4 w-4 flex-shrink-0" />
227 }
228 sectionKey={`${server.id}-tools`}
229 />
230
231 <ResourceRow
232 title="Prompts"
233 items={server.prompts}
234 icon={
235 <CommandLineIcon className="text-description h-4 w-4 flex-shrink-0" />
236 }
237 sectionKey={`${server.id}-prompts`}
238 />
239
240 <ResourceRow
241 title="Resources"
242 items={[...server.resources, ...server.resourceTemplates]}
243 icon={
244 <CircleStackIcon className="text-description h-4 w-4 flex-shrink-0" />
245 }
246 sectionKey={`${server.id}-resources`}
247 />
248 </div>
249
250 {/* Error display below expandable section */}
251 {server.errors && server.errors.length > 0 && (
252 <div className="mt-3 space-y-2">
253 {server.errors.map((error, errorIndex) => (
254 <Alert
255 key={errorIndex}
256 type="error"
257 size="sm"
258 className="cursor-pointer transition-all hover:underline"
259 onClick={() =>
260 void ideMessenger.ide.showVirtualFile(server.name, error)
261 }
262 >
263 <span className="text-xs">
264 {error.length > 150 ? error.substring(0, 150) + "..." : error}
265 </span>
266 </Alert>
267 ))}
268 </div>
269 )}
270
271 {server.infos && server.infos.length > 0 && (
272 <div className="mt-3 space-y-2">
273 {server.infos.map((info, infoIndex) => (
274 <Alert
275 key={infoIndex}
276 type="info"
277 size="sm"
278 className="transition-all"
279 onClick={() =>
280 void ideMessenger.ide.showVirtualFile(server.name, info)
281 }
282 >
283 <span
284 className="text-xs"
285 dangerouslySetInnerHTML={{ __html: info }}
286 />
287 </Alert>
288 ))}
289 </div>
290 )}
291 </div>
292 );
293}
294
295function McpSubsection() {
296 const currentOrg = useAppSelector(selectCurrentOrg);
297 const servers = useAppSelector(
298 (store) => store.config.config.mcpServerStatuses,
299 );
300 const { selectedProfile } = useAuth();
301 const ideMessenger = useContext(IdeMessengerContext);
302 const disableMcp = currentOrg?.policy?.allowMcpServers === false;
303 const isLocal = selectedProfile?.profileType === "local";
304
305 const mergedBlocks = useMemo(() => {
306 const parsed = selectedProfile?.rawYaml
307 ? parseConfigYaml(selectedProfile?.rawYaml ?? "")
308 : undefined;
309
310 // Create a map of YAML servers keyed by name for stable matching
311 const yamlServersByName = new Map(
312 parsed?.mcpServers
313 ?.filter(
314 (server): server is NonNullable<typeof server> & { name: string } =>
315 server != null && "name" in server,
316 )
317 .map((server) => [server.name, server]) ?? [],
318 );
319
320 return (servers ?? []).map((doc) => ({
321 block: doc,
322 blockFromYaml: yamlServersByName.get(doc.name),
323 }));
324 }, [servers, selectedProfile]);
325
326 const handleAddMcpServer = () => {
327 if (isLocal) {
328 void ideMessenger.request("config/addLocalWorkspaceBlock", {
329 blockType: "mcpServers",
330 });
331 } else {
332 void ideMessenger.request("controlPlane/openUrl", {
333 path: "?type=mcpServers",
334 orgSlug: undefined,
335 });
336 }
337 };
338
339 return (
340 <div>
341 <ConfigHeader
342 title="MCP Servers"
343 variant="sm"
344 onAddClick={!disableMcp ? handleAddMcpServer : undefined}
345 addButtonTooltip="Add MCP server"
346 />
347 {disableMcp ? (
348 <Card>
349 <EmptyState message="MCP servers are disabled in your organization" />
350 </Card>
351 ) : mergedBlocks.length > 0 ? (
352 mergedBlocks.map(({ block, blockFromYaml }, index) => (
353 <div key={block.id}>
354 <Card>
355 <MCPServerPreview server={block} serverFromYaml={blockFromYaml} />
356 </Card>
357 {index < mergedBlocks.length - 1 && <div className="mb-4" />}
358 </div>
359 ))
360 ) : (
361 <Card>
362 <EmptyState message="No MCP servers configured. Click the + button to add your first server." />
363 </Card>
364 )}
365 </div>
366 );
367}
368
369function ToolPoliciesSubsection() {
370 return (
371 <div>
372 <ConfigHeader title="Tool Policies" variant="sm" />
373 <ToolPolicies />
374 </div>
375 );
376}
377
378export function ToolsSection() {
379 const availableTools = useAppSelector((state) => state.config.config.tools);
380
381 const hasTools = availableTools && availableTools.length > 0;
382
383 return (
384 <>
385 <ConfigHeader title="Tools" />
386 <div className="space-y-6">
387 <McpSubsection />
388 {hasTools && <ToolPoliciesSubsection />}
389 </div>
390 </>
391 );
392}