Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion client/src/components/ServersTab.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useState } from "react";
import { Card } from "./ui/card";
import { Button } from "./ui/button";
import { Plus, Database,FileText } from "lucide-react";
import { Plus, Database, FileText } from "lucide-react";
import { ServerWithName } from "@/hooks/use-app-state";
import { ServerConnectionCard } from "./connection/ServerConnectionCard";
import { ServerModal } from "./connection/ServerModal";
Expand Down
30 changes: 19 additions & 11 deletions client/src/components/connection/JsonImportModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ export function JsonImportModal({
onImport,
}: JsonImportModalProps) {
const [jsonContent, setJsonContent] = useState("");
const [validationResult, setValidationResult] = useState<{ success: boolean; error?: string } | null>(null);
const [validationResult, setValidationResult] = useState<{
success: boolean;
error?: string;
} | null>(null);
const [isImporting, setIsImporting] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);

Expand Down Expand Up @@ -74,10 +77,13 @@ export function JsonImportModal({
}

onImport(servers);
toast.success(`Successfully imported ${servers.length} server${servers.length === 1 ? '' : 's'}`);
toast.success(
`Successfully imported ${servers.length} server${servers.length === 1 ? "" : "s"}`,
);
handleClose();
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error";
const errorMessage =
error instanceof Error ? error.message : "Unknown error";
toast.error(`Failed to import servers: ${errorMessage}`);
} finally {
setIsImporting(false);
Expand All @@ -91,7 +97,6 @@ export function JsonImportModal({
onClose();
};


const getValidationIcon = () => {
if (!validationResult) return null;
return validationResult.success ? (
Expand All @@ -104,9 +109,13 @@ export function JsonImportModal({
const getValidationMessage = () => {
if (!validationResult) return null;
return validationResult.success ? (
<span className="text-green-600 dark:text-green-400">Valid JSON config</span>
<span className="text-green-600 dark:text-green-400">
Valid JSON config
</span>
) : (
<span className="text-red-600 dark:text-red-400">{validationResult.error}</span>
<span className="text-red-600 dark:text-red-400">
{validationResult.error}
</span>
);
};

Expand All @@ -115,7 +124,8 @@ export function JsonImportModal({
<DialogContent className="max-w-2xl max-h-[80vh] overflow-hidden flex flex-col">
<DialogHeader className="space-y-2">
<DialogTitle className="flex text-xl font-semibold">
<img src="/mcp.svg" alt="MCP" className="mr-2" /> Import Servers from JSON
<img src="/mcp.svg" alt="MCP" className="mr-2" /> Import Servers
from JSON
</DialogTitle>
</DialogHeader>

Expand Down Expand Up @@ -167,7 +177,7 @@ export function JsonImportModal({
<div className="space-y-2">
<h4 className="text-sm font-medium">Example JSON Format:</h4>
<pre className="text-xs text-muted-foreground overflow-x-auto">
{`{
{`{
"mcpServers": {
"weather": {
"command": "/path/to/node",
Expand All @@ -187,9 +197,7 @@ export function JsonImportModal({
{validationResult && !validationResult.success && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>
{validationResult.error}
</AlertDescription>
<AlertDescription>{validationResult.error}</AlertDescription>
</Alert>
)}
</div>
Expand Down
106 changes: 88 additions & 18 deletions client/src/hooks/use-app-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,26 +314,96 @@ export function useAppState() {
[appState.servers, logger],
);

// Auto-connect to CLI-provided MCP server on mount
// CLI config processing guard
const cliConfigProcessedRef = useRef<boolean>(false);

// Auto-connect to CLI-provided MCP server(s) on mount
useEffect(() => {
if (!isLoading) {
const windowCliConfig = (window as any).MCP_CLI_CONFIG;
if (windowCliConfig && windowCliConfig.command) {
logger.info(
"Auto-connecting to CLI-provided MCP server (from window)",
{ cliConfig: windowCliConfig },
);
const formData: ServerFormData = {
name: windowCliConfig.name || "CLI Server",
type: "stdio" as const,
command: windowCliConfig.command,
args: windowCliConfig.args || [],
};
handleConnect(formData);
return;
}
if (!isLoading && !cliConfigProcessedRef.current) {
cliConfigProcessedRef.current = true;
// Fetch CLI config from API (both dev and production)
fetch("/api/mcp-cli-config")
.then((response) => response.json())
.then((data) => {
const cliConfig = data.config;
if (cliConfig) {
// Handle multiple servers from config file
if (cliConfig.servers && Array.isArray(cliConfig.servers)) {
const autoConnectServer = cliConfig.autoConnectServer;

logger.info(
"Processing CLI-provided MCP servers (from config file)",
{
serverCount: cliConfig.servers.length,
autoConnectServer: autoConnectServer || "all",
cliConfig: cliConfig,
},
);

// Add all servers to the UI, but only auto-connect to filtered ones
cliConfig.servers.forEach((server: any) => {
const formData: ServerFormData = {
name: server.name || "CLI Server",
type: (server.type === "sse"
? "http"
: server.type || "stdio") as "stdio" | "http",
command: server.command,
args: server.args || [],
url: server.url,
env: server.env || {},
};

// Always add/update server from CLI config
const mcpConfig = toMCPConfig(formData);
dispatch({
type: "UPSERT_SERVER",
name: formData.name,
server: {
name: formData.name,
config: mcpConfig,
lastConnectionTime: new Date(),
connectionStatus: "disconnected" as const,
retryCount: 0,
enabled: false, // Start disabled, will enable on successful connection
},
});

// Only auto-connect if matches filter (or no filter)
if (!autoConnectServer || server.name === autoConnectServer) {
logger.info("Auto-connecting to server", {
serverName: server.name,
});
handleConnect(formData);
} else {
logger.info("Skipping auto-connect for server", {
serverName: server.name,
reason: "filtered out",
});
}
});
return;
}
// Handle legacy single server mode
if (cliConfig.command) {
logger.info("Auto-connecting to CLI-provided MCP server", {
cliConfig,
});
const formData: ServerFormData = {
name: cliConfig.name || "CLI Server",
type: "stdio" as const,
command: cliConfig.command,
args: cliConfig.args || [],
env: cliConfig.env || {},
};
handleConnect(formData);
}
}
})
.catch((error) => {
logger.debug("Could not fetch CLI config from API", { error });
});
}
}, [isLoading, handleConnect, logger]);
}, [isLoading, handleConnect, logger, appState.servers]);

const getValidAccessToken = useCallback(
async (serverName: string): Promise<string | null> => {
Expand Down
79 changes: 51 additions & 28 deletions client/src/lib/json-config-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,25 @@ export interface JsonConfig {
export function parseJsonConfig(jsonContent: string): ServerFormData[] {
try {
const config: JsonConfig = JSON.parse(jsonContent);

if (!config.mcpServers || typeof config.mcpServers !== 'object') {
throw new Error('Invalid JSON config: missing or invalid "mcpServers" property');

if (!config.mcpServers || typeof config.mcpServers !== "object") {
throw new Error(
'Invalid JSON config: missing or invalid "mcpServers" property',
);
}

const servers: ServerFormData[] = [];

for (const [serverName, serverConfig] of Object.entries(config.mcpServers)) {
if (!serverConfig || typeof serverConfig !== 'object') {
for (const [serverName, serverConfig] of Object.entries(
config.mcpServers,
)) {
if (!serverConfig || typeof serverConfig !== "object") {
console.warn(`Skipping invalid server config for "${serverName}"`);
continue;
}

// Determine server type based on config
if (serverConfig.type === 'sse' || serverConfig.url) {
if (serverConfig.type === "sse" || serverConfig.url) {
// HTTP/SSE server
servers.push({
name: serverName,
Expand All @@ -54,15 +58,17 @@ export function parseJsonConfig(jsonContent: string): ServerFormData[] {
env: serverConfig.env || {},
});
} else {
console.warn(`Skipping server "${serverName}": missing required command`);
console.warn(
`Skipping server "${serverName}": missing required command`,
);
continue;
}
}

return servers;
} catch (error) {
if (error instanceof SyntaxError) {
throw new Error('Invalid JSON format: ' + error.message);
throw new Error("Invalid JSON format: " + error.message);
}
throw error;
}
Expand All @@ -73,51 +79,68 @@ export function parseJsonConfig(jsonContent: string): ServerFormData[] {
* @param jsonContent - The JSON string content
* @returns Validation result with success status and error message
*/
export function validateJsonConfig(jsonContent: string): { success: boolean; error?: string } {
export function validateJsonConfig(jsonContent: string): {
success: boolean;
error?: string;
} {
try {
const config = JSON.parse(jsonContent);

if (!config.mcpServers || typeof config.mcpServers !== 'object') {
return { success: false, error: 'Missing or invalid "mcpServers" property' };

if (!config.mcpServers || typeof config.mcpServers !== "object") {
return {
success: false,
error: 'Missing or invalid "mcpServers" property',
};
}

const serverNames = Object.keys(config.mcpServers);
if (serverNames.length === 0) {
return { success: false, error: 'No servers found in "mcpServers" object' };
return {
success: false,
error: 'No servers found in "mcpServers" object',
};
}

// Validate each server config
for (const [serverName, serverConfig] of Object.entries(config.mcpServers)) {
if (!serverConfig || typeof serverConfig !== 'object') {
return { success: false, error: `Invalid server config for "${serverName}"` };
for (const [serverName, serverConfig] of Object.entries(
config.mcpServers,
)) {
if (!serverConfig || typeof serverConfig !== "object") {
return {
success: false,
error: `Invalid server config for "${serverName}"`,
};
}

const configObj = serverConfig as JsonServerConfig;
const hasCommand = configObj.command && typeof configObj.command === 'string';
const hasUrl = configObj.url && typeof configObj.url === 'string';
const isSse = configObj.type === 'sse';
const hasCommand =
configObj.command && typeof configObj.command === "string";
const hasUrl = configObj.url && typeof configObj.url === "string";
const isSse = configObj.type === "sse";

if (!hasCommand && !hasUrl && !isSse) {
return {
success: false,
error: `Server "${serverName}" must have either "command" or "url" property`
return {
success: false,
error: `Server "${serverName}" must have either "command" or "url" property`,
};
}

if (hasCommand && hasUrl) {
return {
success: false,
error: `Server "${serverName}" cannot have both "command" and "url" properties`
return {
success: false,
error: `Server "${serverName}" cannot have both "command" and "url" properties`,
};
}
}

return { success: true };
} catch (error) {
if (error instanceof SyntaxError) {
return { success: false, error: 'Invalid JSON format: ' + error.message };
return { success: false, error: "Invalid JSON format: " + error.message };
}
return { success: false, error: 'Unknown error: ' + (error as Error).message };
return {
success: false,
error: "Unknown error: " + (error as Error).message,
};
}
}

2 changes: 2 additions & 0 deletions server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,11 @@ function getMCPConfigFromEnv() {
const servers = Object.entries(config.mcpServers).map(
([name, serverConfig]: [string, any]) => ({
name,
type: serverConfig.type || "stdio", // Default to stdio if not specified
command: serverConfig.command,
args: serverConfig.args || [],
env: serverConfig.env || {},
url: serverConfig.url, // For SSE/HTTP connections
}),
);
console.log("Transformed servers:", servers);
Expand Down