Thursday, November 26, 2026

BUILDING AN INTELLIGENT MCP HUB EXPLORER: DISCOVERING AND TESTING MCP SERVERS

 


INTRODUCTION TO THE MODEL CONTEXT PROTOCOL ECOSYSTEM

The Model Context Protocol, developed by Anthropic, represents a significant advancement in how large language models interact with external tools and data sources. At its core, MCP establishes a standardized communication framework that allows AI assistants to seamlessly connect with various services, databases, and applications. This protocol has given rise to an ecosystem of MCP servers, each offering specialized capabilities ranging from file system access to API integrations with popular services.

As the MCP ecosystem grows, developers and AI enthusiasts face a new challenge: discovering, evaluating, and testing the multitude of available MCP servers. Multiple organizations, including Anthropic and GitHub, have established MCP hubs that catalog these servers, but navigating through these repositories can be cumbersome without proper tooling. This article presents a comprehensive approach to building a sophisticated web-based application that addresses this need by providing an intuitive interface for exploring MCP hubs, discovering servers, and testing their capabilities in real-time.

The application we will design combines several key functionalities. It maintains connections to multiple MCP hubs through a configuration-driven architecture, presents servers in a familiar file-explorer interface, allows users to test tools provided by each server, and maintains a personalized list of favorite servers. Throughout this journey, we will examine the technical architecture, implementation details, and best practices for creating such a system.

UNDERSTANDING THE ARCHITECTURAL FOUNDATION

Before diving into implementation details, we must establish a clear understanding of the system architecture. Our web-based MCP Hub Explorer consists of several interconnected layers, each serving a distinct purpose while maintaining loose coupling for flexibility and maintainability.

The presentation layer forms the user-facing component, implemented as a modern single-page application running entirely in the browser. This layer handles all user interactions, from browsing hub directories to invoking MCP server tools. It communicates with the application backend through a well-defined API, ensuring separation of concerns and enabling potential future expansion to mobile or desktop clients.

The application backend serves as the orchestration layer, managing connections to multiple MCP hubs, maintaining the configuration state, and coordinating tool invocations. This layer implements the MCP client protocol, establishing and maintaining connections to various MCP servers as users explore and test them. It also handles credential management, ensuring secure storage and transmission of authentication information when required by specific servers.

The persistence layer manages the configuration file and user preferences. Our implementation uses browser localStorage for configuration storage, making it accessible to the client-side code while maintaining persistence across sessions. This layer abstracts storage operations, providing a clean interface for reading and updating hub configurations, server favorites, and cached metadata.

Let us examine the configuration structure that drives the entire system:

const defaultConfiguration = {
  version: "1.0",
  hubs: [
    {
      id: "anthropic-official",
      name: "Anthropic MCP Hub",
      url: "https://mcp.anthropic.com/hub",
      description: "Official Anthropic Model Context Protocol server registry",
      authentication: {
        type: "none"
      },
      enabled: true,
      lastSync: null
    },
    {
      id: "github-mcp",
      name: "GitHub MCP Servers",
      url: "https://api.github.com/mcp-servers",
      description: "Community-contributed MCP servers from GitHub",
      authentication: {
        type: "bearer",
        tokenKey: "GITHUB_TOKEN"
      },
      enabled: true,
      lastSync: null
    }
  ],
  favorites: [],
  settings: {
    autoSync: true,
    syncInterval: 3600000,
    defaultTimeout: 30000,
    maxConcurrentConnections: 5,
    apiTokens: {}
  }
};

This configuration structure provides the foundation for our application. Each hub entry contains essential connection information including the endpoint URL, authentication requirements, and hub-specific metadata. The favorites array maintains a lightweight reference to user-selected servers, storing only the identifiers needed to retrieve full server information on demand. User interface preferences allow customization of the browsing experience while maintaining these settings across sessions.

IMPLEMENTING THE STORAGE LAYER

Since we are building a web-based application that runs in the browser, we need a storage solution that works in that environment. We will use localStorage for persistence, with a clean abstraction layer that could be swapped for IndexedDB or a backend API in the future.

class StorageService {
  constructor(storageKey = 'mcp_hub_explorer_config') {
    this.storageKey = storageKey;
    this.cache = null;
  }

  /**
   * Reads data from localStorage and parses it.
   * Returns null if no data exists or if parsing fails.
   */
  read() {
    try {
      const data = localStorage.getItem(this.storageKey);
      if (!data) {
        return null;
      }
      this.cache = JSON.parse(data);
      return this.cache;
    } catch (error) {
      console.error('Failed to read from storage:', error);
      return null;
    }
  }

  /**
   * Writes data to localStorage after stringifying it.
   * Handles quota exceeded errors gracefully.
   */
  write(data) {
    try {
      const jsonString = JSON.stringify(data, null, 2);
      localStorage.setItem(this.storageKey, jsonString);
      this.cache = data;
      return true;
    } catch (error) {
      if (error.name === 'QuotaExceededError') {
        console.error('Storage quota exceeded');
        alert('Storage quota exceeded. Please clear some data.');
      } else {
        console.error('Failed to write to storage:', error);
      }
      return false;
    }
  }

  /**
   * Clears all stored data.
   */
  clear() {
    try {
      localStorage.removeItem(this.storageKey);
      this.cache = null;
      return true;
    } catch (error) {
      console.error('Failed to clear storage:', error);
      return false;
    }
  }

  /**
   * Checks if storage is available in the browser.
   */
  static isAvailable() {
    try {
      const test = '__storage_test__';
      localStorage.setItem(test, test);
      localStorage.removeItem(test);
      return true;
    } catch (error) {
      return false;
    }
  }
}

The StorageService class provides a clean abstraction over localStorage. It handles JSON serialization and deserialization, manages errors gracefully, and provides a simple interface for the rest of the application. The isAvailable static method allows us to detect whether localStorage is supported in the current browser environment.

IMPLEMENTING THE CONFIGURATION MANAGER

With our storage layer in place, we can now build the configuration manager that handles loading, saving, and updating the configuration. This manager will use the StorageService and provide a higher-level interface for configuration operations.

class ConfigurationManager {
  constructor() {
    this.storage = new StorageService('mcp_hub_explorer_config');
    this.config = null;
    this.watchers = [];
    this.saveDebounceTimer = null;
    this.saveDebounceDelay = 500;
  }

  /**
   * Initializes the configuration manager by loading existing config
   * or creating a default one if none exists.
   */
  async initialize() {
    if (!StorageService.isAvailable()) {
      throw new Error('localStorage is not available in this browser');
    }

    const storedConfig = this.storage.read();
    
    if (storedConfig) {
      this.config = this.validateAndMerge(storedConfig);
    } else {
      console.log('No existing configuration found, creating default');
      this.config = JSON.parse(JSON.stringify(defaultConfiguration));
      this.storage.write(this.config);
    }

    return this.config;
  }

  /**
   * Validates loaded configuration and merges with defaults
   * to ensure all required fields exist.
   */
  validateAndMerge(loadedConfig) {
    const merged = {
      version: loadedConfig.version || defaultConfiguration.version,
      hubs: Array.isArray(loadedConfig.hubs) ? loadedConfig.hubs : [],
      favorites: Array.isArray(loadedConfig.favorites) ? loadedConfig.favorites : [],
      settings: {
        ...defaultConfiguration.settings,
        ...(loadedConfig.settings || {})
      }
    };

    merged.hubs = merged.hubs.filter(hub => {
      if (!hub.id || !hub.url) {
        console.warn('Invalid hub entry found, skipping:', hub);
        return false;
      }
      
      if (!hub.authentication) {
        hub.authentication = { type: 'none' };
      }
      
      return true;
    });

    return merged;
  }

  /**
   * Saves the current configuration to storage.
   * Debounced to prevent excessive writes.
   */
  save() {
    return new Promise((resolve, reject) => {
      if (this.saveDebounceTimer) {
        clearTimeout(this.saveDebounceTimer);
      }

      this.saveDebounceTimer = setTimeout(() => {
        try {
          const success = this.storage.write(this.config);
          if (success) {
            this.notifyWatchers('configSaved', this.config);
            resolve();
          } else {
            reject(new Error('Failed to save configuration'));
          }
        } catch (error) {
          reject(error);
        }
      }, this.saveDebounceDelay);
    });
  }

  /**
   * Adds a new hub to the configuration.
   * Validates the hub data before adding.
   */
  async addHub(hubConfig) {
    if (!hubConfig.id || !hubConfig.url) {
      throw new Error('Hub configuration must include id and url');
    }

    if (!this.isValidUrl(hubConfig.url)) {
      throw new Error('Invalid URL format');
    }

    const existingIndex = this.config.hubs.findIndex(h => h.id === hubConfig.id);
    if (existingIndex !== -1) {
      throw new Error(`Hub with id ${hubConfig.id} already exists`);
    }

    const hub = {
      id: hubConfig.id,
      name: hubConfig.name || hubConfig.id,
      url: hubConfig.url,
      description: hubConfig.description || '',
      authentication: hubConfig.authentication || { type: 'none' },
      enabled: hubConfig.enabled !== false,
      lastSync: null
    };

    this.config.hubs.push(hub);
    await this.save();
    this.notifyWatchers('hubAdded', hub);

    return hub;
  }

  /**
   * Validates URL format.
   */
  isValidUrl(urlString) {
    try {
      const url = new URL(urlString);
      return url.protocol === 'http:' || url.protocol === 'https:';
    } catch (error) {
      return false;
    }
  }

  /**
   * Removes a hub from the configuration.
   */
  async removeHub(hubId) {
    const initialLength = this.config.hubs.length;
    this.config.hubs = this.config.hubs.filter(h => h.id !== hubId);

    if (this.config.hubs.length === initialLength) {
      throw new Error(`Hub with id ${hubId} not found`);
    }

    this.config.favorites = this.config.favorites.filter(
      fav => fav.hubId !== hubId
    );

    await this.save();
    this.notifyWatchers('hubRemoved', { hubId });
  }

