-
-
Notifications
You must be signed in to change notification settings - Fork 204
Expand file tree
/
Copy pathServerConnectionCard.tsx
More file actions
883 lines (836 loc) · 32.2 KB
/
ServerConnectionCard.tsx
File metadata and controls
883 lines (836 loc) · 32.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
import { useCallback, useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { Card } from "../ui/card";
import { Button } from "../ui/button";
import { Separator } from "../ui/separator";
import { Switch } from "../ui/switch";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "../ui/dropdown-menu";
import {
MoreVertical,
Link2Off,
RefreshCw,
Loader2,
Copy,
Download,
Check,
Edit,
ExternalLink,
Cable,
Trash2,
AlertCircle,
Share2,
Info,
FileText,
} from "lucide-react";
import { ServerWithName } from "@/hooks/use-app-state";
import { exportServerApi } from "@/lib/apis/mcp-export-api";
import {
getServerHealth,
type ServerHealthResponse,
} from "@/lib/apis/mcp-servers-api";
import {
getConnectionStatusMeta,
getServerCommandDisplay,
} from "./server-card-utils";
import { usePostHog, useFeatureFlagEnabled } from "posthog-js/react";
import { detectEnvironment, detectPlatform } from "@/lib/PosthogUtils";
import {
listTools,
type ListToolsResultWithMetadata,
} from "@/lib/apis/mcp-tools-api";
import { ServerInfoModal } from "./ServerInfoModal";
import { downloadJsonFile } from "@/lib/json-config-parser";
import { generateAgentBrief } from "@/lib/generate-agent-brief";
import {
TunnelExplanationModal,
TUNNEL_EXPLANATION_DISMISSED_KEY,
} from "./TunnelExplanationModal";
import {
cleanupOrphanedTunnels,
closeServerTunnel,
createServerTunnel,
getServerTunnel,
} from "@/lib/apis/mcp-tunnels-api";
import { useAuth } from "@workos-inc/authkit-react";
import { useConvexAuth } from "convex/react";
import { HOSTED_MODE } from "@/lib/config";
import { ShareServerDialog } from "./ShareServerDialog";
const SERVER_HEALTH_POLL_INTERVAL_MS = 30000;
function isHostedInsecureHttpServer(server: ServerWithName): boolean {
if (!HOSTED_MODE || !("url" in server.config) || !server.config.url) {
return false;
}
try {
return new URL(server.config.url.toString()).protocol === "http:";
} catch {
return false;
}
}
interface ServerConnectionCardProps {
server: ServerWithName;
onDisconnect: (serverName: string) => void;
onReconnect: (
serverName: string,
options?: { forceOAuthFlow?: boolean },
) => Promise<void>;
onEdit: (server: ServerWithName) => void;
onRemove?: (serverName: string) => void;
onServerInfoModalOpenChange?: (isOpen: boolean) => void;
serverTunnelUrl?: string | null;
hostedServerId?: string;
}
export function ServerConnectionCard({
server,
onDisconnect,
onReconnect,
onEdit,
onRemove,
onServerInfoModalOpenChange,
serverTunnelUrl,
hostedServerId,
}: ServerConnectionCardProps) {
const posthog = usePostHog();
const ciEvalsEnabled = useFeatureFlagEnabled("ci-evals-enabled");
const { getAccessToken } = useAuth();
const { isAuthenticated } = useConvexAuth();
const [isReconnecting, setIsReconnecting] = useState(false);
const [isExporting, setIsExporting] = useState(false);
const [isCopyingBrief, setIsCopyingBrief] = useState(false);
const [isErrorExpanded, setIsErrorExpanded] = useState(false);
const [isInfoModalOpen, setIsInfoModalOpen] = useState(false);
const [copiedField, setCopiedField] = useState<string | null>(null);
const [toolsData, setToolsData] =
useState<ListToolsResultWithMetadata | null>(null);
const [tunnelUrl, setTunnelUrl] = useState<string | null>(
serverTunnelUrl ?? null,
);
const [isCreatingTunnel, setIsCreatingTunnel] = useState(false);
const [isClosingTunnel, setIsClosingTunnel] = useState(false);
const [showTunnelExplanation, setShowTunnelExplanation] = useState(false);
const [isShareDialogOpen, setIsShareDialogOpen] = useState(false);
const [serverHealth, setServerHealth] = useState<ServerHealthResponse | null>(
null,
);
const [isCheckingHealth, setIsCheckingHealth] = useState(false);
const healthCheckRequestIdRef = useRef(0);
const { label: connectionStatusLabel, indicatorColor } =
getConnectionStatusMeta(server.connectionStatus);
const commandDisplay = getServerCommandDisplay(server.config);
const initializationInfo = server.initializationInfo;
// Extract server info from initializationInfo
const serverIcon = initializationInfo?.serverVersion?.icons?.[0];
const version = initializationInfo?.serverVersion?.version;
const serverTitle = initializationInfo?.serverVersion?.title;
const websiteUrl = initializationInfo?.serverVersion?.websiteUrl;
const protocolVersion = initializationInfo?.protocolVersion;
const instructions = initializationInfo?.instructions;
const serverCapabilities = initializationInfo?.serverCapabilities;
// Build capabilities list
const capabilities: string[] = [];
if (serverCapabilities?.tools) capabilities.push("Tools");
if (serverCapabilities?.prompts) capabilities.push("Prompts");
if (serverCapabilities?.resources) capabilities.push("Resources");
const hasInitInfo =
initializationInfo &&
(capabilities.length > 0 ||
protocolVersion ||
websiteUrl ||
instructions ||
serverCapabilities ||
serverTitle);
const isConnected = server.connectionStatus === "connected";
const isTunnelEnabled = !HOSTED_MODE;
const canManageTunnels = isAuthenticated;
const showTunnelActions = isConnected && isTunnelEnabled;
const showHealthStatus = isConnected && !HOSTED_MODE;
const hasTunnel = Boolean(tunnelUrl);
const hasError =
server.connectionStatus === "failed" && Boolean(server.lastError);
const isHostedHttpReconnectBlocked = isHostedInsecureHttpServer(server);
const isReconnectMenuDisabled =
isReconnecting ||
server.connectionStatus === "connecting" ||
server.connectionStatus === "oauth-flow";
const isStdioServer = "command" in server.config;
const isInsecureHttpServer =
"url" in server.config &&
!!server.config.url &&
(() => {
try {
return new URL(server.config.url.toString()).protocol === "http:";
} catch {
return false;
}
})();
const canShareServer =
HOSTED_MODE &&
!!hostedServerId &&
isAuthenticated &&
!isStdioServer &&
!isInsecureHttpServer;
// Load tools when server is connected
useEffect(() => {
const loadTools = async () => {
if (server.connectionStatus !== "connected") {
setToolsData(null);
return;
}
try {
const result = await listTools({ serverId: server.name });
setToolsData(result);
} catch (err) {
// Silently fail - tools metadata is optional
console.error("Failed to load tools metadata:", err);
setToolsData(null);
}
};
loadTools();
}, [server.name, server.connectionStatus]);
useEffect(() => {
if (serverTunnelUrl !== undefined) {
setTunnelUrl(serverTunnelUrl);
}
}, [serverTunnelUrl]);
const handleHealthCheck = useCallback(async () => {
if (!showHealthStatus) {
return;
}
const requestId = ++healthCheckRequestIdRef.current;
setIsCheckingHealth(true);
try {
const result = await getServerHealth(server.name);
if (healthCheckRequestIdRef.current !== requestId) {
return;
}
setServerHealth(result);
} catch (error) {
if (healthCheckRequestIdRef.current !== requestId) {
return;
}
setServerHealth({
success: false,
serverId: server.name,
connectionStatus: server.connectionStatus,
healthStatus: "unhealthy",
checkedAt: new Date().toISOString(),
error: error instanceof Error ? error.message : "Health check failed",
});
} finally {
if (healthCheckRequestIdRef.current === requestId) {
setIsCheckingHealth(false);
}
}
}, [server.connectionStatus, server.name, showHealthStatus]);
useEffect(() => {
let isCancelled = false;
const checkExistingTunnel = async () => {
if (!showTunnelActions) {
return;
}
try {
const accessToken = await getAccessToken();
const existingTunnel = await getServerTunnel(server.name, accessToken);
if (!isCancelled) {
setTunnelUrl(existingTunnel?.url ?? null);
}
} catch (err) {
if (!isCancelled && serverTunnelUrl === undefined) {
setTunnelUrl(null);
}
}
};
checkExistingTunnel();
return () => {
isCancelled = true;
};
}, [getAccessToken, server.name, serverTunnelUrl, showTunnelActions]);
useEffect(() => {
healthCheckRequestIdRef.current += 1;
if (!showHealthStatus) {
setServerHealth(null);
setIsCheckingHealth(false);
return;
}
void handleHealthCheck();
const intervalId = window.setInterval(() => {
void handleHealthCheck();
}, SERVER_HEALTH_POLL_INTERVAL_MS);
return () => {
healthCheckRequestIdRef.current += 1;
window.clearInterval(intervalId);
};
}, [handleHealthCheck, showHealthStatus]);
const copyToClipboard = async (text: string, fieldName: string) => {
try {
await navigator.clipboard.writeText(text);
setCopiedField(fieldName);
setTimeout(() => setCopiedField(null), 2000); // Reset after 2 seconds
} catch (error) {
console.error("Failed to copy text:", error);
}
};
const handleReconnect = async (options?: { forceOAuthFlow?: boolean }) => {
setIsReconnecting(true);
try {
await onReconnect(server.name, options);
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : "Unknown error";
toast.error(`Failed to reconnect to ${server.name}: ${errorMessage}`);
} finally {
setIsReconnecting(false);
}
};
const handleExport = async () => {
setIsExporting(true);
try {
const toastId = toast.loading(`Exporting ${server.name}…`);
const data = await exportServerApi(server.name);
const ts = new Date().toISOString().replace(/[:.]/g, "-");
const filename = `mcp-server-export_${server.name}_${ts}.json`;
downloadJsonFile(filename, data);
toast.success(`Exported ${server.name} info to ${filename}`, {
id: toastId,
});
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : "Unknown error";
toast.error(`Failed to export ${server.name}: ${errorMessage}`);
} finally {
setIsExporting(false);
}
};
const handleCopyAgentBrief = async () => {
setIsCopyingBrief(true);
try {
const data = await exportServerApi(server.name);
const serverUrl =
"url" in server.config && server.config.url
? server.config.url.toString()
: "command" in server.config
? [server.config.command, ...(server.config.args ?? [])]
.filter(Boolean)
.join(" ")
: undefined;
const markdown = generateAgentBrief(data, { serverUrl });
await navigator.clipboard.writeText(markdown);
toast.success("Agent brief copied to clipboard");
posthog.capture("copy_agent_brief_clicked", {
location: "server_connection_card",
platform: detectPlatform(),
environment: detectEnvironment(),
server_id: server.name,
});
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : "Unknown error";
toast.error(`Failed to copy agent brief: ${errorMessage}`);
} finally {
setIsCopyingBrief(false);
}
};
const handleCreateTunnel = () => {
posthog.capture("create_tunnel_button_clicked", {
location: "server_connection_card",
platform: detectPlatform(),
environment: detectEnvironment(),
server_id: server.name,
});
const isDismissed =
localStorage.getItem(TUNNEL_EXPLANATION_DISMISSED_KEY) === "true";
if (isDismissed) {
void handleConfirmCreateTunnel();
} else {
setShowTunnelExplanation(true);
}
};
const handleConfirmCreateTunnel = async () => {
setIsCreatingTunnel(true);
try {
const accessToken = await getAccessToken();
await cleanupOrphanedTunnels(accessToken);
const result = await createServerTunnel(server.name, accessToken);
setTunnelUrl(result.url);
await cleanupOrphanedTunnels(accessToken);
toast.success("Tunnel is ready to use!");
posthog.capture("tunnel_created", {
location: "server_connection_card",
platform: detectPlatform(),
environment: detectEnvironment(),
server_id: server.name,
});
setShowTunnelExplanation(false);
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : "Failed to create tunnel";
toast.error(`Tunnel creation failed: ${errorMessage}`);
} finally {
setIsCreatingTunnel(false);
}
};
const handleCloseTunnel = async () => {
setIsClosingTunnel(true);
try {
const accessToken = await getAccessToken();
await closeServerTunnel(server.name, accessToken);
setTunnelUrl(null);
toast.success("Tunnel closed successfully");
posthog.capture("tunnel_closed", {
location: "server_connection_card",
platform: detectPlatform(),
environment: detectEnvironment(),
server_id: server.name,
});
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : "Failed to close tunnel";
toast.error(`Failed to close tunnel: ${errorMessage}`);
} finally {
setIsClosingTunnel(false);
}
};
const healthStatusClasses =
serverHealth?.success === false
? "border-red-300/40 bg-red-500/10 text-red-700 dark:text-red-300"
: serverHealth?.success === true
? "border-emerald-300/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300"
: "border-border/70 bg-muted/30 text-muted-foreground";
const healthLabel =
serverHealth?.success === false
? "Ping failed"
: serverHealth?.success === true
? `Ping ok ${serverHealth.latencyMs} ms`
: isCheckingHealth
? "Checking ping..."
: "Ping pending";
const healthTitle =
serverHealth?.success === false
? serverHealth.error
: serverHealth?.success === true
? `Last ping ${new Date(serverHealth.checkedAt).toLocaleTimeString()}`
: "Checks whether the server responds to MCP ping";
return (
<>
<Card className="group h-full rounded-xl border border-border/50 bg-card/60 p-0 shadow-sm transition-all duration-200 hover:border-border hover:shadow-md">
<div className="p-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
{serverIcon?.src && (
<img
src={serverIcon.src}
alt={`${server.name} icon`}
className="h-5 w-5 flex-shrink-0 rounded"
onError={(e) => {
e.currentTarget.style.display = "none";
}}
/>
)}
<h3 className="truncate text-sm font-semibold text-foreground">
{server.name}
</h3>
{version && (
<span className="text-xs text-muted-foreground">
v{version}
</span>
)}
</div>
<div className="mt-2 flex flex-wrap items-center gap-1.5">
{hasError && (
<button
onClick={() => setIsErrorExpanded(true)}
className="inline-flex items-center gap-1 rounded-full border border-red-300/60 bg-red-500/10 px-2 py-0.5 text-[11px] text-red-700 dark:text-red-300 cursor-pointer"
>
<AlertCircle className="h-3 w-3" />
Error
</button>
)}
</div>
</div>
<div className="flex flex-col items-end gap-1.5">
<div
className="flex items-center gap-1.5"
onClick={(e) => e.stopPropagation()}
>
<span className="inline-flex items-center gap-1.5 px-1 text-[11px] text-muted-foreground">
<span
className="h-1.5 w-1.5 rounded-full"
style={{ backgroundColor: indicatorColor }}
/>
<span>
{server.connectionStatus === "failed"
? `${connectionStatusLabel} (${server.retryCount})`
: connectionStatusLabel}
</span>
</span>
<Switch
checked={server.connectionStatus === "connected"}
onCheckedChange={(checked) => {
posthog.capture("connection_switch_toggled", {
location: "server_connection_card",
platform: detectPlatform(),
environment: detectEnvironment(),
});
if (checked && isHostedHttpReconnectBlocked) {
toast.error(
"HTTP servers are not supported in hosted mode",
);
return;
}
if (!checked) {
onDisconnect(server.name);
} else {
void handleReconnect();
}
}}
className="cursor-pointer scale-75"
/>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-7 w-7 p-0 text-muted-foreground/70 hover:text-foreground cursor-pointer"
>
<MoreVertical className="h-3.5 w-3.5" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-44">
<DropdownMenuItem
onClick={() => {
if (isHostedHttpReconnectBlocked) {
toast.error(
"HTTP servers are not supported in hosted mode",
);
return;
}
posthog.capture("reconnect_server_clicked", {
location: "server_connection_card",
platform: detectPlatform(),
environment: detectEnvironment(),
});
const shouldForceOAuth =
server.useOAuth === true ||
server.oauthTokens != null;
void handleReconnect(
shouldForceOAuth
? { forceOAuthFlow: true }
: undefined,
);
}}
disabled={isReconnectMenuDisabled}
className="text-xs cursor-pointer"
>
{isReconnecting ? (
<Loader2 className="h-3 w-3 mr-2 animate-spin" />
) : (
<RefreshCw className="h-3 w-3 mr-2" />
)}
{isReconnecting ? "Reconnecting..." : "Reconnect"}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
posthog.capture("edit_server_clicked", {
location: "server_connection_card",
platform: detectPlatform(),
environment: detectEnvironment(),
});
onEdit(server);
}}
className="text-xs cursor-pointer"
>
<Edit className="h-3 w-3 mr-2" />
Edit
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
posthog.capture("export_server_clicked", {
location: "server_connection_card",
platform: detectPlatform(),
environment: detectEnvironment(),
});
handleExport();
}}
disabled={
isExporting || server.connectionStatus !== "connected"
}
className="text-xs cursor-pointer"
>
{isExporting ? (
<Loader2 className="h-3 w-3 mr-2 animate-spin" />
) : (
<Download className="h-3 w-3 mr-2" />
)}
{isExporting ? "Exporting..." : "Export server info"}
</DropdownMenuItem>
{ciEvalsEnabled && (
<DropdownMenuItem
onClick={() => {
handleCopyAgentBrief();
}}
disabled={
isCopyingBrief ||
server.connectionStatus !== "connected"
}
className="text-xs cursor-pointer"
>
{isCopyingBrief ? (
<Loader2 className="h-3 w-3 mr-2 animate-spin" />
) : (
<FileText className="h-3 w-3 mr-2" />
)}
{isCopyingBrief
? "Copying..."
: "Copy markdown for server evals"}
</DropdownMenuItem>
)}
<Separator />
<DropdownMenuItem
className="text-destructive text-xs cursor-pointer"
onClick={() => {
posthog.capture("remove_server_clicked", {
location: "server_connection_card",
platform: detectPlatform(),
environment: detectEnvironment(),
});
onDisconnect(server.name);
onRemove?.(server.name);
}}
>
<Link2Off className="h-3 w-3 mr-2" />
Remove server
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</div>
<div
className="relative mt-2 rounded-md border border-border/50 bg-muted/30 p-2 pr-8 font-mono text-xs text-muted-foreground"
onClick={(e) => e.stopPropagation()}
>
<div className="break-all">{commandDisplay}</div>
<button
onClick={(e) => {
e.stopPropagation();
copyToClipboard(commandDisplay, "command");
}}
className="absolute right-1 top-1 p-1 text-muted-foreground/60 transition-colors hover:text-foreground cursor-pointer"
>
{copiedField === "command" ? (
<Check className="h-3 w-3" />
) : (
<Copy className="h-3 w-3" />
)}
</button>
</div>
<div className="mt-3 flex flex-wrap items-center gap-2">
{showHealthStatus && (
<div
className="flex items-center gap-1.5"
onClick={(e) => e.stopPropagation()}
>
<div
className={`inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-[11px] ${healthStatusClasses}`}
title={healthTitle}
>
{isCheckingHealth ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : serverHealth?.success === false ? (
<AlertCircle className="h-3 w-3" />
) : serverHealth?.success === true ? (
<Check className="h-3 w-3" />
) : (
<RefreshCw className="h-3 w-3" />
)}
<span>{healthLabel}</span>
</div>
<button
type="button"
onClick={() => {
posthog.capture("server_health_refresh_clicked", {
location: "server_connection_card",
platform: detectPlatform(),
environment: detectEnvironment(),
server_id: server.name,
});
void handleHealthCheck();
}}
disabled={isCheckingHealth}
className="inline-flex h-6 w-6 items-center justify-center rounded-full border border-border/70 bg-muted/30 text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-60 cursor-pointer"
aria-label="Refresh server health"
title="Refresh server health"
>
<RefreshCw
className={`h-3 w-3 ${isCheckingHealth ? "animate-spin" : ""}`}
/>
</button>
</div>
)}
<div
className="ml-auto flex items-center gap-2"
onClick={(e) => e.stopPropagation()}
>
{hasInitInfo && (
<button
onClick={() => {
posthog.capture("view_server_info_clicked", {
location: "server_connection_card",
platform: detectPlatform(),
environment: detectEnvironment(),
server_id: server.name,
});
setIsInfoModalOpen(true);
onServerInfoModalOpenChange?.(true);
}}
className="inline-flex items-center gap-1.5 rounded-full border border-border/70 bg-muted/30 px-2 py-0.5 text-[11px] text-foreground transition-colors hover:bg-accent/60 cursor-pointer"
>
<Info className="h-3 w-3" strokeWidth={2.5} />
<span>View server info</span>
</button>
)}
{canShareServer && (
<button
onClick={() => {
posthog.capture("share_server_clicked", {
location: "server_connection_card",
platform: detectPlatform(),
environment: detectEnvironment(),
});
setIsShareDialogOpen(true);
}}
className="inline-flex items-center gap-1.5 rounded-full border border-border/70 bg-muted/30 px-2 py-0.5 text-[11px] text-foreground transition-colors hover:bg-accent/60 cursor-pointer"
>
<Share2 className="h-3 w-3" />
<span>Share</span>
</button>
)}
{showTunnelActions && (
<>
{hasTunnel ? (
<div className="inline-flex items-center overflow-hidden rounded-full border border-border/70 bg-muted/30 text-foreground">
<button
onClick={() => copyToClipboard(tunnelUrl!, "tunnel")}
className="inline-flex items-center gap-1.5 px-2 py-0.5 text-[11px] transition-colors hover:bg-accent/60 cursor-pointer"
>
{copiedField === "tunnel" ? (
<>
<Check className="h-3 w-3" />
<span>Copied</span>
</>
) : (
<>
<Cable className="h-3 w-3" />
<span>Copy ngrok URL</span>
</>
)}
</button>
<span className="h-4 w-px bg-border/80" />
<button
onClick={handleCloseTunnel}
disabled={isClosingTunnel}
className="inline-flex items-center justify-center px-1.5 py-0.5 text-destructive transition-colors hover:bg-destructive/15 hover:text-destructive disabled:cursor-not-allowed disabled:opacity-60 cursor-pointer"
aria-label="Close tunnel"
title="Close tunnel"
>
{isClosingTunnel ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
<Trash2 className="h-3 w-3" />
)}
</button>
</div>
) : (
<button
onClick={handleCreateTunnel}
disabled={isCreatingTunnel || !canManageTunnels}
className="inline-flex items-center gap-1.5 rounded-full border border-border/70 bg-muted/30 px-2 py-0.5 text-[11px] text-foreground transition-colors hover:bg-accent/60 disabled:cursor-not-allowed disabled:opacity-60 cursor-pointer"
>
{isCreatingTunnel ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
<Cable className="h-3 w-3" />
)}
<span>
{canManageTunnels
? "Create ngrok tunnel"
: "Sign in for tunnel"}
</span>
</button>
)}
</>
)}
</div>
</div>
{hasError && (
<div className="mt-3 rounded-md border border-red-300/40 bg-red-500/10 p-2 text-xs text-red-700 dark:text-red-300">
<div className="break-all">
{isErrorExpanded
? server.lastError
: server.lastError!.length > 140
? `${server.lastError!.substring(0, 140)}...`
: server.lastError}
</div>
{server.lastError!.length > 140 && (
<button
onClick={() => setIsErrorExpanded((prev) => !prev)}
className="mt-1 underline cursor-pointer"
>
{isErrorExpanded ? "Show less" : "Show more"}
</button>
)}
{server.retryCount > 0 && (
<div className="mt-1 opacity-80">
{server.retryCount} retry attempt
{server.retryCount !== 1 ? "s" : ""}
</div>
)}
</div>
)}
{server.connectionStatus === "failed" && (
<div className="mt-2 text-xs text-muted-foreground">
Having trouble?{" "}
<a
href="https://docs.mcpjam.com/troubleshooting/common-errors"
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-primary hover:underline"
>
Check troubleshooting
<ExternalLink className="h-3 w-3" />
</a>
</div>
)}
</div>
</Card>
<ServerInfoModal
isOpen={isInfoModalOpen}
onClose={() => {
setIsInfoModalOpen(false);
onServerInfoModalOpenChange?.(false);
}}
server={server}
toolsData={toolsData}
/>
<TunnelExplanationModal
isOpen={showTunnelExplanation}
onClose={() => setShowTunnelExplanation(false)}
onConfirm={handleConfirmCreateTunnel}
isCreating={isCreatingTunnel}
/>
{canShareServer && hostedServerId && (
<ShareServerDialog
isOpen={isShareDialogOpen}
onClose={() => setIsShareDialogOpen(false)}
serverId={hostedServerId}
serverName={server.name}
/>
)}
</>
);
}