chore: ran frontend linting

This commit is contained in:
Anish Sarkar 2026-01-19 21:23:22 +05:30
parent 5f672a07f2
commit f0997b0a30
11 changed files with 199 additions and 193 deletions

View file

@ -101,7 +101,8 @@ export const ConnectorIndicator: FC = () => {
// Fallback to API if Electric is not available or fails // Fallback to API if Electric is not available or fails
// Use Electric data if: 1) we have data, or 2) still loading without error // Use Electric data if: 1) we have data, or 2) still loading without error
// Use API data if: Electric failed (has error) or finished loading with no data // Use API data if: Electric failed (has error) or finished loading with no data
const useElectricData = connectorsFromElectric.length > 0 || (connectorsLoading && !connectorsError); const useElectricData =
connectorsFromElectric.length > 0 || (connectorsLoading && !connectorsError);
const connectors = useElectricData ? connectorsFromElectric : allConnectors || []; const connectors = useElectricData ? connectorsFromElectric : allConnectors || [];
// Manual refresh function that works with both Electric and API // Manual refresh function that works with both Electric and API
@ -129,7 +130,7 @@ export const ConnectorIndicator: FC = () => {
const hasConnectors = connectors.length > 0; const hasConnectors = connectors.length > 0;
const hasSources = hasConnectors || activeDocumentTypes.length > 0; const hasSources = hasConnectors || activeDocumentTypes.length > 0;
const totalSourceCount = connectors.length + activeDocumentTypes.length; const totalSourceCount = connectors.length + activeDocumentTypes.length;
const activeConnectorsCount = connectors.length; const activeConnectorsCount = connectors.length;
// Check which connectors are already connected // Check which connectors are already connected
@ -226,7 +227,6 @@ export const ConnectorIndicator: FC = () => {
isDisconnecting={isDisconnecting} isDisconnecting={isDisconnecting}
isIndexing={indexingConnectorIds.has(editingConnector.id)} isIndexing={indexingConnectorIds.has(editingConnector.id)}
searchSpaceId={searchSpaceId?.toString()} searchSpaceId={searchSpaceId?.toString()}
onStartDateChange={setStartDate} onStartDateChange={setStartDate}
onEndDateChange={setEndDate} onEndDateChange={setEndDate}
onPeriodicEnabledChange={setPeriodicEnabled} onPeriodicEnabledChange={setPeriodicEnabled}

View file

@ -49,12 +49,12 @@ export const MCPConnectForm: FC<ConnectFormProps> = ({ onSubmit, isSubmitting })
const handleConfigChange = (value: string) => { const handleConfigChange = (value: string) => {
setConfigJson(value); setConfigJson(value);
// Clear previous error // Clear previous error
if (jsonError) { if (jsonError) {
setJsonError(null); setJsonError(null);
} }
// Validate immediately to show errors as user types (with debouncing via parseMCPConfig cache) // Validate immediately to show errors as user types (with debouncing via parseMCPConfig cache)
if (value.trim()) { if (value.trim()) {
const result = parseMCPConfig(value); const result = parseMCPConfig(value);
@ -120,13 +120,14 @@ export const MCPConnectForm: FC<ConnectFormProps> = ({ onSubmit, isSubmitting })
return ( return (
<div className="space-y-6 pb-6"> <div className="space-y-6 pb-6">
<Alert className="bg-slate-400/5 dark:bg-white/5 border-slate-400/20 p-2 sm:p-3 [&>svg]:top-2 sm:[&>svg]:top-3"> <Alert className="bg-slate-400/5 dark:bg-white/5 border-slate-400/20 p-2 sm:p-3 [&>svg]:top-2 sm:[&>svg]:top-3">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Server className="h-4 w-4 shrink-0" /> <Server className="h-4 w-4 shrink-0" />
<AlertDescription className="text-[10px] sm:text-xs"> <AlertDescription className="text-[10px] sm:text-xs">
Connect to an MCP (Model Context Protocol) server. Each MCP server is added as a separate connector. Connect to an MCP (Model Context Protocol) server. Each MCP server is added as a
</AlertDescription> separate connector.
</div> </AlertDescription>
</Alert> </div>
</Alert>
<form id="mcp-connect-form" onSubmit={handleSubmit} className="space-y-6"> <form id="mcp-connect-form" onSubmit={handleSubmit} className="space-y-6">
<div className="rounded-xl border border-border bg-slate-400/5 dark:bg-white/5 p-4 sm:p-6 space-y-4"> <div className="rounded-xl border border-border bg-slate-400/5 dark:bg-white/5 p-4 sm:p-6 space-y-4">
@ -140,11 +141,10 @@ export const MCPConnectForm: FC<ConnectFormProps> = ({ onSubmit, isSubmitting })
rows={16} rows={16}
className={`font-mono text-xs ${jsonError ? "border-red-500" : ""}`} className={`font-mono text-xs ${jsonError ? "border-red-500" : ""}`}
/> />
{jsonError && ( {jsonError && <p className="text-xs text-red-500">{jsonError}</p>}
<p className="text-xs text-red-500">{jsonError}</p>
)}
<p className="text-[10px] sm:text-xs text-muted-foreground"> <p className="text-[10px] sm:text-xs text-muted-foreground">
Paste a single MCP server configuration. Must include: name, command, args (optional), env (optional), transport (optional). Paste a single MCP server configuration. Must include: name, command, args (optional),
env (optional), transport (optional).
</p> </p>
</div> </div>
@ -178,7 +178,9 @@ export const MCPConnectForm: FC<ConnectFormProps> = ({ onSubmit, isSubmitting })
<div className="flex-1"> <div className="flex-1">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-0"> <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-0">
<AlertTitle className="text-xs sm:text-sm"> <AlertTitle className="text-xs sm:text-sm">
{testResult.status === "success" ? "Connection Successful" : "Connection Failed"} {testResult.status === "success"
? "Connection Successful"
: "Connection Failed"}
</AlertTitle> </AlertTitle>
{testResult.tools.length > 0 && ( {testResult.tools.length > 0 && (
<Button <Button
@ -212,9 +214,7 @@ export const MCPConnectForm: FC<ConnectFormProps> = ({ onSubmit, isSubmitting })
{testResult.message} {testResult.message}
{showDetails && testResult.tools.length > 0 && ( {showDetails && testResult.tools.length > 0 && (
<div className="mt-3 pt-3 border-t border-green-500/20"> <div className="mt-3 pt-3 border-t border-green-500/20">
<p className="font-semibold mb-2 text-[10px] sm:text-xs"> <p className="font-semibold mb-2 text-[10px] sm:text-xs">Available tools:</p>
Available tools:
</p>
<ul className="list-disc list-inside text-[10px] sm:text-xs space-y-0.5"> <ul className="list-disc list-inside text-[10px] sm:text-xs space-y-0.5">
{testResult.tools.map((tool) => ( {testResult.tools.map((tool) => (
<li key={tool.name}>{tool.name}</li> <li key={tool.name}>{tool.name}</li>
@ -230,4 +230,4 @@ export const MCPConnectForm: FC<ConnectFormProps> = ({ onSubmit, isSubmitting })
</form> </form>
</div> </div>
); );
}; };

View file

@ -34,7 +34,7 @@ export const MCPConfig: FC<MCPConfigProps> = ({ connector, onConfigChange, onNam
if (connector.name) { if (connector.name) {
setName(connector.name); setName(connector.name);
} }
const serverConfig = connector.config?.server_config as MCPServerConfig | undefined; const serverConfig = connector.config?.server_config as MCPServerConfig | undefined;
if (serverConfig) { if (serverConfig) {
// Convert server config to JSON string for editing (name is in separate field) // Convert server config to JSON string for editing (name is in separate field)
@ -50,17 +50,12 @@ export const MCPConfig: FC<MCPConfigProps> = ({ connector, onConfigChange, onNam
// Validate that this is an MCP connector (after hooks) // Validate that this is an MCP connector (after hooks)
if (connector.connector_type !== EnumConnectorName.MCP_CONNECTOR) { if (connector.connector_type !== EnumConnectorName.MCP_CONNECTOR) {
console.error( console.error("MCPConfig received non-MCP connector:", connector.connector_type);
"MCPConfig received non-MCP connector:",
connector.connector_type
);
return ( return (
<Alert className="border-red-500/50 bg-red-500/10"> <Alert className="border-red-500/50 bg-red-500/10">
<XCircle className="h-4 w-4 text-red-600" /> <XCircle className="h-4 w-4 text-red-600" />
<AlertTitle>Invalid Connector Type</AlertTitle> <AlertTitle>Invalid Connector Type</AlertTitle>
<AlertDescription> <AlertDescription>This component can only be used with MCP connectors.</AlertDescription>
This component can only be used with MCP connectors.
</AlertDescription>
</Alert> </Alert>
); );
} }
@ -87,10 +82,10 @@ export const MCPConfig: FC<MCPConfigProps> = ({ connector, onConfigChange, onNam
if (jsonError) { if (jsonError) {
setJsonError(null); setJsonError(null);
} }
// Use shared utility for validation and parsing (with caching) // Use shared utility for validation and parsing (with caching)
const result = parseMCPConfig(value); const result = parseMCPConfig(value);
if (result.config && onConfigChange) { if (result.config && onConfigChange) {
// Valid config - update parent immediately // Valid config - update parent immediately
onConfigChange({ server_config: result.config }); onConfigChange({ server_config: result.config });
@ -127,7 +122,9 @@ export const MCPConfig: FC<MCPConfigProps> = ({ connector, onConfigChange, onNam
{/* Server Name */} {/* Server Name */}
<div className="rounded-xl border border-border bg-slate-400/5 dark:bg-white/5 p-3 sm:p-6 space-y-3 sm:space-y-4"> <div className="rounded-xl border border-border bg-slate-400/5 dark:bg-white/5 p-3 sm:p-6 space-y-3 sm:space-y-4">
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="name" className="text-xs sm:text-sm">Server Name</Label> <Label htmlFor="name" className="text-xs sm:text-sm">
Server Name
</Label>
<Input <Input
id="name" id="name"
value={name} value={name}
@ -159,11 +156,10 @@ export const MCPConfig: FC<MCPConfigProps> = ({ connector, onConfigChange, onNam
rows={16} rows={16}
className={`font-mono text-xs ${jsonError ? "border-red-500" : ""}`} className={`font-mono text-xs ${jsonError ? "border-red-500" : ""}`}
/> />
{jsonError && ( {jsonError && <p className="text-xs text-red-500">JSON Error: {jsonError}</p>}
<p className="text-xs text-red-500">JSON Error: {jsonError}</p>
)}
<p className="text-[10px] sm:text-xs text-muted-foreground"> <p className="text-[10px] sm:text-xs text-muted-foreground">
Edit your MCP server configuration. Must include: name, command, args (optional), env (optional), transport (optional). Edit your MCP server configuration. Must include: name, command, args (optional), env
(optional), transport (optional).
</p> </p>
</div> </div>
@ -197,7 +193,9 @@ export const MCPConfig: FC<MCPConfigProps> = ({ connector, onConfigChange, onNam
<div className="flex-1"> <div className="flex-1">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-0"> <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-0">
<AlertTitle className="text-sm"> <AlertTitle className="text-sm">
{testResult.status === "success" ? "Connection Successful" : "Connection Failed"} {testResult.status === "success"
? "Connection Successful"
: "Connection Failed"}
</AlertTitle> </AlertTitle>
{testResult.tools.length > 0 && ( {testResult.tools.length > 0 && (
<Button <Button
@ -231,9 +229,7 @@ export const MCPConfig: FC<MCPConfigProps> = ({ connector, onConfigChange, onNam
{testResult.message} {testResult.message}
{showDetails && testResult.tools.length > 0 && ( {showDetails && testResult.tools.length > 0 && (
<div className="mt-3 pt-3 border-t border-green-500/20"> <div className="mt-3 pt-3 border-t border-green-500/20">
<p className="font-semibold mb-2"> <p className="font-semibold mb-2">Available tools:</p>
Available tools:
</p>
<ul className="list-disc list-inside text-xs space-y-0.5"> <ul className="list-disc list-inside text-xs space-y-0.5">
{testResult.tools.map((tool) => ( {testResult.tools.map((tool) => (
<li key={tool.name}>{tool.name}</li> <li key={tool.name}>{tool.name}</li>

View file

@ -99,7 +99,10 @@ export const ConnectorConnectView: FC<ConnectorConnectViewProps> = ({
</div> </div>
<div> <div>
<h2 className="text-xl sm:text-2xl font-semibold tracking-tight"> <h2 className="text-xl sm:text-2xl font-semibold tracking-tight">
Connect {connectorType === "MCP_CONNECTOR" ? "MCP Server" : getConnectorTypeDisplay(connectorType)} Connect{" "}
{connectorType === "MCP_CONNECTOR"
? "MCP Server"
: getConnectorTypeDisplay(connectorType)}
</h2> </h2>
<p className="text-xs sm:text-base text-muted-foreground mt-1"> <p className="text-xs sm:text-base text-muted-foreground mt-1">
Enter your connection details Enter your connection details
@ -139,7 +142,11 @@ export const ConnectorConnectView: FC<ConnectorConnectViewProps> = ({
Connecting Connecting
</> </>
) : ( ) : (
<>{connectorType === "MCP_CONNECTOR" ? "Connect" : `Connect ${getConnectorTypeDisplay(connectorType)}`}</> <>
{connectorType === "MCP_CONNECTOR"
? "Connect"
: `Connect ${getConnectorTypeDisplay(connectorType)}`}
</>
)} )}
</Button> </Button>
</div> </div>

View file

@ -151,7 +151,7 @@ export const ConnectorEditView: FC<ConnectorEditViewProps> = ({
</div> </div>
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<h2 className="text-xl sm:text-2xl font-semibold tracking-tight text-wrap whitespace-normal wrap-break-word"> <h2 className="text-xl sm:text-2xl font-semibold tracking-tight text-wrap whitespace-normal wrap-break-word">
{connector.name} {connector.name}
</h2> </h2>
<p className="text-xs sm:text-base text-muted-foreground mt-1"> <p className="text-xs sm:text-base text-muted-foreground mt-1">
Manage your connector settings and sync configuration Manage your connector settings and sync configuration
@ -200,7 +200,6 @@ export const ConnectorEditView: FC<ConnectorEditViewProps> = ({
onConfigChange={onConfigChange} onConfigChange={onConfigChange}
onNameChange={onNameChange} onNameChange={onNameChange}
searchSpaceId={searchSpaceId} searchSpaceId={searchSpaceId}
/> />
)} )}

View file

@ -540,18 +540,18 @@ export const useConnectorDialog = () => {
data: { data: {
...connectorData, ...connectorData,
connector_type: connectorData.connector_type as EnumConnectorName, connector_type: connectorData.connector_type as EnumConnectorName,
is_active: true, is_active: true,
next_scheduled_at: connectorData.next_scheduled_at as string | null, next_scheduled_at: connectorData.next_scheduled_at as string | null,
}, },
queryParams: { queryParams: {
search_space_id: searchSpaceId, search_space_id: searchSpaceId,
}, },
}); });
// Refetch connectors to get the new one // Refetch connectors to get the new one
const result = await refetchAllConnectors(); const result = await refetchAllConnectors();
if (result.data) { if (result.data) {
const connector = result.data.find( const connector = result.data.find(
(c: SearchSourceConnector) => c.id === newConnector.id (c: SearchSourceConnector) => c.id === newConnector.id
); );
if (connector) { if (connector) {
@ -644,34 +644,35 @@ export const useConnectorDialog = () => {
}, },
}); });
const successMessage = currentConnectorType === "MCP_CONNECTOR" const successMessage =
? `${connector.name} added successfully` currentConnectorType === "MCP_CONNECTOR"
: `${connectorTitle} connected and indexing started!`; ? `${connector.name} added successfully`
toast.success(successMessage, { : `${connectorTitle} connected and indexing started!`;
description: periodicEnabledForIndexing toast.success(successMessage, {
? `Periodic sync enabled every ${getFrequencyLabel(frequencyMinutesForIndexing)}.` description: periodicEnabledForIndexing
: "You can continue working while we sync your data.", ? `Periodic sync enabled every ${getFrequencyLabel(frequencyMinutesForIndexing)}.`
}); : "You can continue working while we sync your data.",
});
const url = new URL(window.location.href); const url = new URL(window.location.href);
url.searchParams.delete("modal"); url.searchParams.delete("modal");
url.searchParams.delete("tab"); url.searchParams.delete("tab");
url.searchParams.delete("view"); url.searchParams.delete("view");
url.searchParams.delete("connectorType"); url.searchParams.delete("connectorType");
router.replace(url.pathname + url.search, { scroll: false }); router.replace(url.pathname + url.search, { scroll: false });
// Clear indexing config state since we're not showing the view // Clear indexing config state since we're not showing the view
setIndexingConfig(null); setIndexingConfig(null);
setIndexingConnector(null); setIndexingConnector(null);
setIndexingConnectorConfig(null); setIndexingConnectorConfig(null);
// Invalidate queries to refresh data // Invalidate queries to refresh data
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: cacheKeys.logs.summary(Number(searchSpaceId)), queryKey: cacheKeys.logs.summary(Number(searchSpaceId)),
}); });
// Refresh connectors list // Refresh connectors list
await refetchAllConnectors(); await refetchAllConnectors();
} else { } else {
// Non-indexable connector // Non-indexable connector
// For Circleback, transition to edit view to show webhook URL // For Circleback, transition to edit view to show webhook URL
@ -708,9 +709,10 @@ export const useConnectorDialog = () => {
await refetchAllConnectors(); await refetchAllConnectors();
} else { } else {
// Other non-indexable connectors - just show success message and close // Other non-indexable connectors - just show success message and close
const successMessage = currentConnectorType === "MCP_CONNECTOR" const successMessage =
? `${connector.name} added successfully` currentConnectorType === "MCP_CONNECTOR"
: `${connectorTitle} connected successfully!`; ? `${connector.name} added successfully`
: `${connectorTitle} connected successfully!`;
toast.success(successMessage); toast.success(successMessage);
// Refresh connectors list before closing modal // Refresh connectors list before closing modal
@ -758,7 +760,7 @@ export const useConnectorDialog = () => {
const handleBackFromConnect = useCallback(() => { const handleBackFromConnect = useCallback(() => {
const url = new URL(window.location.href); const url = new URL(window.location.href);
url.searchParams.set("modal", "connectors"); url.searchParams.set("modal", "connectors");
// If we're connecting an MCP and came from list view, go back to list // If we're connecting an MCP and came from list view, go back to list
if (connectingConnectorType === "MCP_CONNECTOR" && viewingMCPList) { if (connectingConnectorType === "MCP_CONNECTOR" && viewingMCPList) {
url.searchParams.set("view", "mcp-list"); url.searchParams.set("view", "mcp-list");
@ -766,7 +768,7 @@ export const useConnectorDialog = () => {
url.searchParams.set("tab", "all"); url.searchParams.set("tab", "all");
url.searchParams.delete("view"); url.searchParams.delete("view");
} }
url.searchParams.delete("connectorType"); url.searchParams.delete("connectorType");
router.replace(url.pathname + url.search, { scroll: false }); router.replace(url.pathname + url.search, { scroll: false });
}, [router, connectingConnectorType, viewingMCPList]); }, [router, connectingConnectorType, viewingMCPList]);
@ -1252,33 +1254,33 @@ export const useConnectorDialog = () => {
); );
} }
// Generate toast message based on connector type // Generate toast message based on connector type
const toastTitle = `${editingConnector.name} updated successfully`; const toastTitle = `${editingConnector.name} updated successfully`;
toast.success(toastTitle, { toast.success(toastTitle, {
description: periodicEnabled description: periodicEnabled
? `Periodic sync ${frequency ? `enabled every ${getFrequencyLabel(frequencyMinutes)}` : "enabled"}. ${indexingDescription}` ? `Periodic sync ${frequency ? `enabled every ${getFrequencyLabel(frequencyMinutes)}` : "enabled"}. ${indexingDescription}`
: indexingDescription, : indexingDescription,
}); });
// Update URL - the effect will handle closing the modal and clearing state // Update URL - the effect will handle closing the modal and clearing state
const url = new URL(window.location.href); const url = new URL(window.location.href);
url.searchParams.delete("modal"); url.searchParams.delete("modal");
url.searchParams.delete("tab"); url.searchParams.delete("tab");
url.searchParams.delete("view"); url.searchParams.delete("view");
url.searchParams.delete("connectorId"); url.searchParams.delete("connectorId");
router.replace(url.pathname + url.search, { scroll: false }); router.replace(url.pathname + url.search, { scroll: false });
refreshConnectors(); refreshConnectors();
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: cacheKeys.logs.summary(Number(searchSpaceId)), queryKey: cacheKeys.logs.summary(Number(searchSpaceId)),
}); });
} catch (error) { } catch (error) {
console.error("Error saving connector:", error); console.error("Error saving connector:", error);
toast.error("Failed to save connector changes"); toast.error("Failed to save connector changes");
} finally { } finally {
setIsSaving(false); setIsSaving(false);
} }
}, },
[ [
editingConnector, editingConnector,

View file

@ -96,9 +96,7 @@ export const ActiveConnectorsTab: FC<ActiveConnectorsTabProps> = ({
// Separate OAuth and non-OAuth connectors // Separate OAuth and non-OAuth connectors
const oauthConnectors = connectors.filter((c) => oauthConnectorTypes.has(c.connector_type)); const oauthConnectors = connectors.filter((c) => oauthConnectorTypes.has(c.connector_type));
const nonOauthConnectors = connectors.filter( const nonOauthConnectors = connectors.filter((c) => !oauthConnectorTypes.has(c.connector_type));
(c) => !oauthConnectorTypes.has(c.connector_type)
);
// Group OAuth connectors by type // Group OAuth connectors by type
const oauthConnectorsByType = oauthConnectors.reduce( const oauthConnectorsByType = oauthConnectors.reduce(
@ -150,8 +148,7 @@ export const ActiveConnectorsTab: FC<ActiveConnectorsTabProps> = ({
}); });
const hasActiveConnectors = const hasActiveConnectors =
filteredOAuthConnectorTypes.length > 0 || filteredOAuthConnectorTypes.length > 0 || filteredNonOAuthConnectors.length > 0;
filteredNonOAuthConnectors.length > 0;
return ( return (
<TabsContent value="active" className="m-0"> <TabsContent value="active" className="m-0">

View file

@ -123,7 +123,6 @@ export const AllConnectorsTab: FC<AllConnectorsTabProps> = ({
isConnecting={isConnecting} isConnecting={isConnecting}
documentCount={documentCount} documentCount={documentCount}
accountCount={accountCount} accountCount={accountCount}
isIndexing={isIndexing} isIndexing={isIndexing}
onConnect={() => onConnectOAuth(connector)} onConnect={() => onConnectOAuth(connector)}
onManage={ onManage={
@ -165,9 +164,13 @@ export const AllConnectorsTab: FC<AllConnectorsTabProps> = ({
// For MCP connectors, count total MCP connectors instead of document count // For MCP connectors, count total MCP connectors instead of document count
const isMCP = connector.connectorType === EnumConnectorName.MCP_CONNECTOR; const isMCP = connector.connectorType === EnumConnectorName.MCP_CONNECTOR;
const mcpConnectorCount = isMCP && allConnectors const mcpConnectorCount =
? allConnectors.filter((c: SearchSourceConnector) => c.connector_type === EnumConnectorName.MCP_CONNECTOR).length isMCP && allConnectors
: undefined; ? allConnectors.filter(
(c: SearchSourceConnector) =>
c.connector_type === EnumConnectorName.MCP_CONNECTOR
).length
: undefined;
const handleConnect = onConnectNonOAuth const handleConnect = onConnectNonOAuth
? () => onConnectNonOAuth(connector.connectorType) ? () => onConnectNonOAuth(connector.connectorType)

View file

@ -1,14 +1,14 @@
/** /**
* MCP Configuration Validator Utility * MCP Configuration Validator Utility
* *
* Shared validation and parsing logic for MCP (Model Context Protocol) server configurations. * Shared validation and parsing logic for MCP (Model Context Protocol) server configurations.
* *
* Features: * Features:
* - Zod schema validation for runtime type safety * - Zod schema validation for runtime type safety
* - Configuration caching to avoid repeated parsing (5-minute TTL) * - Configuration caching to avoid repeated parsing (5-minute TTL)
* - Standardized error messages * - Standardized error messages
* - Connection testing utilities * - Connection testing utilities
* *
* Usage: * Usage:
* ```typescript * ```typescript
* // Parse and validate config * // Parse and validate config
@ -18,14 +18,14 @@
* } else { * } else {
* // Show result.error to user * // Show result.error to user
* } * }
* *
* // Test connection * // Test connection
* const testResult = await testMCPConnection(config); * const testResult = await testMCPConnection(config);
* if (testResult.status === "success") { * if (testResult.status === "success") {
* console.log(`Found ${testResult.tools.length} tools`); * console.log(`Found ${testResult.tools.length} tools`);
* } * }
* ``` * ```
* *
* @module mcp-config-validator * @module mcp-config-validator
*/ */
@ -36,7 +36,7 @@ import { connectorsApiService } from "@/lib/apis/connectors-api.service";
/** /**
* Zod schema for MCP server configuration * Zod schema for MCP server configuration
* Provides compile-time and runtime type safety * Provides compile-time and runtime type safety
* *
* Exported for advanced use cases (e.g., form builders) * Exported for advanced use cases (e.g., form builders)
*/ */
export const MCPServerConfigSchema = z.object({ export const MCPServerConfigSchema = z.object({
@ -95,11 +95,11 @@ export const parseMCPConfig = (configJson: string): MCPConfigValidationResult =>
// Check cache first // Check cache first
const cached = configCache.get(configJson); const cached = configCache.get(configJson);
if (cached && Date.now() - cached.timestamp < CACHE_TTL) { if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
console.log('[MCP Validator] ✅ Using cached config'); console.log("[MCP Validator] ✅ Using cached config");
return { config: cached.config, error: null }; return { config: cached.config, error: null };
} }
console.log('[MCP Validator] 🔍 Parsing new config...'); console.log("[MCP Validator] 🔍 Parsing new config...");
// Clean up expired cache entries periodically // Clean up expired cache entries periodically
if (configCache.size > 100) { if (configCache.size > 100) {
@ -111,7 +111,7 @@ export const parseMCPConfig = (configJson: string): MCPConfigValidationResult =>
// Validate that it's an object, not an array // Validate that it's an object, not an array
if (Array.isArray(parsed)) { if (Array.isArray(parsed)) {
console.error('[MCP Validator] ❌ Error: Config is an array, expected object'); console.error("[MCP Validator] ❌ Error: Config is an array, expected object");
return { return {
config: null, config: null,
error: "Please provide a single server configuration object, not an array", error: "Please provide a single server configuration object, not an array",
@ -125,27 +125,23 @@ export const parseMCPConfig = (configJson: string): MCPConfigValidationResult =>
// Format Zod validation errors for user-friendly display // Format Zod validation errors for user-friendly display
const firstError = result.error.issues[0]; const firstError = result.error.issues[0];
const fieldPath = firstError.path.join("."); const fieldPath = firstError.path.join(".");
// Clean up error message - remove technical Zod jargon // Clean up error message - remove technical Zod jargon
let errorMsg = firstError.message; let errorMsg = firstError.message;
// Replace technical error messages with user-friendly ones // Replace technical error messages with user-friendly ones
if (errorMsg.includes("expected string, received undefined")) { if (errorMsg.includes("expected string, received undefined")) {
errorMsg = fieldPath errorMsg = fieldPath ? `The '${fieldPath}' field is required` : "This field is required";
? `The '${fieldPath}' field is required`
: "This field is required";
} else if (errorMsg.includes("Invalid input")) { } else if (errorMsg.includes("Invalid input")) {
errorMsg = fieldPath errorMsg = fieldPath ? `The '${fieldPath}' field has an invalid value` : "Invalid value";
? `The '${fieldPath}' field has an invalid value`
: "Invalid value";
} else if (fieldPath && !errorMsg.toLowerCase().includes(fieldPath.toLowerCase())) { } else if (fieldPath && !errorMsg.toLowerCase().includes(fieldPath.toLowerCase())) {
// If error message doesn't mention the field name, prepend it // If error message doesn't mention the field name, prepend it
errorMsg = `The '${fieldPath}' field: ${errorMsg}`; errorMsg = `The '${fieldPath}' field: ${errorMsg}`;
} }
console.error('[MCP Validator] ❌ Validation error:', errorMsg); console.error("[MCP Validator] ❌ Validation error:", errorMsg);
console.error('[MCP Validator] Full Zod errors:', result.error.issues); console.error("[MCP Validator] Full Zod errors:", result.error.issues);
return { return {
config: null, config: null,
error: errorMsg, error: errorMsg,
@ -164,8 +160,8 @@ export const parseMCPConfig = (configJson: string): MCPConfigValidationResult =>
config, config,
timestamp: Date.now(), timestamp: Date.now(),
}); });
console.log('[MCP Validator] ✅ Config parsed successfully:', config); console.log("[MCP Validator] ✅ Config parsed successfully:", config);
return { return {
config, config,
@ -173,7 +169,7 @@ export const parseMCPConfig = (configJson: string): MCPConfigValidationResult =>
}; };
} catch (error) { } catch (error) {
const errorMsg = error instanceof Error ? error.message : "Invalid JSON"; const errorMsg = error instanceof Error ? error.message : "Invalid JSON";
console.error('[MCP Validator] ❌ JSON parse error:', errorMsg); console.error("[MCP Validator] ❌ JSON parse error:", errorMsg);
return { return {
config: null, config: null,
error: errorMsg, error: errorMsg,
@ -222,11 +218,11 @@ export const testMCPConnection = async (
export const extractServerName = (configJson: string): string => { export const extractServerName = (configJson: string): string => {
try { try {
const parsed = JSON.parse(configJson); const parsed = JSON.parse(configJson);
// Use Zod to validate and extract name field safely // Use Zod to validate and extract name field safely
const nameSchema = z.object({ name: z.string().optional() }); const nameSchema = z.object({ name: z.string().optional() });
const result = nameSchema.safeParse(parsed); const result = nameSchema.safeParse(parsed);
if (result.success && result.data.name) { if (result.success && result.data.name) {
return result.data.name; return result.data.name;
} }

View file

@ -82,11 +82,13 @@ export const ConnectorAccountsListView: FC<ConnectorAccountsListViewProps> = ({
// Filter connectors to only show those of this type // Filter connectors to only show those of this type
const typeConnectors = connectors.filter((c) => c.connector_type === connectorType); const typeConnectors = connectors.filter((c) => c.connector_type === connectorType);
// Determine button text - default to "Add Account" unless specified // Determine button text - default to "Add Account" unless specified
const buttonText = addButtonText || (connectorType === EnumConnectorName.MCP_CONNECTOR ? "Add New MCP Server" : "Add Account"); const buttonText =
addButtonText ||
(connectorType === EnumConnectorName.MCP_CONNECTOR ? "Add New MCP Server" : "Add Account");
const isMCP = connectorType === EnumConnectorName.MCP_CONNECTOR; const isMCP = connectorType === EnumConnectorName.MCP_CONNECTOR;
// Helper to get display name for connector (handles MCP server name extraction) // Helper to get display name for connector (handles MCP server name extraction)
const getDisplayName = (connector: SearchSourceConnector): string => { const getDisplayName = (connector: SearchSourceConnector): string => {
if (isMCP) { if (isMCP) {
@ -177,58 +179,58 @@ export const ConnectorAccountsListView: FC<ConnectorAccountsListViewProps> = ({
) : ( ) : (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3"> <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
{typeConnectors.map((connector) => { {typeConnectors.map((connector) => {
const isIndexing = indexingConnectorIds.has(connector.id); const isIndexing = indexingConnectorIds.has(connector.id);
return ( return (
<div
key={connector.id}
className={cn(
"flex items-center gap-4 p-4 rounded-xl transition-all",
isIndexing
? "bg-primary/5 border-0"
: "bg-slate-400/5 dark:bg-white/5 hover:bg-slate-400/10 dark:hover:bg-white/10 border border-border"
)}
>
<div <div
key={connector.id}
className={cn( className={cn(
"flex h-12 w-12 items-center justify-center rounded-lg border shrink-0", "flex items-center gap-4 p-4 rounded-xl transition-all",
isIndexing isIndexing
? "bg-primary/10 border-primary/20" ? "bg-primary/5 border-0"
: "bg-slate-400/5 dark:bg-white/5 border-slate-400/5 dark:border-white/5" : "bg-slate-400/5 dark:bg-white/5 hover:bg-slate-400/10 dark:hover:bg-white/10 border border-border"
)} )}
> >
{getConnectorIcon(connector.connector_type, "size-6")} <div
</div> className={cn(
<div className="flex-1 min-w-0"> "flex h-12 w-12 items-center justify-center rounded-lg border shrink-0",
<p className="text-[14px] font-semibold leading-tight truncate"> isIndexing
{getDisplayName(connector)} ? "bg-primary/10 border-primary/20"
</p> : "bg-slate-400/5 dark:bg-white/5 border-slate-400/5 dark:border-white/5"
{isIndexing ? ( )}
<p className="text-[11px] text-primary mt-1 flex items-center gap-1.5"> >
<Loader2 className="size-3 animate-spin" /> {getConnectorIcon(connector.connector_type, "size-6")}
Syncing </div>
<div className="flex-1 min-w-0">
<p className="text-[14px] font-semibold leading-tight truncate">
{getDisplayName(connector)}
</p> </p>
) : ( {isIndexing ? (
<p className="text-[10px] text-muted-foreground mt-1 whitespace-nowrap truncate"> <p className="text-[11px] text-primary mt-1 flex items-center gap-1.5">
{isIndexableConnector(connector.connector_type) <Loader2 className="size-3 animate-spin" />
? connector.last_indexed_at Syncing
? `Last indexed: ${formatLastIndexedDate(connector.last_indexed_at)}` </p>
: "Never indexed" ) : (
: "Active"} <p className="text-[10px] text-muted-foreground mt-1 whitespace-nowrap truncate">
</p> {isIndexableConnector(connector.connector_type)
)} ? connector.last_indexed_at
? `Last indexed: ${formatLastIndexedDate(connector.last_indexed_at)}`
: "Never indexed"
: "Active"}
</p>
)}
</div>
<Button
variant="secondary"
size="sm"
className="h-8 text-[11px] px-3 rounded-lg font-medium bg-white text-slate-700 hover:bg-slate-50 border-0 shadow-xs dark:bg-secondary dark:text-secondary-foreground dark:hover:bg-secondary/80 shrink-0"
onClick={() => onManage(connector)}
>
Manage
</Button>
</div> </div>
<Button );
variant="secondary" })}
size="sm"
className="h-8 text-[11px] px-3 rounded-lg font-medium bg-white text-slate-700 hover:bg-slate-50 border-0 shadow-xs dark:bg-secondary dark:text-secondary-foreground dark:hover:bg-secondary/80 shrink-0"
onClick={() => onManage(connector)}
>
Manage
</Button>
</div>
);
})}
</div> </div>
)} )}
</div> </div>

View file

@ -267,9 +267,13 @@ class ConnectorsApiService {
search_space_id: String(queryParams.search_space_id), search_space_id: String(queryParams.search_space_id),
}).toString(); }).toString();
return baseApiService.post<MCPConnectorRead>(`/api/v1/connectors/mcp?${queryString}`, undefined, { return baseApiService.post<MCPConnectorRead>(
body: data, `/api/v1/connectors/mcp?${queryString}`,
}); undefined,
{
body: data,
}
);
}; };
/** /**