  /**
   * Updates an existing hub configuration.
   */
  async updateHub(hubId, updates) {
    const hubIndex = this.config.hubs.findIndex(h => h.id === hubId);
    if (hubIndex === -1) {
      throw new Error(`Hub with id ${hubId} not found`);
    }

    if (updates.url && !this.isValidUrl(updates.url)) {
      throw new Error('Invalid URL format');
    }

    this.config.hubs[hubIndex] = {
      ...this.config.hubs[hubIndex],
      ...updates,
      id: hubId
    };

    await this.save();
    this.notifyWatchers('hubUpdated', this.config.hubs[hubIndex]);
  }

  /**
   * Adds a server to favorites.
   */
  async addToFavorites(hubId, serverId, serverName) {
    const exists = this.config.favorites.some(
      fav => fav.hubId === hubId && fav.serverId === serverId
    );

    if (exists) {
      return;
    }

    const favorite = {
      hubId,
      serverId,
      serverName: serverName || serverId,
      addedAt: new Date().toISOString()
    };

    this.config.favorites.push(favorite);
    await this.save();
    this.notifyWatchers('favoriteAdded', favorite);
  }

  /**
   * Removes a server from favorites.
   */
  async removeFromFavorites(hubId, serverId) {
    const initialLength = this.config.favorites.length;
    this.config.favorites = this.config.favorites.filter(
      fav => !(fav.hubId === hubId && fav.serverId === serverId)
    );

    if (this.config.favorites.length < initialLength) {
      await this.save();
      this.notifyWatchers('favoriteRemoved', { hubId, serverId });
      return true;
    }

    return false;
  }

  /**
   * Checks if a server is in favorites.
   */
  isFavorite(hubId, serverId) {
    return this.config.favorites.some(
      fav => fav.hubId === hubId && fav.serverId === serverId
    );
  }

  /**
   * Gets all favorites.
   */
  getFavorites() {
    return [...this.config.favorites];
  }

  /**
   * Updates UI settings.
   */
  async updateSettings(settings) {
    this.config.settings = {
      ...this.config.settings,
      ...settings
    };

    await this.save();
    this.notifyWatchers('settingsUpdated', this.config.settings);
  }

  /**
   * Sets an API token for a specific service.
   */
  async setApiToken(key, value) {
    if (!this.config.settings.apiTokens) {
      this.config.settings.apiTokens = {};
    }

    this.config.settings.apiTokens[key] = value;
    await this.save();
  }

  /**
   * Gets an API token for a specific service.
   */
  getApiToken(key) {
    if (!this.config.settings.apiTokens) {
      return null;
    }
    return this.config.settings.apiTokens[key] || null;
  }

  /**
   * Gets all hubs.
   */
  getHubs(enabledOnly = false) {
    if (enabledOnly) {
      return this.config.hubs.filter(hub => hub.enabled);
    }
    return [...this.config.hubs];
  }

  /**
   * Gets a specific hub by ID.
   */
  getHub(hubId) {
    return this.config.hubs.find(hub => hub.id === hubId) || null;
  }

  /**
   * Registers a watcher callback.
   */
  watch(callback) {
    this.watchers.push(callback);
    return () => {
      this.watchers = this.watchers.filter(w => w !== callback);
    };
  }

  /**
   * Notifies all watchers of a configuration change.
   */
  notifyWatchers(eventType, data) {
    this.watchers.forEach(watcher => {
      try {
        watcher(eventType, data);
      } catch (error) {
        console.error('Error in configuration watcher:', error);
      }
    });
  }
}

The ConfigurationManager provides a comprehensive interface for managing application configuration. It handles validation of hub entries, ensures URL formats are correct, and manages the favorites list. The debounced save mechanism prevents excessive localStorage writes when multiple changes occur in quick succession.

IMPLEMENTING THE MCP CLIENT PROTOCOL

The heart of our application lies in its implementation of the Model Context Protocol client. This component must correctly implement the MCP specification to establish connections, discover available tools, and invoke them with proper parameter handling.

class MCPMessage {
  constructor(method, params = {}, id = null) {
    this.jsonrpc = "2.0";
    this.method = method;
    this.params = params;
    
    if (id !== null) {
      this.id = id;
    }
  }

  toJSON() {
    const obj = {
      jsonrpc: this.jsonrpc,
      method: this.method,
      params: this.params
    };
    
    if (this.id !== null) {
      obj.id = this.id;
    }
    
    return obj;
  }
}

class MCPClient {
  constructor(serverUrl, authConfig = null) {
    this.serverUrl = serverUrl;
    this.authConfig = authConfig;
    this.messageId = 0;
    this.capabilities = null;
    this.tools = null;
    this.connectionState = 'disconnected';
    this.eventHandlers = new Map();
    this.requestTimeout = 30000;
    this.abortController = null;
  }

  generateMessageId() {
    return ++this.messageId;
  }

  /**
   * Sends a request to the MCP server with timeout and error handling.
   */
  async sendRequest(method, params = {}) {
    const message = new MCPMessage(method, params, this.generateMessageId());
    
    const headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    };

    if (this.authConfig && this.authConfig.type !== 'none') {
      if (this.authConfig.type === 'bearer' && this.authConfig.token) {
        headers['Authorization'] = `Bearer ${this.authConfig.token}`;
      } else if (this.authConfig.type === 'apikey' && this.authConfig.apiKey) {
        headers[this.authConfig.headerName || 'X-API-Key'] = this.authConfig.apiKey;
      }
    }

    this.abortController = new AbortController();
    const timeoutId = setTimeout(() => {
      this.abortController.abort();
    }, this.requestTimeout);

    try {
      const response = await fetch(this.serverUrl, {
        method: 'POST',
        headers: headers,
        body: JSON.stringify(message.toJSON()),
        signal: this.abortController.signal,
        mode: 'cors'
      });

      clearTimeout(timeoutId);

      if (!response.ok) {
        const errorText = await response.text().catch(() => response.statusText);
        throw new Error(`HTTP ${response.status}: ${errorText}`);
      }

      const contentType = response.headers.get('content-type');
      if (!contentType || !contentType.includes('application/json')) {
        throw new Error('Server did not return JSON response');
      }

      const result = await response.json();

      if (result.error) {
        throw new Error(`MCP Error ${result.error.code}: ${result.error.message}`);
      }

      return result.result;

    } catch (error) {
      clearTimeout(timeoutId);
      
      if (error.name === 'AbortError') {
        const timeoutError = new Error(`Request timeout after ${this.requestTimeout}ms`);
        this.emitEvent('error', { method, error: timeoutError.message });
        throw timeoutError;
      }

      this.emitEvent('error', { method, error: error.message });
      throw error;
    }
  }

  /**
   * Initializes the MCP connection with proper handshake.
   */
  async initialize() {
    if (this.connectionState === 'connected') {
      return this.capabilities;
    }

    this.connectionState = 'connecting';
    this.emitEvent('stateChange', { state: 'connecting' });

    try {
      const result = await this.sendRequest('initialize', {
        protocolVersion: '2024-11-05',
        capabilities: {
          roots: { listChanged: true },
          sampling: {}
        },
        clientInfo: {
          name: 'MCP Hub Explorer',
          version: '1.0.0'
        }
      });

      this.capabilities = result.capabilities || {};
      this.connectionState = 'connected';
      this.emitEvent('stateChange', { state: 'connected', capabilities: this.capabilities });

      await this.sendNotification('notifications/initialized');

      return this.capabilities;

    } catch (error) {
      this.connectionState = 'error';
      this.emitEvent('stateChange', { state: 'error', error: error.message });
      throw error;
    }
  }

  /**
   * Sends a notification (no response expected).
   */
  async sendNotification(method, params = {}) {
    const message = new MCPMessage(method, params, null);
    
    const headers = {
      'Content-Type': 'application/json'
    };

    if (this.authConfig && this.authConfig.type !== 'none') {
      if (this.authConfig.type === 'bearer' && this.authConfig.token) {
        headers['Authorization'] = `Bearer ${this.authConfig.token}`;
      }
    }

    try {
      await fetch(this.serverUrl, {
        method: 'POST',
        headers: headers,
        body: JSON.stringify(message.toJSON()),
        mode: 'cors'
      });
    } catch (error) {
      console.warn('Notification send failed:', error);
    }
  }

  /**
   * Lists all tools available from the server.
   */
  async listTools() {
    if (this.connectionState !== 'connected') {
      await this.initialize();
    }

    try {
      const result = await this.sendRequest('tools/list', {});
      this.tools = result.tools || [];
      return this.tools;
    } catch (error) {
      console.error('Failed to list tools:', error);
      throw error;
    }
  }

  /**
   * Calls a specific tool with given arguments.
   */
  async callTool(toolName, toolArguments = {}) {
    if (this.connectionState !== 'connected') {
      await this.initialize();
    }

    try {
      const result = await this.sendRequest('tools/call', {
        name: toolName,
        arguments: toolArguments
      });

      return result;

    } catch (error) {
      console.error(`Failed to call tool ${toolName}:`, error);
      throw error;
    }
  }

  /**
   * Registers an event handler.
   */
  on(eventName, handler) {
    if (!this.eventHandlers.has(eventName)) {
      this.eventHandlers.set(eventName, []);
    }
    this.eventHandlers.get(eventName).push(handler);
  }

  /**
   * Removes an event handler.
   */
  off(eventName, handler) {
    const handlers = this.eventHandlers.get(eventName);
    if (handlers) {
      const index = handlers.indexOf(handler);
      if (index !== -1) {
        handlers.splice(index, 1);
      }
    }
  }

  /**
   * Emits an event to all registered handlers.
   */
  emitEvent(eventName, data) {
    const handlers = this.eventHandlers.get(eventName);
    if (handlers) {
      handlers.forEach(handler => {
        try {
          handler(data);
        } catch (error) {
          console.error(`Error in event handler for ${eventName}:`, error);
        }
      });
    }
  }

  /**
   * Disconnects from the server and cleans up resources.
   */
  disconnect() {
    if (this.abortController) {
      this.abortController.abort();
      this.abortController = null;
    }

    this.connectionState = 'disconnected';
    this.capabilities = null;
    this.tools = null;
    this.emitEvent('stateChange', { state: 'disconnected' });
  }

  /**
   * Sets the request timeout in milliseconds.
   */
  setTimeout(timeoutMs) {
    this.requestTimeout = timeoutMs;
  }
}

The MCPClient class now includes comprehensive error handling, request timeouts using AbortController, and proper CORS support. The timeout mechanism ensures that requests do not hang indefinitely, and the abort controller allows for clean cancellation of in-flight requests.

BUILDING THE HUB DISCOVERY SERVICE

The hub discovery service manages the process of fetching server listings from various hubs, normalizing the data into a common format, and caching the results for performance.

class HubDiscoveryService {
  constructor(configManager) {
    this.configManager = configManager;
    this.serverCache = new Map();
    this.syncInProgress = new Set();
    this.cacheTimeout = 300000;
  }

  /**
   * Syncs a specific hub to fetch latest server listings.
   */
  async syncHub(hubId) {
    if (this.syncInProgress.has(hubId)) {
      console.log(`Sync already in progress for hub ${hubId}`);
      return;
    }

    const hub = this.configManager.getHub(hubId);
    if (!hub) {
      throw new Error(`Hub ${hubId} not found in configuration`);
    }

    if (!hub.enabled) {
      console.log(`Hub ${hubId} is disabled, skipping sync`);
      return;
    }

    this.syncInProgress.add(hubId);

    try {
      const servers = await this.fetchServersFromHub(hub);
      
      this.serverCache.set(hubId, {
        servers: servers,
        syncedAt: Date.now(),
        hubInfo: {
          id: hub.id,
          name: hub.name,
          description: hub.description
        }
      });

      hub.lastSync = new Date().toISOString();
      await this.configManager.save();

      console.log(`Successfully synced ${servers.length} servers from hub ${hubId}`);
      return servers;

    } catch (error) {
      console.error(`Failed to sync hub ${hubId}:`, error);
      throw error;
    } finally {
      this.syncInProgress.delete(hubId);
    }
  }

  /**
   * Fetches servers from a hub with proper authentication.
   */
  async fetchServersFromHub(hub) {
    const headers = {
      'Accept': 'application/json'
    };

    if (hub.authentication && hub.authentication.type !== 'none') {
      if (hub.authentication.type === 'bearer') {
        const token = this.configManager.getApiToken(hub.authentication.tokenKey);
        if (token) {
          headers['Authorization'] = `Bearer ${token}`;
        } else {
          console.warn(`No token found for ${hub.authentication.tokenKey}`);
        }
      }
    }

    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 30000);

    try {
      const response = await fetch(hub.url, {
        method: 'GET',
        headers: headers,
        signal: controller.signal,
        mode: 'cors'
      });

      clearTimeout(timeoutId);

      if (!response.ok) {
        throw new Error(`Hub API returned ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      return this.normalizeHubResponse(hub.id, data);

    } catch (error) {
      clearTimeout(timeoutId);
      if (error.name === 'AbortError') {
        throw new Error('Hub request timeout');
      }
      throw error;
    }
  }

  /**
   * Normalizes hub response to common format.
   */
  normalizeHubResponse(hubId, rawData) {
    if (hubId === 'anthropic-official') {
      return this.normalizeAnthropicHub(rawData);
    } else if (hubId === 'github-mcp') {
      return this.normalizeGitHubHub(rawData);
    } else {
      return this.normalizeGenericHub(rawData);
    }
  }

  /**
   * Normalizes Anthropic hub format.
   */
  normalizeAnthropicHub(data) {
    if (!data || !data.servers || !Array.isArray(data.servers)) {
      return [];
    }

    return data.servers.map(server => ({
      id: server.id || this.generateServerId(),
      name: server.name || 'Unnamed Server',
      description: server.description || '',
      version: server.version || '1.0.0',
      author: server.author || 'Unknown',
      category: server.category || 'Uncategorized',
      tags: Array.isArray(server.tags) ? server.tags : [],
      endpoint: server.endpoint || '',
      authRequired: Boolean(server.authRequired),
      documentation: server.documentation || null,
      tools: Array.isArray(server.tools) ? server.tools : [],
      metadata: {
        stars: server.stars || 0,
        downloads: server.downloads || 0,
        lastUpdated: server.lastUpdated || null
      }
    }));
  }

  /**
   * Normalizes GitHub hub format.
   */
  normalizeGitHubHub(data) {
    if (!Array.isArray(data)) {
      return [];
    }

    return data.map(repo => ({
      id: (repo.full_name || '').replace('/', '-') || this.generateServerId(),
      name: repo.name || 'Unnamed Repository',
      description: repo.description || '',
      version: repo.default_branch || 'main',
      author: (repo.owner && repo.owner.login) || 'Unknown',
      category: this.inferCategoryFromTopics(repo.topics),
      tags: Array.isArray(repo.topics) ? repo.topics : [],
      endpoint: this.constructEndpointFromRepo(repo),
      authRequired: false,
      documentation: repo.html_url || null,
      tools: [],
      metadata: {
        stars: repo.stargazers_count || 0,
        downloads: 0,
        lastUpdated: repo.updated_at || null
      }
    }));
  }

  /**
   * Normalizes generic hub format.
   */
  normalizeGenericHub(data) {
    const servers = Array.isArray(data) ? data : (data.servers || []);

    return servers.map(server => ({
      id: server.id || server.name || this.generateServerId(),
      name: server.name || 'Unnamed Server',
      description: server.description || '',
      version: server.version || '1.0.0',
      author: server.author || 'Unknown',
      category: server.category || 'Uncategorized',
      tags: Array.isArray(server.tags) ? server.tags : [],
      endpoint: server.endpoint || server.url || '',
      authRequired: Boolean(server.authRequired),
      documentation: server.documentation || null,
      tools: Array.isArray(server.tools) ? server.tools : [],
      metadata: server.metadata || {}
    }));
  }

  /**
   * Generates a unique server ID.
   */
  generateServerId() {
    return `server-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  }

  /**
   * Infers category from topic tags.
   */
  inferCategoryFromTopics(topics) {
    if (!Array.isArray(topics) || topics.length === 0) {
      return 'Uncategorized';
    }

    const categoryMap = {
      'database': 'Database',
      'filesystem': 'File System',
      'api': 'API Integration',
      'web': 'Web Services',
      'ai': 'AI & ML',
      'data': 'Data Processing',
      'security': 'Security',
      'monitoring': 'Monitoring'
    };

    for (const topic of topics) {
      const normalized = topic.toLowerCase();
      if (categoryMap[normalized]) {
        return categoryMap[normalized];
      }
    }

    return 'Uncategorized';
  }

  /**
   * Constructs endpoint URL from repository information.
   */
  constructEndpointFromRepo(repo) {
    if (!repo || !repo.full_name || !repo.default_branch) {
      return '';
    }
    return `https://raw.githubusercontent.com/${repo.full_name}/${repo.default_branch}/mcp-server.json`;
  }

  /**
   * Syncs all enabled hubs.
   */
  async syncAllHubs() {
    const hubs = this.configManager.getHubs(true);
    const results = await Promise.allSettled(
      hubs.map(hub => this.syncHub(hub.id))
    );

    const failures = results.filter(r => r.status === 'rejected');
    if (failures.length > 0) {
      console.warn(`${failures.length} hub(s) failed to sync`);
    }

    return results;
  }

  /**
   * Gets servers from a specific hub.
   */
  getServersFromHub(hubId) {
    const cached = this.serverCache.get(hubId);
    if (!cached) {
      return [];
    }

    const age = Date.now() - cached.syncedAt;
    if (age > this.cacheTimeout) {
      console.log(`Cache for hub ${hubId} is stale`);
    }

    return [...cached.servers];
  }

  /**
   * Gets all servers from all hubs.
   */
  getAllServers() {
    const allServers = [];

    for (const [hubId, cache] of this.serverCache.entries()) {
      cache.servers.forEach(server => {
        allServers.push({
          ...server,
          hubId: hubId,
          hubName: cache.hubInfo.name
        });
      });
    }

    return allServers;
  }

  /**
   * Gets servers organized by category.
   */
  getServersByCategory() {
    const categorized = new Map();
    const allServers = this.getAllServers();

    allServers.forEach(server => {
      const category = server.category || 'Uncategorized';
      if (!categorized.has(category)) {
        categorized.set(category, []);
      }
      categorized.get(category).push(server);
    });

    return categorized;
  }

  /**
   * Searches servers by query string.
   */
  searchServers(query) {
    if (!query || typeof query !== 'string') {
      return [];
    }

    const normalizedQuery = query.toLowerCase().trim();
    if (!normalizedQuery) {
      return [];
    }

    const allServers = this.getAllServers();

    return allServers.filter(server => {
      return (
        (server.name && server.name.toLowerCase().includes(normalizedQuery)) ||
        (server.description && server.description.toLowerCase().includes(normalizedQuery)) ||
        (Array.isArray(server.tags) && server.tags.some(tag => 
          tag.toLowerCase().includes(normalizedQuery)
        )) ||
        (server.author && server.author.toLowerCase().includes(normalizedQuery))
      );
    });
  }

  /**
   * Gets favorite servers with full details.
   */
  getFavoriteServers() {
    const favorites = this.configManager.getFavorites();
    const favoriteServers = [];

    favorites.forEach(fav => {
      const servers = this.getServersFromHub(fav.hubId);
      const server = servers.find(s => s.id === fav.serverId);
      if (server) {
        favoriteServers.push({
          ...server,
          hubId: fav.hubId,
          addedToFavoritesAt: fav.addedAt
        });
      }
    });

    return favoriteServers;
  }

  /**
   * Clears the cache for a specific hub.
   */
  clearHubCache(hubId) {
    this.serverCache.delete(hubId);
  }

  /**
   * Clears all cached data.
   */
  clearAllCache() {
    this.serverCache.clear();
  }
}

The HubDiscoveryService now includes proper timeout handling, better error management, and cache invalidation logic. The normalization methods handle missing or malformed data gracefully by providing sensible defaults.

CREATING THE FILE EXPLORER UI

The user interface brings our application to life with an intuitive file explorer metaphor. We will build a comprehensive UI that handles all user interactions while maintaining clean separation from business logic.

class FileExplorerUI {
  constructor(configManager, discoveryService) {
    this.configManager = configManager;
    this.discoveryService = discoveryService;
    this.selectedNode = null;
    this.expandedNodes = new Set();
    this.treeContainer = null;
    this.detailsPanel = null;
    this.activeConnections = new Map();
    this.eventListeners = new Map();
  }

  /**
   * Initializes the UI and renders the initial state.
   */
  initialize() {
    this.createLayout();
    this.renderTree();
    this.setupEventListeners();
  }

  /**
   * Creates the main layout structure.
   */
  createLayout() {
    const appContainer = document.getElementById('app');
    if (!appContainer) {
      throw new Error('App container element not found');
    }

    appContainer.innerHTML = `
      <div class="explorer-container">
        <div class="toolbar">
          <button id="sync-all-btn" class="toolbar-btn">Sync All Hubs</button>
          <button id="add-hub-btn" class="toolbar-btn">Add Hub</button>
          <input type="text" id="search-input" class="search-box" placeholder="Search servers...">
          <button id="favorites-btn" class="toolbar-btn">Show Favorites</button>
        </div>
        <div class="content-area">
          <div class="tree-panel">
            <div id="tree-container" class="tree-container"></div>
          </div>
          <div class="details-panel">
            <div id="details-container" class="details-container">
              <div class="empty-state">Select a server to view details</div>
            </div>
          </div>
        </div>
      </div>
    `;

    this.treeContainer = document.getElementById('tree-container');
    this.detailsPanel = document.getElementById('details-container');
  }

  /**
   * Renders the tree structure.
   */
  renderTree() {
    const treeData = this.buildTreeData();
    this.cleanupTreeEventListeners();
    this.treeContainer.innerHTML = '';

    const rootNode = this.createTreeNode({
      type: 'root',
      label: 'MCP Hubs',
      children: treeData,
      expanded: true
    }, 0);

    this.treeContainer.appendChild(rootNode);
  }

  /**
   * Builds the tree data structure from hubs and servers.
   */
  buildTreeData() {
    const hubs = this.configManager.getHubs();
    const treeData = [];

    const favoriteServers = this.discoveryService.getFavoriteServers();
    if (favoriteServers.length > 0) {
      treeData.push({
        type: 'favorites',
        label: `Favorites (${favoriteServers.length})`,
        icon: 'star',
        children: favoriteServers.map(server => ({
          type: 'server',
          data: server,
          label: server.name,
          icon: 'file',
          hubId: server.hubId
        }))
      });
    }

    hubs.forEach(hub => {
      const servers = this.discoveryService.getServersFromHub(hub.id);
      const categorized = this.categorizeServers(servers);

      const hubNode = {
        type: 'hub',
        data: hub,
        label: `${hub.name} (${servers.length})`,
        icon: 'folder',
        children: []
      };

      for (const [category, categoryServers] of categorized.entries()) {
        const categoryNode = {
          type: 'category',
          label: `${category} (${categoryServers.length})`,
          icon: 'folder',
          hubId: hub.id,
          categoryName: category,
          children: categoryServers.map(server => ({
            type: 'server',
            data: server,
            label: server.name,
            icon: 'file',
            hubId: hub.id
          }))
        };

        hubNode.children.push(categoryNode);
      }

      treeData.push(hubNode);
    });

    return treeData;
  }

  /**
   * Categorizes servers by their category field.
   */
  categorizeServers(servers) {
    const categorized = new Map();

    servers.forEach(server => {
      const category = server.category || 'Uncategorized';
      if (!categorized.has(category)) {
        categorized.set(category, []);
      }
      categorized.get(category).push(server);
    });

    return categorized;
  }

  /**
   * Creates a tree node element with proper structure and event handling.
   */
  createTreeNode(nodeData, level) {
    const nodeElement = document.createElement('div');
    nodeElement.className = 'tree-node';
    nodeElement.dataset.type = nodeData.type;
    nodeElement.dataset.level = level;

    const indent = level * 20;
    const hasChildren = nodeData.children && nodeData.children.length > 0;
    const nodeKey = this.getNodeKey(nodeData);
    const isExpanded = this.expandedNodes.has(nodeKey) || nodeData.expanded;

    const nodeContent = document.createElement('div');
    nodeContent.className = 'node-content';
    nodeContent.style.paddingLeft = `${indent}px`;

    if (hasChildren) {
      const expandIcon = document.createElement('span');
      expandIcon.className = `expand-icon ${isExpanded ? 'expanded' : ''}`;
      expandIcon.textContent = isExpanded ? '▼' : '▶';
      nodeContent.appendChild(expandIcon);
    } else {
      const spacer = document.createElement('span');
      spacer.className = 'expand-icon-spacer';
      nodeContent.appendChild(spacer);
    }

    const icon = document.createElement('span');
    icon.className = `node-icon ${this.getIconClass(nodeData.icon)}`;
    nodeContent.appendChild(icon);

    const label = document.createElement('span');
    label.className = 'node-label';
    label.textContent = nodeData.label;
    nodeContent.appendChild(label);

    if (nodeData.type === 'server' && nodeData.hubId && nodeData.data) {
      const isFavorite = this.configManager.isFavorite(nodeData.hubId, nodeData.data.id);
      const favoriteIcon = document.createElement('span');
      favoriteIcon.className = `favorite-icon ${isFavorite ? 'favorited' : ''}`;
      favoriteIcon.textContent = isFavorite ? '★' : '☆';
      favoriteIcon.dataset.hubId = nodeData.hubId;
      favoriteIcon.dataset.serverId = nodeData.data.id;
      nodeContent.appendChild(favoriteIcon);
    }

    nodeElement.appendChild(nodeContent);

    if (hasChildren) {
      const childrenContainer = document.createElement('div');
      childrenContainer.className = 'node-children';
      childrenContainer.style.display = isExpanded ? 'block' : 'none';

      if (isExpanded) {
        nodeData.children.forEach(child => {
          childrenContainer.appendChild(this.createTreeNode(child, level + 1));
        });
      }

      nodeElement.appendChild(childrenContainer);
    }

    nodeElement.nodeData = nodeData;
    this.attachNodeEventListeners(nodeElement);

    return nodeElement;
  }

  /**
   * Generates a unique key for a node.
   */
  getNodeKey(nodeData) {
    if (nodeData.type === 'server' && nodeData.hubId && nodeData.data) {
      return `server-${nodeData.hubId}-${nodeData.data.id}`;
    } else if (nodeData.type === 'category' && nodeData.hubId) {
      return `category-${nodeData.hubId}-${nodeData.categoryName}`;
    } else if (nodeData.type === 'hub' && nodeData.data) {
      return `hub-${nodeData.data.id}`;
    } else {
      return `${nodeData.type}-${nodeData.label}`;
    }
  }

  /**
   * Gets CSS class for node icon.
   */
  getIconClass(iconType) {
    const iconMap = {
      'folder': 'icon-folder',
      'file': 'icon-file',
      'star': 'icon-star'
    };
    return iconMap[iconType] || 'icon-default';
  }

  /**
   * Attaches event listeners to a node element.
   */
  attachNodeEventListeners(nodeElement) {
    const nodeContent = nodeElement.querySelector('.node-content');
    const expandIcon = nodeElement.querySelector('.expand-icon');
    const favoriteIcon = nodeElement.querySelector('.favorite-icon');

    const expandHandler = (e) => {
      e.stopPropagation();
      this.handleNodeExpand(nodeElement);
    };

    const selectHandler = (e) => {
      if (!favoriteIcon || e.target !== favoriteIcon) {
        this.handleNodeSelect(nodeElement);
      }
    };

    const favoriteHandler = (e) => {
      e.stopPropagation();
      this.handleFavoriteToggle(nodeElement);
    };

    if (expandIcon) {
      expandIcon.addEventListener('click', expandHandler);
      this.trackEventListener(expandIcon, 'click', expandHandler);
    }

    nodeContent.addEventListener('click', selectHandler);
    this.trackEventListener(nodeContent, 'click', selectHandler);

    if (favoriteIcon) {
      favoriteIcon.addEventListener('click', favoriteHandler);
      this.trackEventListener(favoriteIcon, 'click', favoriteHandler);
    }
  }

  /**
   * Tracks event listeners for cleanup.
   */
  trackEventListener(element, eventType, handler) {
    if (!this.eventListeners.has(element)) {
      this.eventListeners.set(element, []);
    }
    this.eventListeners.get(element).push({ eventType, handler });
  }

  /**
   * Cleans up all tracked event listeners.
   */
  cleanupTreeEventListeners() {
    for (const [element, listeners] of this.eventListeners.entries()) {
      listeners.forEach(({ eventType, handler }) => {
        element.removeEventListener(eventType, handler);
      });
    }
    this.eventListeners.clear();
  }

  /**
   * Handles node expansion/collapse.
   */
  handleNodeExpand(nodeElement) {
    const nodeData = nodeElement.nodeData;
    if (!nodeData || !nodeData.children || nodeData.children.length === 0) {
      return;
    }

    const nodeKey = this.getNodeKey(nodeData);
    const childrenContainer = nodeElement.querySelector('.node-children');
    const expandIcon = nodeElement.querySelector('.expand-icon');

    if (!childrenContainer || !expandIcon) {
      return;
    }

    const isCurrentlyExpanded = childrenContainer.style.display === 'block';

    if (isCurrentlyExpanded) {
      childrenContainer.style.display = 'none';
      expandIcon.textContent = '▶';
      expandIcon.classList.remove('expanded');
      this.expandedNodes.delete(nodeKey);
    } else {
      childrenContainer.style.display = 'block';
      expandIcon.textContent = '▼';
      expandIcon.classList.add('expanded');
      this.expandedNodes.add(nodeKey);

      if (childrenContainer.children.length === 0) {
        const level = parseInt(nodeElement.dataset.level, 10);
        nodeData.children.forEach(child => {
          childrenContainer.appendChild(this.createTreeNode(child, level + 1));
        });
      }
    }
  }

  /**
   * Handles node selection.
   */
  handleNodeSelect(nodeElement) {
    if (this.selectedNode) {
      const prevContent = this.selectedNode.querySelector('.node-content');
      if (prevContent) {
        prevContent.classList.remove('selected');
      }
    }

    const nodeContent = nodeElement.querySelector('.node-content');
    if (nodeContent) {
      nodeContent.classList.add('selected');
    }
    this.selectedNode = nodeElement;

    const nodeData = nodeElement.nodeData;
    if (!nodeData) {
      return;
    }

    if (nodeData.type === 'server' && nodeData.data) {
      this.displayServerDetails(nodeData.data, nodeData.hubId);
    } else if (nodeData.type === 'hub' && nodeData.data) {
      this.displayHubDetails(nodeData.data);
    } else if (nodeData.type === 'category') {
      this.displayCategoryDetails(nodeData);
    }
  }

  /**
   * Handles favorite toggle.
   */
  async handleFavoriteToggle(nodeElement) {
    const favoriteIcon = nodeElement.querySelector('.favorite-icon');
    if (!favoriteIcon) {
      return;
    }

    const hubId = favoriteIcon.dataset.hubId;
    const serverId = favoriteIcon.dataset.serverId;
    const nodeData = nodeElement.nodeData;

    if (!hubId || !serverId || !nodeData || !nodeData.data) {
      return;
    }

    const isFavorite = favoriteIcon.classList.contains('favorited');

    try {
      if (isFavorite) {
        await this.configManager.removeFromFavorites(hubId, serverId);
        favoriteIcon.classList.remove('favorited');
        favoriteIcon.textContent = '☆';
      } else {
        await this.configManager.addToFavorites(hubId, serverId, nodeData.data.name);
        favoriteIcon.classList.add('favorited');
        favoriteIcon.textContent = '★';
      }

      this.renderTree();

    } catch (error) {
      console.error('Error toggling favorite:', error);
      this.showError('Failed to update favorites: ' + error.message);
    }
  }

  /**
   * Displays server details in the details panel.
   */
  displayServerDetails(server, hubId) {
    if (!server || !hubId) {
      return;
    }

    const isFavorite = this.configManager.isFavorite(hubId, server.id);

    const detailsHTML = `
      <div class="server-details">
        <div class="details-header">
          <h2>${this.escapeHtml(server.name)}</h2>
          <button class="favorite-btn ${isFavorite ? 'favorited' : ''}" 
                  data-hub-id="${this.escapeHtml(hubId)}" 
                  data-server-id="${this.escapeHtml(server.id)}">
            ${isFavorite ? '★ Remove from Favorites' : '☆ Add to Favorites'}
          </button>
        </div>
        
        <div class="details-section">
          <h3>Overview</h3>
          <p class="description">${this.escapeHtml(server.description)}</p>
          
          <div class="metadata-grid">
            <div class="metadata-item">
              <span class="metadata-label">Author:</span>
              <span class="metadata-value">${this.escapeHtml(server.author)}</span>
            </div>
            <div class="metadata-item">
              <span class="metadata-label">Version:</span>
              <span class="metadata-value">${this.escapeHtml(server.version)}</span>
            </div>
            <div class="metadata-item">
              <span class="metadata-label">Category:</span>
              <span class="metadata-value">${this.escapeHtml(server.category)}</span>
            </div>
            <div class="metadata-item">
              <span class="metadata-label">Authentication:</span>
              <span class="metadata-value">${server.authRequired ? 'Required' : 'Not Required'}</span>
            </div>
          </div>
          
          ${server.tags && server.tags.length > 0 ? `
            <div class="tags">
              ${server.tags.map(tag => `<span class="tag">${this.escapeHtml(tag)}</span>`).join('')}
            </div>
          ` : ''}
        </div>
        
        <div class="details-section">
          <h3>Connection</h3>
          <div class="connection-info">
            <div class="info-item">
              <span class="info-label">Endpoint:</span>
              <code class="info-value">${this.escapeHtml(server.endpoint)}</code>
            </div>
          </div>
          
          ${server.authRequired ? `
            <div class="auth-section">
              <h4>Authentication Required</h4>
              <div class="auth-form">
                <label for="auth-token">Token:</label>
                <input type="password" id="auth-token" class="auth-input" 
                       placeholder="Enter authentication token">
              </div>
            </div>
          ` : ''}
          
          <button class="connect-btn" 
                  data-server-endpoint="${this.escapeHtml(server.endpoint)}"
                  data-hub-id="${this.escapeHtml(hubId)}"
                  data-server-id="${this.escapeHtml(server.id)}">
            Connect to Server
          </button>
        </div>
        
        <div class="details-section">
          <h3>Tools</h3>
          <div id="tools-container" class="tools-container">
            <p class="info-message">Connect to the server to view available tools</p>
          </div>
        </div>
        
        ${server.documentation ? `
          <div class="details-section">
            <h3>Documentation</h3>
            <a href="${this.escapeHtml(server.documentation)}" 
               target="_blank" 
               rel="noopener noreferrer" 
               class="doc-link">
              View Documentation
            </a>
          </div>
        ` : ''}
        
        ${server.metadata && (server.metadata.stars || server.metadata.downloads) ? `
          <div class="details-section">
            <h3>Statistics</h3>
            <div class="stats-grid">
              ${server.metadata.stars ? `
                <div class="stat-item">
                  <span class="stat-label">Stars:</span>
                  <span class="stat-value">${server.metadata.stars}</span>
                </div>
              ` : ''}
              ${server.metadata.downloads ? `
                <div class="stat-item">
                  <span class="stat-label">Downloads:</span>
                  <span class="stat-value">${server.metadata.downloads}</span>
                </div>
              ` : ''}
              ${server.metadata.lastUpdated ? `
                <div class="stat-item">
                  <span class="stat-label">Last Updated:</span>
                  <span class="stat-value">${new Date(server.metadata.lastUpdated).toLocaleDateString()}</span>
                </div>
              ` : ''}
            </div>
          </div>
        ` : ''}
      </div>
    `;

    this.detailsPanel.innerHTML = detailsHTML;
    this.attachDetailsEventListeners(server, hubId);
  }

  /**
   * Escapes HTML to prevent XSS attacks.
   */
  escapeHtml(text) {
    if (text === null || text === undefined) {
      return '';
    }
    
    const div = document.createElement('div');
    div.textContent = String(text);
    return div.innerHTML;
  }

  /**
   * Attaches event listeners to details panel elements.
   */
  attachDetailsEventListeners(server, hubId) {
    const favoriteBtn = this.detailsPanel.querySelector('.favorite-btn');
    if (favoriteBtn) {
      favoriteBtn.addEventListener('click', async () => {
        const isFavorite = favoriteBtn.classList.contains('favorited');

        try {
          if (isFavorite) {
            await this.configManager.removeFromFavorites(hubId, server.id);
            favoriteBtn.classList.remove('favorited');
            favoriteBtn.textContent = '☆ Add to Favorites';
          } else {
            await this.configManager.addToFavorites(hubId, server.id, server.name);
            favoriteBtn.classList.add('favorited');
            favoriteBtn.textContent = '★ Remove from Favorites';
          }

          this.renderTree();

        } catch (error) {
          console.error('Error toggling favorite:', error);
          this.showError('Failed to update favorites: ' + error.message);
        }
      });
    }

    const connectBtn = this.detailsPanel.querySelector('.connect-btn');
    if (connectBtn) {
      connectBtn.addEventListener('click', () => {
        this.handleServerConnection(server, hubId);
      });
    }
  }

  /**
   * Handles server connection and tool discovery.
   */
  async handleServerConnection(server, hubId) {
    const connectBtn = this.detailsPanel.querySelector('.connect-btn');
    const toolsContainer = this.detailsPanel.querySelector('#tools-container');

    if (!connectBtn || !toolsContainer) {
      return;
    }

    connectBtn.disabled = true;
    connectBtn.textContent = 'Connecting...';

    let authConfig = null;

    if (server.authRequired) {
      const tokenInput = this.detailsPanel.querySelector('#auth-token');
      const token = tokenInput ? tokenInput.value.trim() : '';

      if (!token) {
        this.showError('Please enter an authentication token');
        connectBtn.disabled = false;
        connectBtn.textContent = 'Connect to Server';
        return;
      }

      authConfig = {
        type: 'bearer',
        token: token
      };
    }

    const connectionKey = `${hubId}-${server.id}`;
    
    if (this.activeConnections.has(connectionKey)) {
      const existingClient = this.activeConnections.get(connectionKey);
      existingClient.disconnect();
      this.activeConnections.delete(connectionKey);
    }

    try {
      const client = new MCPClient(server.endpoint, authConfig);

      client.on('stateChange', (data) => {
        console.log('Connection state changed:', data.state);
      });

      await client.initialize();
      const tools = await client.listTools();

      this.activeConnections.set(connectionKey, client);
      this.displayTools(tools, client, server, hubId);

      connectBtn.textContent = 'Connected';
      connectBtn.classList.add('connected');

    } catch (error) {
      console.error('Connection error:', error);
      toolsContainer.innerHTML = `
        <div class="error-message">
          Failed to connect: ${this.escapeHtml(error.message)}
        </div>
      `;
      connectBtn.disabled = false;
      connectBtn.textContent = 'Connect to Server';
    }
  }

  /**
   * Displays tools in the tools container.
   */
  displayTools(tools, client, server, hubId) {
    const toolsContainer = this.detailsPanel.querySelector('#tools-container');
    if (!toolsContainer) {
      return;
    }

    if (!tools || tools.length === 0) {
      toolsContainer.innerHTML = '<p class="info-message">No tools available</p>';
      return;
    }

    let toolsHTML = '<div class="tools-list">';

    tools.forEach((tool, index) => {
      const toolId = `tool-${this.generateSafeId(tool.name)}-${index}`;
      
      toolsHTML += `
        <div class="tool-item" data-tool-id="${toolId}">
          <div class="tool-header">
            <h4 class="tool-name">${this.escapeHtml(tool.name)}</h4>
            <button class="test-tool-btn" data-tool-id="${toolId}">
              Test Tool
            </button>
          </div>
          <p class="tool-description">${this.escapeHtml(tool.description || 'No description available')}</p>
          
          ${tool.inputSchema ? `
            <div class="tool-schema">
              <h5>Parameters:</h5>
              <div class="schema-content" data-tool-id="${toolId}">
                ${this.renderInputSchema(tool.inputSchema, toolId)}
              </div>
            </div>
          ` : ''}
          
          <div class="tool-result" id="result-${toolId}" style="display: none;">
            <h5>Result:</h5>
            <pre class="result-content"></pre>
          </div>
        </div>
      `;
    });

    toolsHTML += '</div>';
    toolsContainer.innerHTML = toolsHTML;

    const testButtons = toolsContainer.querySelectorAll('.test-tool-btn');
    testButtons.forEach(btn => {
      btn.addEventListener('click', () => {
        const toolId = btn.dataset.toolId;
        const tool = tools.find((t, idx) => 
          `tool-${this.generateSafeId(t.name)}-${idx}` === toolId
        );
        if (tool) {
          this.handleToolTest(tool, client, toolId);
        }
      });
    });
  }

  /**
   * Generates a safe ID from a string.
   */
  generateSafeId(str) {
    return String(str).replace(/[^a-zA-Z0-9-_]/g, '-');
  }

  /**
   * Renders input schema as form fields.
   */
  renderInputSchema(schema, toolId) {
    if (!schema || !schema.properties) {
      return '<p class="info-message">No parameters required</p>';
    }

    let html = '<div class="parameter-form">';

    for (const [paramName, paramDef] of Object.entries(schema.properties)) {
      const isRequired = schema.required && schema.required.includes(paramName);
      const paramType = paramDef.type || 'string';
      const inputId = `param-${toolId}-${this.generateSafeId(paramName)}`;

      html += `
        <div class="parameter-field">
          <label for="${inputId}">
            ${this.escapeHtml(paramName)}${isRequired ? ' *' : ''}
            <span class="parameter-type">${this.escapeHtml(paramType)}</span>
          </label>
      `;

      if (paramDef.description) {
        html += `<p class="parameter-description">${this.escapeHtml(paramDef.description)}</p>`;
      }

      if (paramType === 'boolean') {
        html += `
          <select id="${inputId}" 
                  class="parameter-input" 
                  data-param-name="${this.escapeHtml(paramName)}" 
                  data-param-type="${paramType}"
                  ${isRequired ? 'required' : ''}>
            <option value="true">true</option>
            <option value="false">false</option>
          </select>
        `;
      } else if (paramType === 'number' || paramType === 'integer') {
        html += `
          <input type="number" 
                 id="${inputId}" 
                 class="parameter-input" 
                 data-param-name="${this.escapeHtml(paramName)}" 
                 data-param-type="${paramType}"
                 ${isRequired ? 'required' : ''}>
        `;
      } else if (paramType === 'object' || paramType === 'array') {
        html += `
          <textarea id="${inputId}" 
                    class="parameter-input parameter-textarea" 
                    data-param-name="${this.escapeHtml(paramName)}" 
                    data-param-type="${paramType}"
                    placeholder="Enter JSON"
                    rows="4"
                    ${isRequired ? 'required' : ''}></textarea>
        `;
      } else {
        html += `
          <input type="text" 
                 id="${inputId}" 
                 class="parameter-input" 
                 data-param-name="${this.escapeHtml(paramName)}" 
                 data-param-type="${paramType}"
                 ${isRequired ? 'required' : ''}>
        `;
      }

      html += '</div>';
    }

    html += '</div>';
    return html;
  }

  /**
   * Handles tool testing.
   */
  async handleToolTest(tool, client, toolId) {
    const resultContainer = this.detailsPanel.querySelector(`#result-${toolId}`);
    const resultContent = resultContainer ? resultContainer.querySelector('.result-content') : null;

    if (!resultContainer || !resultContent) {
      return;
    }

    resultContainer.style.display = 'block';
    resultContent.textContent = 'Executing tool...';
    resultContent.className = 'result-content';

    const parameters = {};

    if (tool.inputSchema && tool.inputSchema.properties) {
      const toolItem = this.detailsPanel.querySelector(`[data-tool-id="${toolId}"]`);
      if (!toolItem) {
        return;
      }

      const paramInputs = toolItem.querySelectorAll('.parameter-input');

      let validationError = null;

      paramInputs.forEach(input => {
        const paramName = input.dataset.paramName;
        const paramType = input.dataset.paramType;
        let value = input.value;

        if (!value && tool.inputSchema.required && 
            tool.inputSchema.required.includes(paramName)) {
          validationError = `Required parameter '${paramName}' is missing`;
          return;
        }

        if (value) {
          try {
            if (paramType === 'number') {
              value = parseFloat(value);
              if (isNaN(value)) {
                validationError = `Parameter '${paramName}' must be a valid number`;
                return;
              }
            } else if (paramType === 'integer') {
              value = parseInt(value, 10);
              if (isNaN(value)) {
                validationError = `Parameter '${paramName}' must be a valid integer`;
                return;
              }
            } else if (paramType === 'boolean') {
              value = value === 'true';
            } else if (paramType === 'object' || paramType === 'array') {
              value = JSON.parse(value);
            }

            parameters[paramName] = value;

          } catch (error) {
            validationError = `Invalid value for parameter '${paramName}': ${error.message}`;
            return;
          }
        }
      });

      if (validationError) {
        resultContent.textContent = `Error: ${validationError}`;
        resultContent.classList.add('error');
        return;
      }
    }

    try {
      const result = await client.callTool(tool.name, parameters);

      resultContent.textContent = JSON.stringify(result, null, 2);
      resultContent.classList.remove('error');
      resultContent.classList.add('success');

    } catch (error) {
      resultContent.textContent = `Error: ${error.message}`;
      resultContent.classList.add('error');
      resultContent.classList.remove('success');
    }
  }

  /**
   * Displays hub details.
   */
  displayHubDetails(hub) {
    if (!hub) {
      return;
    }

    const servers = this.discoveryService.getServersFromHub(hub.id);

    const detailsHTML = `
      <div class="hub-details">
        <h2>${this.escapeHtml(hub.name)}</h2>
        <p class="description">${this.escapeHtml(hub.description)}</p>
        
        <div class="details-section">
          <h3>Hub Information</h3>
          <div class="info-grid">
            <div class="info-item">
              <span class="info-label">URL:</span>
              <code class="info-value">${this.escapeHtml(hub.url)}</code>
            </div>
            <div class="info-item">
              <span class="info-label">Status:</span>
              <span class="info-value ${hub.enabled ? 'status-enabled' : 'status-disabled'}">
                ${hub.enabled ? 'Enabled' : 'Disabled'}
              </span>
            </div>
            <div class="info-item">
              <span class="info-label">Servers:</span>
              <span class="info-value">${servers.length}</span>
            </div>
            ${hub.lastSync ? `
              <div class="info-item">
                <span class="info-label">Last Synced:</span>
                <span class="info-value">${new Date(hub.lastSync).toLocaleString()}</span>
              </div>
            ` : ''}
          </div>
        </div>
        
        <div class="details-section">
          <h3>Actions</h3>
          <div class="action-buttons">
            <button class="action-btn" id="sync-hub-btn" data-hub-id="${this.escapeHtml(hub.id)}">
              Sync Hub
            </button>
            <button class="action-btn ${hub.enabled ? 'disable' : 'enable'}" 
                    id="toggle-hub-btn" 
                    data-hub-id="${this.escapeHtml(hub.id)}">
              ${hub.enabled ? 'Disable Hub' : 'Enable Hub'}
            </button>
            <button class="action-btn danger" id="remove-hub-btn" data-hub-id="${this.escapeHtml(hub.id)}">
              Remove Hub
            </button>
          </div>
        </div>
      </div>
    `;

    this.detailsPanel.innerHTML = detailsHTML;
    this.attachHubActionListeners(hub);
  }

  /**
   * Attaches event listeners for hub actions.
   */
  attachHubActionListeners(hub) {
    const syncBtn = this.detailsPanel.querySelector('#sync-hub-btn');
    if (syncBtn) {
      syncBtn.addEventListener('click', async () => {
        syncBtn.disabled = true;
        syncBtn.textContent = 'Syncing...';

        try {
          await this.discoveryService.syncHub(hub.id);
          this.renderTree();
          this.displayHubDetails(hub);
          this.showSuccess('Hub synced successfully');
        } catch (error) {
          this.showError('Failed to sync hub: ' + error.message);
        } finally {
          syncBtn.disabled = false;
          syncBtn.textContent = 'Sync Hub';
        }
      });
    }

    const toggleBtn = this.detailsPanel.querySelector('#toggle-hub-btn');
    if (toggleBtn) {
      toggleBtn.addEventListener('click', async () => {
        try {
          await this.configManager.updateHub(hub.id, { enabled: !hub.enabled });
          this.renderTree();
          const updatedHub = this.configManager.getHub(hub.id);
          if (updatedHub) {
            this.displayHubDetails(updatedHub);
          }
        } catch (error) {
          this.showError('Failed to toggle hub: ' + error.message);
        }
      });
    }

    const removeBtn = this.detailsPanel.querySelector('#remove-hub-btn');
    if (removeBtn) {
      removeBtn.addEventListener('click', async () => {
        if (confirm(`Are you sure you want to remove ${hub.name}?`)) {
          try {
            await this.configManager.removeHub(hub.id);
            this.renderTree();
            this.detailsPanel.innerHTML = '<div class="empty-state">Select a server to view details</div>';
            this.showSuccess('Hub removed successfully');
          } catch (error) {
            this.showError('Failed to remove hub: ' + error.message);
          }
        }
      });
    }
  }

  /**
   * Displays category details.
   */
  displayCategoryDetails(nodeData) {
    if (!nodeData || !nodeData.children) {
      return;
    }

    const servers = nodeData.children.map(child => child.data).filter(Boolean);

    const detailsHTML = `
      <div class="category-details">
        <h2>${this.escapeHtml(nodeData.label)}</h2>
        <p class="server-count">${servers.length} server${servers.length !== 1 ? 's' : ''} in this category</p>
        
        <div class="server-list">
          ${servers.map(server => `
            <div class="server-card">
              <h3>${this.escapeHtml(server.name)}</h3>
              <p>${this.escapeHtml(server.description)}</p>
              <div class="server-meta">
                <span class="author">by ${this.escapeHtml(server.author)}</span>
                ${server.metadata && server.metadata.stars ? `
                  <span class="stars">★ ${server.metadata.stars}</span>
                ` : ''}
              </div>
            </div>
          `).join('')}
        </div>
      </div>
    `;

    this.detailsPanel.innerHTML = detailsHTML;
  }

  /**
   * Sets up global event listeners.
   */
  setupEventListeners() {
    const syncAllBtn = document.getElementById('sync-all-btn');
    if (syncAllBtn) {
      syncAllBtn.addEventListener('click', async () => {
        syncAllBtn.disabled = true;
        syncAllBtn.textContent = 'Syncing...';

        try {
          await this.discoveryService.syncAllHubs();
          this.renderTree();
          this.showSuccess('All hubs synced successfully');
        } catch (error) {
          this.showError('Some hubs failed to sync. Check console for details.');
        } finally {
          syncAllBtn.disabled = false;
          syncAllBtn.textContent = 'Sync All Hubs';
        }
      });
    }

    const addHubBtn = document.getElementById('add-hub-btn');
    if (addHubBtn) {
      addHubBtn.addEventListener('click', () => {
        this.showAddHubDialog();
      });
    }

    const searchInput = document.getElementById('search-input');
    if (searchInput) {
      let searchTimeout;
      searchInput.addEventListener('input', (e) => {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
          this.handleSearch(e.target.value);
        }, 300);
      });
    }

    const favoritesBtn = document.getElementById('favorites-btn');
    if (favoritesBtn) {
      favoritesBtn.addEventListener('click', () => {
        this.showFavorites();
      });
    }
  }

  /**
   * Shows the add hub dialog.
   */
  showAddHubDialog() {
    const dialogHTML = `
      <div class="modal-overlay" id="add-hub-modal">
        <div class="modal-content">
          <h2>Add New Hub</h2>
          <form id="add-hub-form">
            <div class="form-group">
              <label for="hub-id">Hub ID:</label>
              <input type="text" id="hub-id" required placeholder="my-custom-hub">
            </div>
            <div class="form-group">
              <label for="hub-name">Hub Name:</label>
              <input type="text" id="hub-name" required placeholder="My Custom Hub">
            </div>
            <div class="form-group">
              <label for="hub-url">Hub URL:</label>
              <input type="url" id="hub-url" required placeholder="https://example.com/mcp-hub">
            </div>
            <div class="form-group">
              <label for="hub-description">Description:</label>
              <textarea id="hub-description" rows="3"></textarea>
            </div>
            <div class="form-group">
              <label for="hub-auth-type">Authentication:</label>
              <select id="hub-auth-type">
                <option value="none">None</option>
                <option value="bearer">Bearer Token</option>
              </select>
            </div>
            <div class="form-actions">
              <button type="submit" class="btn-primary">Add Hub</button>
              <button type="button" class="btn-secondary" id="cancel-add-hub">Cancel</button>
            </div>
          </form>
        </div>
      </div>
    `;

    document.body.insertAdjacentHTML('beforeend', dialogHTML);

    const modal = document.getElementById('add-hub-modal');
    const form = document.getElementById('add-hub-form');
    const cancelBtn = document.getElementById('cancel-add-hub');

    if (!modal || !form || !cancelBtn) {
      return;
    }

    form.addEventListener('submit', async (e) => {
      e.preventDefault();

      const hubIdInput = document.getElementById('hub-id');
      const hubNameInput = document.getElementById('hub-name');
      const hubUrlInput = document.getElementById('hub-url');
      const hubDescInput = document.getElementById('hub-description');
      const hubAuthInput = document.getElementById('hub-auth-type');

      if (!hubIdInput || !hubNameInput || !hubUrlInput || !hubAuthInput) {
        return;
      }

      const hubConfig = {
        id: hubIdInput.value.trim(),
        name: hubNameInput.value.trim(),
        url: hubUrlInput.value.trim(),
        description: hubDescInput ? hubDescInput.value.trim() : '',
        authentication: {
          type: hubAuthInput.value
        }
      };

      try {
        await this.configManager.addHub(hubConfig);
        modal.remove();
        this.renderTree();
        this.showSuccess('Hub added successfully');
      } catch (error) {
        this.showError('Failed to add hub: ' + error.message);
      }
    });

    cancelBtn.addEventListener('click', () => {
      modal.remove();
    });

    modal.addEventListener('click', (e) => {
      if (e.target === modal) {
        modal.remove();
      }
    });
  }

  /**
   * Handles search functionality.
   */
  handleSearch(query) {
    if (!query || !query.trim()) {
      this.renderTree();
      return;
    }

    const results = this.discoveryService.searchServers(query);

    this.cleanupTreeEventListeners();
    this.treeContainer.innerHTML = '';

    const searchNode = this.createTreeNode({
      type: 'root',
      label: `Search Results (${results.length})`,
      children: results.map(server => ({
        type: 'server',
        data: server,
        label: server.name,
        icon: 'file',
        hubId: server.hubId
      })),
      expanded: true
    }, 0);

    this.treeContainer.appendChild(searchNode);
  }

  /**
   * Shows favorites view.
   */
  showFavorites() {
    const favorites = this.discoveryService.getFavoriteServers();

    this.cleanupTreeEventListeners();
    this.treeContainer.innerHTML = '';

    const favoritesNode = this.createTreeNode({
      type: 'root',
      label: `Favorites (${favorites.length})`,
      children: favorites.map(server => ({
        type: 'server',
        data: server,
        label: server.name,
        icon: 'file',
        hubId: server.hubId
      })),
      expanded: true
    }, 0);

    this.treeContainer.appendChild(favoritesNode);
  }

  /**
   * Shows an error message to the user.
   */
  showError(message) {
    alert('Error: ' + message);
  }

  /**
   * Shows a success message to the user.
   */
  showSuccess(message) {
    alert(message);
  }

  /**
   * Cleans up resources when destroying the UI.
   */
  destroy() {
    this.cleanupTreeEventListeners();
    
    for (const [key, client] of this.activeConnections.entries()) {
      client.disconnect();
    }
    this.activeConnections.clear();

    if (this.treeContainer) {
      this.treeContainer.innerHTML = '';
    }
    if (this.detailsPanel) {
      this.detailsPanel.innerHTML = '';
    }
  }
}

The FileExplorerUI class now includes comprehensive error handling, proper event listener cleanup to prevent memory leaks, XSS protection through HTML escaping, and better scoping of tool parameters to prevent cross-contamination.

STYLING THE APPLICATION

The CSS provides a polished, professional appearance while maintaining usability and accessibility.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  background-color: #f5f5f5;
}

.explorer-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 15px;
  background-color: #fff;
  border-bottom: 1px solid #ddd;
  flex-shrink: 0;
}

.toolbar-btn {
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.toolbar-btn:hover {
  background-color: #0056b3;
}

.toolbar-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.search-box {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.search-box:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
}

.content-area {
  display: flex;
  flex: 1;
  overflow: hidden;
  min-height: 0;
}

.tree-panel {
  width: 350px;
  background-color: #fff;
  border-right: 1px solid #ddd;
  overflow-y: auto;
  flex-shrink: 0;
}

.tree-container {
  padding: 10px;
}

.tree-node {
  user-select: none;
}

.node-content {
  display: flex;
  align-items: center;
  padding: 6px 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.15s;
}

.node-content:hover {
  background-color: #f0f0f0;
}

.node-content.selected {
  background-color: #e3f2fd;
}

.expand-icon {
  width: 16px;
  height: 16px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin-right: 4px;
  font-size: 10px;
  cursor: pointer;
  color: #666;
  flex-shrink: 0;
}

.expand-icon:hover {
  color: #333;
}

.expand-icon-spacer {
  width: 16px;
  display: inline-block;
  margin-right: 4px;
  flex-shrink: 0;
}

.node-icon {
  width: 16px;
  height: 16px;
  margin-right: 6px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.icon-folder::before {
  content: '📁';
}

.icon-file::before {
  content: '📄';
}

.icon-star::before {
  content: '⭐';
}

.node-label {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 0;
}

.favorite-icon {
  margin-left: 8px;
  cursor: pointer;
  color: #ffa500;
  font-size: 16px;
  flex-shrink: 0;
  transition: transform 0.2s;
}

.favorite-icon:hover {
  transform: scale(1.2);
}

.favorite-icon.favorited {
  color: #ff8c00;
}

.node-children {
  margin-left: 0;
}

.details-panel {
  flex: 1;
  background-color: #fff;
  overflow-y: auto;
  padding: 20px;
  min-width: 0;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
  font-size: 16px;
}

.server-details,
.hub-details,
.category-details {
  max-width: 900px;
}

.details-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #eee;
  gap: 15px;
  flex-wrap: wrap;
}

.details-header h2 {
  font-size: 24px;
  color: #333;
  word-break: break-word;
}

.favorite-btn {
  padding: 8px 16px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
  white-space: nowrap;
}

.favorite-btn:hover {
  background-color: #f8f8f8;
}

.favorite-btn.favorited {
  background-color: #fff3cd;
  border-color: #ffa500;
  color: #856404;
}

.details-section {
  margin-bottom: 30px;
}

.details-section h3 {
  font-size: 18px;
  margin-bottom: 15px;
  color: #555;
}

.description {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
  word-wrap: break-word;
}

.metadata-grid,
.info-grid,
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 15px;
}

.metadata-item,
.info-item,
.stat-item {
  display: flex;
  flex-direction: column;
}

.metadata-label,
.info-label,
.stat-label {
  font-weight: 600;
  color: #666;
  font-size: 12px;
  text-transform: uppercase;
  margin-bottom: 4px;
}

.metadata-value,
.info-value,
.stat-value {
  color: #333;
  font-size: 14px;
  word-break: break-word;
}

code.info-value {
  background-color: #f5f5f5;
  padding: 4px 8px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  word-break: break-all;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 10px;
}

.tag {
  padding: 4px 12px;
  background-color: #e3f2fd;
  color: #1976d2;
  border-radius: 12px;
  font-size: 12px;
}

.connection-info {
  margin-bottom: 15px;
}

.auth-section {
  margin: 15px 0;
  padding: 15px;
  background-color: #fff3cd;
  border-radius: 4px;
  border: 1px solid #ffc107;
}

.auth-section h4 {
  margin-bottom: 10px;
  color: #856404;
}

.auth-form label {
  display: block;
  margin-bottom: 5px;
  font-weight: 600;
}

.auth-input {
  width: 100%;
  max-width: 400px;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.auth-input:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
}

.connect-btn {
  padding: 10px 20px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: background-color 0.2s;
}

.connect-btn:hover:not(:disabled) {
  background-color: #218838;
}

.connect-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.connect-btn.connected {
  background-color: #17a2b8;
}

.tools-container {
  margin-top: 15px;
}

.tools-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.tool-item {
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  background-color: #fafafa;
}

.tool-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  gap: 10px;
  flex-wrap: wrap;
}

.tool-name {
  font-size: 16px;
  color: #333;
  word-break: break-word;
}

.test-tool-btn {
  padding: 6px 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  white-space: nowrap;
}

.test-tool-btn:hover:not(:disabled) {
  background-color: #0056b3;
}

.test-tool-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.tool-description {
  color: #666;
  margin-bottom: 10px;
  word-wrap: break-word;
}

.tool-schema {
  margin-top: 15px;
}

.tool-schema h5 {
  margin-bottom: 10px;
  color: #555;
}

.parameter-form {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.parameter-field {
  display: flex;
  flex-direction: column;
}

.parameter-field label {
  font-weight: 600;
  margin-bottom: 4px;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.parameter-type {
  font-size: 11px;
  color: #999;
  font-weight: normal;
}

.parameter-description {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.parameter-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  font-family: inherit;
}

.parameter-input:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
}

.parameter-textarea {
  font-family: 'Courier New', monospace;
  resize: vertical;
}

.tool-result {
  margin-top: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.tool-result h5 {
  margin-bottom: 10px;
  color: #555;
}

.result-content {
  background-color: #fff;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #ddd;
  overflow-x: auto;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.4;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.result-content.success {
  border-color: #28a745;
  background-color: #f0fff4;
}

.result-content.error {
  border-color: #dc3545;
  background-color: #fff5f5;
  color: #dc3545;
}

.info-message {
  color: #666;
  font-style: italic;
  padding: 10px;
}

.error-message {
  color: #dc3545;
  padding: 10px;
  background-color: #fff5f5;
  border: 1px solid #dc3545;
  border-radius: 4px;
  word-wrap: break-word;
}

.doc-link {
  display: inline-block;
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  text-decoration: none;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.doc-link:hover {
  background-color: #0056b3;
}

.status-enabled {
  color: #28a745;
  font-weight: 600;
}

.status-disabled {
  color: #dc3545;
  font-weight: 600;
}

.action-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.action-btn {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.action-btn:hover:not(:disabled) {
  background-color: #0056b3;
}

.action-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.action-btn.danger {
  background-color: #dc3545;
}

.action-btn.danger:hover:not(:disabled) {
  background-color: #c82333;
}

.action-btn.disable {
  background-color: #ffc107;
  color: #333;
}

.action-btn.enable {
  background-color: #28a745;
}

.server-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
  margin-top: 15px;
}

.server-card {
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  background-color: #fff;
  cursor: pointer;
  transition: all 0.2s;
}

.server-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.server-card h3 {
  font-size: 16px;
  margin-bottom: 8px;
  color: #333;
  word-break: break-word;
}

.server-card p {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
  word-wrap: break-word;
}

.server-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
  gap: 10px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  max-width: 500px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-content h2 {
  margin-bottom: 20px;
  color: #333;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 600;
  color: #333;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  font-family: inherit;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.btn-primary {
  flex: 1;
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
}

.btn-primary:hover {
  background-color: #0056b3;
}

.btn-secondary {
  flex: 1;
  padding: 10px 20px;
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-secondary:hover {
  background-color: #5a6268;
}

@media (max-width: 768px) {
  .content-area {
    flex-direction: column;
  }
  
  .tree-panel {
    width: 100%;
    max-height: 40vh;
    border-right: none;
    border-bottom: 1px solid #ddd;
  }
  
  .details-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .metadata-grid,
  .info-grid,
  .stats-grid {
    grid-template-columns: 1fr;
  }
}

BRINGING IT ALL TOGETHER

Finally, we create the main application class that initializes all components and starts the application.

class MCPHubExplorer {
  constructor() {
    this.configManager = null;
    this.discoveryService = null;
    this.ui = null;
    this.autoSyncInterval = null;
  }

  async initialize() {
    try {
      console.log('Initializing MCP Hub Explorer...');

      this.configManager = new ConfigurationManager();
      await this.configManager.initialize();
      console.log('Configuration loaded successfully');

      this.discoveryService = new HubDiscoveryService(this.configManager);
      console.log('Discovery service initialized');

      console.log('Syncing with configured hubs...');
      await this.discoveryService.syncAllHubs();
      console.log('Hub sync completed');

      this.ui = new FileExplorerUI(this.configManager, this.discoveryService);
      this.ui.initialize();
      console.log('UI initialized');

      this.setupAutoSync();

      console.log('MCP Hub Explorer ready');

    } catch (error) {
      console.error('Failed to initialize application:', error);
      this.showFatalError(error);
    }
  }

  setupAutoSync() {
    const settings = this.configManager.config.settings;

    if (settings.autoSync && settings.syncInterval > 0) {
      this.autoSyncInterval = setInterval(async () => {
        console.log('Auto-syncing hubs...');
        try {
          await this.discoveryService.syncAllHubs();
          if (this.ui) {
            this.ui.renderTree();
          }
        } catch (error) {
          console.error('Auto-sync failed:', error);
        }
      }, settings.syncInterval);
    }
  }

  showFatalError(error) {
    const appContainer = document.getElementById('app');
    if (!appContainer) {
      return;
    }

    appContainer.innerHTML = `
      <div style="display: flex; align-items: center; justify-content: center; height: 100vh; flex-direction: column; font-family: sans-serif; padding: 20px;">
        <h1 style="color: #dc3545;">Application Error</h1>
        <p style="color: #666; max-width: 600px; text-align: center; margin: 20px 0;">
          The application failed to initialize. Please check the console for details.
        </p>
        <pre style="background: #f5f5f5; padding: 15px; border-radius: 4px; margin-top: 20px; max-width: 800px; overflow: auto; width: 100%;">
${this.escapeHtml(error.message)}
        </pre>
        <button onclick="location.reload()" style="margin-top: 20px; padding: 10px 20px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">
          Reload Application
        </button>
      </div>
    `;
  }

  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = String(text);
    return div.innerHTML;
  }

  destroy() {
    if (this.autoSyncInterval) {
      clearInterval(this.autoSyncInterval);
      this.autoSyncInterval = null;
    }

    if (this.ui) {
      this.ui.destroy();
      this.ui = null;
    }

    this.discoveryService = null;
    this.configManager = null;
  }
}

document.addEventListener('DOMContentLoaded', async () => {
  const app = new MCPHubExplorer();
  window.mcpApp = app;
  await app.initialize();
});

HTML STRUCTURE

The application requires a simple HTML file to host the JavaScript and CSS.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>MCP Hub Explorer</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div id="app">
    <div style="display: flex; align-items: center; justify-content: center; height: 100vh; font-family: sans-serif;">
      <div style="text-align: center;">
        <h1>Loading MCP Hub Explorer...</h1>
        <p style="color: #666;">Please wait while the application initializes</p>
      </div>
    </div>
  </div>
  
  <script src="storage.js"></script>
  <script src="config.js"></script>
  <script src="mcp-client.js"></script>
  <script src="discovery.js"></script>
  <script src="ui.js"></script>
  <script src="app.js"></script>
</body>
</html>

CONCLUSION

We have built a comprehensive, production-ready web-based MCP Hub Explorer that addresses all the critical issues identified in the code review. The application now features proper error handling, memory leak prevention, XSS protection, timeout management, and clean resource cleanup. The architecture is browser-compatible, using localStorage instead of Node.js file system APIs, and properly handles CORS, authentication, and network errors.

The modular design allows for easy extension and maintenance. Each component has a single responsibility and communicates through well-defined interfaces. The UI provides an intuitive file-explorer metaphor that makes discovering and testing MCP servers accessible to users of all technical levels.

Future enhancements could include IndexedDB for larger datasets, service workers for offline functionality, WebSocket support for real-time updates, and a backend API for team collaboration features. The foundation we have built makes all these extensions straightforward to implement.

No comments: