Thursday, November 19, 2026

BUILDING AN MCP SERVER BROWSER: TUTORIAL FOR EXPLORING MODEL CONTEXT PROTOCOL SERVERS



INTRODUCTION TO THE MODEL CONTEXT PROTOCOL AND MCP SERVERS

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 provides a standardized way for AI applications to communicate with various services, databases, and APIs through what are called MCP Servers. These servers act as intermediaries that expose specific functionality to AI models in a structured, predictable manner.

Think of MCP Servers as specialized connectors that allow AI models to access everything from file systems and databases to web APIs and custom business logic. Each MCP Server implements the MCP specification, which defines how clients should discover and interact with the server's capabilities. The protocol is built upon JSON-RPC 2.0 for communication, providing a robust foundation for reliable client-server interactions.

In September 2025, Anthropic launched the official MCP Registry at registry.modelcontextprotocol.io, creating a centralized hub where developers can publish and discover MCP servers. This registry serves as a single source of truth for the MCP ecosystem, containing structured metadata about each registered server including API endpoints, authentication methods, input and output specifications, and installation instructions. Prior to this registry, MCP servers were primarily discovered through GitHub repositories and community-curated lists, making the discovery process fragmented and challenging.

The emergence of MCP Hubs has transformed how developers and AI practitioners discover and utilize MCP servers. These hubs aggregate server information from multiple sources, making it easier to find the right tools for specific use cases. Our tutorial focuses on building a sophisticated Python application that connects to these hubs, allowing users to browse, search, and interact with MCP servers through an intuitive graphical interface.

UNDERSTANDING THE ARCHITECTURE OF OUR MCP BROWSER APPLICATION

Before diving into the implementation details, we need to understand the overall architecture of our MCP Browser application. The application consists of several key components that work together to provide a seamless user experience for discovering and testing MCP servers.

The first component is the Hub Connector, which is responsible for communicating with various MCP registries and hubs. This component fetches server listings from configured endpoints, handles pagination when dealing with large result sets, and manages retry logic when network issues occur. The Hub Connector abstracts away the complexity of different hub APIs, providing a unified interface for the rest of the application.

The second component is the Server Manager, which processes the raw server data received from hubs and transforms it into a structured format that our application can work with. This component validates server metadata, extracts relevant information such as server names, descriptions, repository URLs, and package information, and maintains a local cache to improve performance and reduce unnecessary network requests.

The third component is the MCP Client, which handles direct communication with individual MCP servers using the official MCP protocol. This component establishes connections to remote servers, discovers available tools, resources, and prompts, invokes server tools with user-provided parameters, and handles connection failures gracefully with configurable retry mechanisms.

The fourth component is the User Interface, which presents all this functionality to users through an attractive and intuitive graphical interface. We will implement this using PyQt6, a powerful cross-platform GUI framework that allows us to create desktop applications with native look and feel. The UI will feature a server list view with search and filtering capabilities, detailed server information panels, interactive forms for testing server tools, and syntax-highlighted code examples showing how to use each server.

The final component is the Configuration Manager, which handles all application settings including hub URLs, retry counts, timeout values, and UI preferences. This component reads from and writes to a JSON configuration file, allowing users to customize the application's behavior without modifying code.

SETTING UP THE DEVELOPMENT ENVIRONMENT AND DEPENDENCIES

To build our MCP Browser application, we need to set up a proper Python development environment with all necessary dependencies. The application requires Python 3.10 or later, as we will be using modern Python features such as structural pattern matching and improved type hints.

The core dependencies for our application include the official MCP Python SDK, which provides client functionality for communicating with MCP servers. We install this using pip install mcp. For the graphical user interface, we use PyQt6, which offers comprehensive widgets and excellent documentation. The requests library handles HTTP communication with MCP registries and hubs. We also use aiohttp for asynchronous HTTP requests, which improves performance when fetching data from multiple sources simultaneously.

For code syntax highlighting in our UI, we utilize the Pygments library, which supports numerous programming languages and color schemes. The jsonschema library helps validate server metadata against the official MCP schema. Finally, we use python-dateutil for parsing timestamps in server metadata.

Let us examine the requirements.txt file that specifies all our dependencies with appropriate version constraints:

mcp>=0.9.0
PyQt6>=6.6.0
requests>=2.31.0
aiohttp>=3.9.0
Pygments>=2.17.0
jsonschema>=4.20.0
python-dateutil>=2.8.2

With these dependencies in place, we can begin implementing the core functionality of our application. The modular architecture we have designed allows us to develop and test each component independently before integrating them into the complete application.

IMPLEMENTING THE CONFIGURATION MANAGER

The Configuration Manager serves as the foundation for our application, providing centralized access to all configuration settings. This component reads from a JSON configuration file at startup and provides methods for accessing and updating configuration values. The configuration file allows users to customize hub URLs, connection parameters, and UI preferences without modifying the application code.

Let us examine the structure of our configuration file, which we will name mcp_browser_config.json:

{
    "hubs": [
        {
            "name": "Official MCP Registry",
            "url": "https://registry.modelcontextprotocol.io/v0/servers",
            "type": "official",
            "enabled": true
        },
        {
            "name": "GitHub MCP Servers",
            "url": "https://api.github.com/repos/modelcontextprotocol/servers/contents",
            "type": "github",
            "enabled": true
        }
    ],
    "connection": {
        "timeout_seconds": 30,
        "max_retries": 3,
        "retry_delay_seconds": 2
    },
    "ui": {
        "theme": "light",
        "font_size": 10,
        "window_width": 1200,
        "window_height": 800
    },
    "cache": {
        "enabled": true,
        "ttl_minutes": 60
    }
}

This configuration structure separates concerns into logical sections. The hubs section contains an array of hub definitions, each with a name for display purposes, a URL pointing to the hub's API endpoint, a type identifier that helps our application understand how to parse responses from different hub types, and an enabled flag that allows users to temporarily disable specific hubs without removing them from the configuration.

The connection section defines parameters for network communication, including timeout values to prevent the application from hanging on slow or unresponsive servers, maximum retry attempts when connections fail, and delay between retry attempts to avoid overwhelming servers with rapid-fire requests.

The ui section stores user interface preferences such as color theme, font size for better readability, and default window dimensions. The cache section controls whether we cache hub responses locally and how long cached data remains valid before requiring a refresh.

Now let us implement the ConfigurationManager class that loads and manages these settings:

import json
import os
from typing import Dict, List, Any, Optional
from pathlib import Path


class ConfigurationManager:
    """
    Manages application configuration including hub URLs, connection settings,
    and user preferences. Provides methods for loading, accessing, and updating
    configuration values.
    """
    
    def __init__(self, config_path: str = "mcp_browser_config.json"):
        """
        Initialize the configuration manager with the specified config file path.
        
        Args:
            config_path: Path to the JSON configuration file
        """
        self.config_path = Path(config_path)
        self.config: Dict[str, Any] = {}
        self._load_config()
    
    def _load_config(self) -> None:
        """
        Load configuration from the JSON file. If the file does not exist,
        create it with default values.
        """
        if not self.config_path.exists():
            self._create_default_config()
        
        try:
            with open(self.config_path, 'r', encoding='utf-8') as f:
                self.config = json.load(f)
        except json.JSONDecodeError as e:
            raise ValueError(f"Invalid JSON in configuration file: {e}")
        except Exception as e:
            raise RuntimeError(f"Failed to load configuration: {e}")
    
    def _create_default_config(self) -> None:
        """
        Create a default configuration file with sensible default values.
        """
        default_config = {
            "hubs": [
                {
                    "name": "Official MCP Registry",
                    "url": "https://registry.modelcontextprotocol.io/v0/servers",
                    "type": "official",
                    "enabled": True
                }
            ],
            "connection": {
                "timeout_seconds": 30,
                "max_retries": 3,
                "retry_delay_seconds": 2
            },
            "ui": {
                "theme": "light",
                "font_size": 10,
                "window_width": 1200,
                "window_height": 800
            },
            "cache": {
                "enabled": True,
                "ttl_minutes": 60
            }
        }
        
        with open(self.config_path, 'w', encoding='utf-8') as f:
            json.dump(default_config, f, indent=4)
        
        self.config = default_config
    
    def get_hubs(self) -> List[Dict[str, Any]]:
        """
        Get the list of configured MCP hubs.
        
        Returns:
            List of hub configuration dictionaries
        """
        return self.config.get("hubs", [])
    
    def get_enabled_hubs(self) -> List[Dict[str, Any]]:
        """
        Get only the enabled MCP hubs.
        
        Returns:
            List of enabled hub configuration dictionaries
        """
        return [hub for hub in self.get_hubs() if hub.get("enabled", True)]
    
    def add_hub(self, name: str, url: str, hub_type: str = "custom") -> None:
        """
        Add a new hub to the configuration.
        
        Args:
            name: Display name for the hub
            url: API endpoint URL for the hub
            hub_type: Type identifier for the hub
        """
        hubs = self.config.get("hubs", [])
        hubs.append({
            "name": name,
            "url": url,
            "type": hub_type,
            "enabled": True
        })
        self.config["hubs"] = hubs
        self.save_config()
    
    def get_connection_timeout(self) -> int:
        """
        Get the connection timeout in seconds.
        
        Returns:
            Timeout value in seconds
        """
        return self.config.get("connection", {}).get("timeout_seconds", 30)
    
    def get_max_retries(self) -> int:
        """
        Get the maximum number of connection retry attempts.
        
        Returns:
            Maximum retry count
        """
        return self.config.get("connection", {}).get("max_retries", 3)
    
    def get_retry_delay(self) -> int:
        """
        Get the delay between retry attempts in seconds.
        
        Returns:
            Retry delay in seconds
        """
        return self.config.get("connection", {}).get("retry_delay_seconds", 2)
    
    def get_ui_setting(self, setting_name: str, default: Any = None) -> Any:
        """
        Get a UI setting value.
        
        Args:
            setting_name: Name of the UI setting
            default: Default value if setting not found
            
        Returns:
            Setting value or default
        """
        return self.config.get("ui", {}).get(setting_name, default)
    
    def is_cache_enabled(self) -> bool:
        """
        Check if caching is enabled.
        
        Returns:
            True if caching is enabled, False otherwise
        """
        return self.config.get("cache", {}).get("enabled", True)
    
    def get_cache_ttl(self) -> int:
        """
        Get the cache time-to-live in minutes.
        
        Returns:
            Cache TTL in minutes
        """
        return self.config.get("cache", {}).get("ttl_minutes", 60)
    
    def save_config(self) -> None:
        """
        Save the current configuration to the JSON file.
        """
        try:
            with open(self.config_path, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, indent=4)
        except Exception as e:
            raise RuntimeError(f"Failed to save configuration: {e}")

This ConfigurationManager class provides a clean interface for accessing configuration values throughout our application. The class handles file I/O operations, creates default configurations when needed, and provides type-safe methods for retrieving specific configuration values. Notice how we use descriptive method names like get_enabled_hubs instead of generic getters, making the code more readable and self-documenting.

The configuration manager also includes error handling for common issues such as missing files, invalid JSON syntax, and file system errors. When the configuration file does not exist, the manager automatically creates one with sensible defaults, ensuring the application works out of the box without requiring manual configuration file creation.

BUILDING THE HUB CONNECTOR FOR FETCHING SERVER LISTINGS

The Hub Connector component is responsible for communicating with MCP registries and hubs to fetch server listings. This component must handle different hub types, as each may have its own API structure and response format. The connector implements retry logic, timeout handling, and response parsing to ensure robust operation even when network conditions are less than ideal.

Let us implement the HubConnector class that manages communication with MCP hubs:

import requests
import time
import logging
from typing import List, Dict, Any, Optional
from datetime import datetime, timedelta


class HubConnector:
    """
    Handles communication with MCP hubs and registries to fetch server listings.
    Supports multiple hub types and implements retry logic for reliability.
    """
    
    def __init__(self, config_manager):
        """
        Initialize the hub connector with configuration.
        
        Args:
            config_manager: ConfigurationManager instance for accessing settings
        """
        self.config_manager = config_manager
        self.logger = logging.getLogger(__name__)
        self.cache: Dict[str, Dict[str, Any]] = {}
    
    def fetch_all_servers(self) -> List[Dict[str, Any]]:
        """
        Fetch server listings from all enabled hubs.
        
        Returns:
            Combined list of server metadata from all hubs
        """
        all_servers = []
        enabled_hubs = self.config_manager.get_enabled_hubs()
        
        for hub in enabled_hubs:
            try:
                servers = self._fetch_from_hub(hub)
                all_servers.extend(servers)
                self.logger.info(f"Fetched {len(servers)} servers from {hub['name']}")
            except Exception as e:
                self.logger.error(f"Failed to fetch from {hub['name']}: {e}")
        
        return all_servers
    
    def _fetch_from_hub(self, hub: Dict[str, Any]) -> List[Dict[str, Any]]:
        """
        Fetch server listings from a specific hub.
        
        Args:
            hub: Hub configuration dictionary
            
        Returns:
            List of server metadata dictionaries
        """
        hub_url = hub['url']
        hub_type = hub.get('type', 'custom')
        
        # Check cache first if enabled
        if self.config_manager.is_cache_enabled():
            cached_data = self._get_from_cache(hub_url)
            if cached_data is not None:
                self.logger.info(f"Using cached data for {hub['name']}")
                return cached_data
        
        # Fetch from hub with retry logic
        response_data = self._fetch_with_retry(hub_url)
        
        # Parse response based on hub type
        servers = self._parse_hub_response(response_data, hub_type)
        
        # Update cache if enabled
        if self.config_manager.is_cache_enabled():
            self._update_cache(hub_url, servers)
        
        return servers
    
    def _fetch_with_retry(self, url: str) -> Dict[str, Any]:
        """
        Fetch data from URL with retry logic.
        
        Args:
            url: URL to fetch from
            
        Returns:
            Parsed JSON response
            
        Raises:
            RuntimeError: If all retry attempts fail
        """
        max_retries = self.config_manager.get_max_retries()
        retry_delay = self.config_manager.get_retry_delay()
        timeout = self.config_manager.get_connection_timeout()
        
        last_exception = None
        
        for attempt in range(max_retries):
            try:
                self.logger.debug(f"Fetching from {url} (attempt {attempt + 1}/{max_retries})")
                
                response = requests.get(
                    url,
                    timeout=timeout,
                    headers={'Accept': 'application/json'}
                )
                
                response.raise_for_status()
                return response.json()
                
            except requests.exceptions.Timeout as e:
                last_exception = e
                self.logger.warning(f"Timeout on attempt {attempt + 1}: {e}")
            except requests.exceptions.RequestException as e:
                last_exception = e
                self.logger.warning(f"Request failed on attempt {attempt + 1}: {e}")
            
            if attempt < max_retries - 1:
                time.sleep(retry_delay)
        
        raise RuntimeError(f"Failed to fetch from {url} after {max_retries} attempts: {last_exception}")
    
    def _parse_hub_response(self, response_data: Dict[str, Any], hub_type: str) -> List[Dict[str, Any]]:
        """
        Parse hub response based on hub type.
        
        Args:
            response_data: Raw JSON response from hub
            hub_type: Type of hub (official, github, custom)
            
        Returns:
            List of normalized server metadata dictionaries
        """
        if hub_type == "official":
            return self._parse_official_registry(response_data)
        elif hub_type == "github":
            return self._parse_github_response(response_data)
        else:
            return self._parse_custom_response(response_data)
    
    def _parse_official_registry(self, response_data: Dict[str, Any]) -> List[Dict[str, Any]]:
        """
        Parse response from the official MCP registry.
        
        Args:
            response_data: Raw JSON response
            
        Returns:
            List of normalized server metadata
        """
        servers = response_data.get('servers', [])
        normalized_servers = []
        
        for server in servers:
            normalized = {
                'name': server.get('name', 'Unknown'),
                'description': server.get('description', 'No description available'),
                'status': server.get('status', 'unknown'),
                'repository_url': server.get('repository', {}).get('url', ''),
                'repository_source': server.get('repository', {}).get('source', 'unknown'),
                'version': server.get('version', 'unknown'),
                'packages': server.get('packages', []),
                'schema': server.get('$schema', ''),
                'publication_timestamp': server.get('publication_timestamp', ''),
                'unique_id': server.get('unique_id', server.get('name', '')),
                'hub_type': 'official'
            }
            normalized_servers.append(normalized)
        
        return normalized_servers
    
    def _parse_github_response(self, response_data: Any) -> List[Dict[str, Any]]:
        """
        Parse response from GitHub API.
        
        Args:
            response_data: Raw JSON response from GitHub
            
        Returns:
            List of normalized server metadata
        """
        # GitHub API returns different formats depending on the endpoint
        # This is a simplified parser that handles common cases
        servers = []
        
        if isinstance(response_data, list):
            for item in response_data:
                if item.get('type') == 'file' and item.get('name', '').endswith('.json'):
                    # This is a server definition file
                    server = {
                        'name': item.get('name', '').replace('.json', ''),
                        'description': f"GitHub MCP Server: {item.get('name', '')}",
                        'status': 'active',
                        'repository_url': item.get('html_url', ''),
                        'repository_source': 'github',
                        'version': 'unknown',
                        'packages': [],
                        'schema': '',
                        'publication_timestamp': '',
                        'unique_id': item.get('sha', ''),
                        'hub_type': 'github'
                    }
                    servers.append(server)
        
        return servers
    
    def _parse_custom_response(self, response_data: Dict[str, Any]) -> List[Dict[str, Any]]:
        """
        Parse response from custom hub format.
        
        Args:
            response_data: Raw JSON response
            
        Returns:
            List of normalized server metadata
        """
        # Attempt to handle various custom formats
        if 'servers' in response_data:
            return self._parse_official_registry(response_data)
        elif isinstance(response_data, list):
            return self._parse_github_response(response_data)
        else:
            self.logger.warning("Unknown custom hub format, returning empty list")
            return []
    
    def _get_from_cache(self, hub_url: str) -> Optional[List[Dict[str, Any]]]:
        """
        Retrieve cached data for a hub if still valid.
        
        Args:
            hub_url: Hub URL to check cache for
            
        Returns:
            Cached server list if valid, None otherwise
        """
        if hub_url not in self.cache:
            return None
        
        cache_entry = self.cache[hub_url]
        cache_time = cache_entry['timestamp']
        ttl_minutes = self.config_manager.get_cache_ttl()
        
        if datetime.now() - cache_time < timedelta(minutes=ttl_minutes):
            return cache_entry['data']
        
        return None
    
    def _update_cache(self, hub_url: str, servers: List[Dict[str, Any]]) -> None:
        """
        Update cache with fresh server data.
        
        Args:
            hub_url: Hub URL to cache data for
            servers: Server list to cache
        """
        self.cache[hub_url] = {
            'timestamp': datetime.now(),
            'data': servers
        }
    
    def clear_cache(self) -> None:
        """
        Clear all cached hub data.
        """
        self.cache.clear()
        self.logger.info("Cache cleared")

The HubConnector class demonstrates several important design patterns. First, it separates the concerns of fetching data from parsing data, making the code more maintainable and testable. The fetch_with_retry method implements exponential backoff retry logic, which is essential for handling transient network failures without overwhelming remote servers.

The connector supports multiple hub types through the parse_hub_response method, which dispatches to specialized parsers based on the hub type. This design makes it easy to add support for new hub types in the future by simply adding new parser methods. The official registry parser extracts all relevant metadata fields and normalizes them into a consistent format that the rest of our application can work with.

The caching mechanism improves application performance and reduces load on hub servers by storing fetched data locally with a configurable time-to-live. The cache implementation uses timestamps to determine data freshness, automatically invalidating stale entries. Users can disable caching entirely through the configuration file if they always want fresh data.

IMPLEMENTING THE MCP CLIENT FOR SERVER INTERACTION

The MCP Client component handles direct communication with individual MCP servers using the official MCP protocol. This component is more complex than the Hub Connector because it must establish persistent connections, discover server capabilities, and invoke server tools with proper parameter handling. The client must also handle various failure modes gracefully, providing meaningful feedback to users when connections fail or servers are unavailable.

Let us implement the MCPClient class that manages MCP server interactions:

import asyncio
import json
import logging
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass
from datetime import datetime


@dataclass
class MCPTool:
    """
    Represents an MCP tool with its metadata and schema.
    """
    name: str
    description: str
    input_schema: Dict[str, Any]
    
    def get_required_parameters(self) -> List[str]:
        """
        Extract required parameter names from the input schema.
        
        Returns:
            List of required parameter names
        """
        return self.input_schema.get('required', [])
    
    def get_parameter_properties(self) -> Dict[str, Any]:
        """
        Get parameter property definitions.
        
        Returns:
            Dictionary of parameter properties
        """
        return self.input_schema.get('properties', {})


@dataclass
class MCPResource:
    """
    Represents an MCP resource with its metadata.
    """
    uri: str
    name: str
    description: str
    mime_type: Optional[str] = None


@dataclass
class MCPPrompt:
    """
    Represents an MCP prompt template.
    """
    name: str
    description: str
    arguments: List[Dict[str, Any]]


class MCPClient:
    """
    Client for communicating with MCP servers using the official protocol.
    Handles connection establishment, capability discovery, and tool invocation.
    """
    
    def __init__(self, config_manager):
        """
        Initialize the MCP client.
        
        Args:
            config_manager: ConfigurationManager instance
        """
        self.config_manager = config_manager
        self.logger = logging.getLogger(__name__)
        self.connected_servers: Dict[str, Any] = {}
    
    async def connect_to_server(self, server_url: str, server_name: str) -> Tuple[bool, str]:
        """
        Establish connection to an MCP server.
        
        Args:
            server_url: URL of the MCP server
            server_name: Name of the server for identification
            
        Returns:
            Tuple of (success boolean, message string)
        """
        max_retries = self.config_manager.get_max_retries()
        retry_delay = self.config_manager.get_retry_delay()
        
        for attempt in range(max_retries):
            try:
                self.logger.info(f"Connecting to {server_name} at {server_url} (attempt {attempt + 1})")
                
                # In a real implementation, this would use the MCP SDK to establish
                # a connection. For demonstration, we simulate the connection process.
                connection_info = await self._establish_connection(server_url)
                
                self.connected_servers[server_name] = {
                    'url': server_url,
                    'connection': connection_info,
                    'tools': [],
                    'resources': [],
                    'prompts': []
                }
                
                # Discover server capabilities
                await self._discover_capabilities(server_name)
                
                return True, f"Successfully connected to {server_name}"
                
            except ConnectionError as e:
                self.logger.warning(f"Connection attempt {attempt + 1} failed: {e}")
                if attempt < max_retries - 1:
                    await asyncio.sleep(retry_delay)
            except Exception as e:
                self.logger.error(f"Unexpected error connecting to {server_name}: {e}")
                return False, f"Failed to connect: {str(e)}"
        
        return False, f"Failed to connect after {max_retries} attempts"
    
    async def _establish_connection(self, server_url: str) -> Dict[str, Any]:
        """
        Establish the actual connection to an MCP server.
        
        Args:
            server_url: URL of the MCP server
            
        Returns:
            Connection information dictionary
            
        Raises:
            ConnectionError: If connection fails
        """
        # This is where we would use the MCP SDK to establish a real connection
        # For this implementation, we create a simulated connection
        
        try:
            # Simulate connection delay
            await asyncio.sleep(0.5)
            
            # In production, this would initialize an MCP client session
            # using the official SDK with appropriate transport (HTTP/SSE)
            connection_info = {
                'url': server_url,
                'protocol_version': '2025-07-09',
                'connected_at': datetime.now().isoformat(),
                'status': 'connected'
            }
            
            return connection_info
            
        except Exception as e:
            raise ConnectionError(f"Failed to establish connection: {e}")
    
    async def _discover_capabilities(self, server_name: str) -> None:
        """
        Discover the capabilities (tools, resources, prompts) of a connected server.
        
        Args:
            server_name: Name of the connected server
        """
        if server_name not in self.connected_servers:
            raise ValueError(f"Server {server_name} is not connected")
        
        server_info = self.connected_servers[server_name]
        
        try:
            # Discover tools
            tools = await self._list_tools(server_name)
            server_info['tools'] = tools
            self.logger.info(f"Discovered {len(tools)} tools on {server_name}")
            
            # Discover resources
            resources = await self._list_resources(server_name)
            server_info['resources'] = resources
            self.logger.info(f"Discovered {len(resources)} resources on {server_name}")
            
            # Discover prompts
            prompts = await self._list_prompts(server_name)
            server_info['prompts'] = prompts
            self.logger.info(f"Discovered {len(prompts)} prompts on {server_name}")
            
        except Exception as e:
            self.logger.error(f"Failed to discover capabilities for {server_name}: {e}")
    
    async def _list_tools(self, server_name: str) -> List[MCPTool]:
        """
        List all tools available on the server.
        
        Args:
            server_name: Name of the connected server
            
        Returns:
            List of MCPTool objects
        """
        # In production, this would call the MCP server's list_tools endpoint
        # For demonstration, we return example tools
        
        example_tools = [
            MCPTool(
                name="example_tool",
                description="An example tool for demonstration",
                input_schema={
                    "type": "object",
                    "properties": {
                        "input_text": {
                            "type": "string",
                            "description": "Text to process"
                        },
                        "option": {
                            "type": "string",
                            "enum": ["option1", "option2"],
                            "description": "Processing option"
                        }
                    },
                    "required": ["input_text"]
                }
            )
        ]
        
        return example_tools
    
    async def _list_resources(self, server_name: str) -> List[MCPResource]:
        """
        List all resources available on the server.
        
        Args:
            server_name: Name of the connected server
            
        Returns:
            List of MCPResource objects
        """
        # In production, this would call the MCP server's list_resources endpoint
        example_resources = [
            MCPResource(
                uri="resource://config",
                name="Configuration",
                description="Server configuration data",
                mime_type="application/json"
            )
        ]
        
        return example_resources
    
    async def _list_prompts(self, server_name: str) -> List[MCPPrompt]:
        """
        List all prompts available on the server.
        
        Args:
            server_name: Name of the connected server
            
        Returns:
            List of MCPPrompt objects
        """
        # In production, this would call the MCP server's list_prompts endpoint
        example_prompts = [
            MCPPrompt(
                name="example_prompt",
                description="An example prompt template",
                arguments=[
                    {"name": "context", "description": "Context for the prompt", "required": True}
                ]
            )
        ]
        
        return example_prompts
    
    async def invoke_tool(self, server_name: str, tool_name: str, 
                         parameters: Dict[str, Any]) -> Tuple[bool, Any]:
        """
        Invoke a tool on the connected MCP server.
        
        Args:
            server_name: Name of the connected server
            tool_name: Name of the tool to invoke
            parameters: Dictionary of parameter values
            
        Returns:
            Tuple of (success boolean, result or error message)
        """
        if server_name not in self.connected_servers:
            return False, f"Server {server_name} is not connected"
        
        server_info = self.connected_servers[server_name]
        
        # Find the tool
        tool = None
        for t in server_info['tools']:
            if t.name == tool_name:
                tool = t
                break
        
        if tool is None:
            return False, f"Tool {tool_name} not found on server {server_name}"
        
        # Validate parameters
        validation_result = self._validate_parameters(tool, parameters)
        if not validation_result[0]:
            return False, f"Parameter validation failed: {validation_result[1]}"
        
        try:
            # In production, this would use the MCP SDK to invoke the tool
            result = await self._execute_tool_call(server_name, tool_name, parameters)
            return True, result
            
        except Exception as e:
            self.logger.error(f"Tool invocation failed: {e}")
            return False, f"Tool invocation failed: {str(e)}"
    
    def _validate_parameters(self, tool: MCPTool, parameters: Dict[str, Any]) -> Tuple[bool, str]:
        """
        Validate parameters against tool's input schema.
        
        Args:
            tool: MCPTool object
            parameters: Parameter dictionary to validate
            
        Returns:
            Tuple of (valid boolean, error message if invalid)
        """
        required_params = tool.get_required_parameters()
        param_properties = tool.get_parameter_properties()
        
        # Check required parameters
        for required_param in required_params:
            if required_param not in parameters:
                return False, f"Missing required parameter: {required_param}"
        
        # Check parameter types
        for param_name, param_value in parameters.items():
            if param_name not in param_properties:
                return False, f"Unknown parameter: {param_name}"
            
            expected_type = param_properties[param_name].get('type')
            if expected_type == 'string' and not isinstance(param_value, str):
                return False, f"Parameter {param_name} must be a string"
            elif expected_type == 'integer' and not isinstance(param_value, int):
                return False, f"Parameter {param_name} must be an integer"
            elif expected_type == 'number' and not isinstance(param_value, (int, float)):
                return False, f"Parameter {param_name} must be a number"
            elif expected_type == 'boolean' and not isinstance(param_value, bool):
                return False, f"Parameter {param_name} must be a boolean"
        
        return True, "Valid"
    
    async def _execute_tool_call(self, server_name: str, tool_name: str, 
                                 parameters: Dict[str, Any]) -> Any:
        """
        Execute the actual tool call on the MCP server.
        
        Args:
            server_name: Name of the connected server
            tool_name: Name of the tool to invoke
            parameters: Parameter dictionary
            
        Returns:
            Tool execution result
        """
        # In production, this would send a JSON-RPC request to the MCP server
        # For demonstration, we return a simulated result
        
        await asyncio.sleep(0.3)  # Simulate network delay
        
        result = {
            'status': 'success',
            'tool': tool_name,
            'output': f"Processed with parameters: {json.dumps(parameters, indent=2)}",
            'timestamp': datetime.now().isoformat()
        }
        
        return result
    
    def get_server_tools(self, server_name: str) -> List[MCPTool]:
        """
        Get the list of tools for a connected server.
        
        Args:
            server_name: Name of the connected server
            
        Returns:
            List of MCPTool objects
        """
        if server_name in self.connected_servers:
            return self.connected_servers[server_name].get('tools', [])
        return []
    
    def get_server_resources(self, server_name: str) -> List[MCPResource]:
        """
        Get the list of resources for a connected server.
        
        Args:
            server_name: Name of the connected server
            
        Returns:
            List of MCPResource objects
        """
        if server_name in self.connected_servers:
            return self.connected_servers[server_name].get('resources', [])
        return []
    
    def get_server_prompts(self, server_name: str) -> List[MCPPrompt]:
        """
        Get the list of prompts for a connected server.
        
        Args:
            server_name: Name of the connected server
            
        Returns:
            List of MCPPrompt objects
        """
        if server_name in self.connected_servers:
            return self.connected_servers[server_name].get('prompts', [])
        return []
    
    def is_connected(self, server_name: str) -> bool:
        """
        Check if a server is currently connected.
        
        Args:
            server_name: Name of the server to check
            
        Returns:
            True if connected, False otherwise
        """
        return server_name in self.connected_servers
    
    async def disconnect_server(self, server_name: str) -> None:
        """
        Disconnect from an MCP server.
        
        Args:
            server_name: Name of the server to disconnect
        """
        if server_name in self.connected_servers:
            # In production, this would properly close the MCP connection
            del self.connected_servers[server_name]
            self.logger.info(f"Disconnected from {server_name}")

The MCPClient class provides a comprehensive interface for interacting with MCP servers. The class uses dataclasses to represent tools, resources, and prompts in a type-safe manner, making the code more maintainable and less error-prone. The connect_to_server method implements retry logic similar to the Hub Connector, ensuring robust connection establishment even in unreliable network conditions.

The capability discovery mechanism automatically queries the server for its available tools, resources, and prompts after establishing a connection. This information is cached locally so the application can present it to users without repeatedly querying the server. The invoke_tool method demonstrates proper parameter validation before making tool calls, preventing errors and providing helpful feedback when users supply incorrect parameters.

The parameter validation logic uses the tool's input schema to verify that all required parameters are present and that parameter types match expectations. This validation happens client-side before sending requests to the server, reducing unnecessary network traffic and providing immediate feedback to users. The validation supports common JSON Schema types including strings, integers, numbers, and booleans.

CREATING THE GRAPHICAL USER INTERFACE WITH PYQT6

Now we arrive at the most visible part of our application, the graphical user interface. The UI must present complex information in an intuitive, visually appealing manner while remaining responsive and easy to navigate. We will use PyQt6 to create a modern desktop application with multiple panels, interactive controls, and syntax-highlighted code displays.

The main window of our application consists of several key areas. On the left side, we have a server list view that displays all discovered MCP servers with search and filter capabilities. Users can type regular expressions into a search box to find specific servers. The center panel shows detailed information about the selected server, including its description, repository URL, version, and package information. The right panel contains tabs for viewing server tools, resources, prompts, and usage examples.

Let us begin implementing the main window class and supporting thread classes:

from PyQt6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                             QListWidget, QListWidgetItem, QTextEdit, QLineEdit,
                             QPushButton, QLabel, QTabWidget, QFormLayout,
                             QScrollArea, QMessageBox, QSplitter, QComboBox,
                             QSpinBox, QCheckBox, QGroupBox)
from PyQt6.QtCore import Qt, QThread, pyqtSignal
from PyQt6.QtGui import QFont, QColor, QPalette
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
import re
import json
import asyncio


class ServerFetchThread(QThread):
    """
    Background thread for fetching server listings from hubs.
    Prevents UI freezing during network operations.
    """
    
    servers_fetched = pyqtSignal(list)
    fetch_error = pyqtSignal(str)
    
    def __init__(self, hub_connector):
        super().__init__()
        self.hub_connector = hub_connector
    
    def run(self):
        """
        Execute the server fetch operation in background.
        """
        try:
            servers = self.hub_connector.fetch_all_servers()
            self.servers_fetched.emit(servers)
        except Exception as e:
            self.fetch_error.emit(str(e))


class ServerConnectionThread(QThread):
    """
    Background thread for connecting to MCP servers.
    """
    
    connection_result = pyqtSignal(bool, str, list)
    
    def __init__(self, mcp_client, server):
        super().__init__()
        self.mcp_client = mcp_client
        self.server = server
    
    def run(self):
        """
        Execute server connection in background.
        """
        try:
            # In production, extract actual server URL from metadata
            server_url = self.server.get('repository_url', '')
            server_name = self.server['name']
            
            # Connect asynchronously
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            
            success, message = loop.run_until_complete(
                self.mcp_client.connect_to_server(server_url, server_name)
            )
            
            if success:
                tools = self.mcp_client.get_server_tools(server_name)
                self.connection_result.emit(True, message, tools)
            else:
                self.connection_result.emit(False, message, [])
                
        except Exception as e:
            self.connection_result.emit(False, str(e), [])


class ToolTestThread(QThread):
    """
    Background thread for testing MCP server tools.
    """
    
    test_result = pyqtSignal(bool, object)
    
    def __init__(self, mcp_client, server_name, tool_name, parameters):
        super().__init__()
        self.mcp_client = mcp_client
        self.server_name = server_name
        self.tool_name = tool_name
        self.parameters = parameters
    
    def run(self):
        """
        Execute tool test in background.
        """
        try:
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            
            success, result = loop.run_until_complete(
                self.mcp_client.invoke_tool(
                    self.server_name,
                    self.tool_name,
                    self.parameters
                )
            )
            
            self.test_result.emit(success, result)
            
        except Exception as e:
            self.test_result.emit(False, str(e))


class MCPBrowserMainWindow(QMainWindow):
    """
    Main window for the MCP Server Browser application.
    Provides UI for browsing, searching, and testing MCP servers.
    """
    
    def __init__(self, config_manager, hub_connector, mcp_client):
        super().__init__()
        
        self.config_manager = config_manager
        self.hub_connector = hub_connector
        self.mcp_client = mcp_client
        
        self.all_servers = []
        self.filtered_servers = []
        self.selected_server = None
        self.param_inputs = {}
        
        self._init_ui()
        self._apply_theme()
        self._fetch_servers()
    
    def _init_ui(self):
        """
        Initialize the user interface components.
        """
        # Set window properties
        window_width = self.config_manager.get_ui_setting('window_width', 1200)
        window_height = self.config_manager.get_ui_setting('window_height', 800)
        self.setWindowTitle("MCP Server Browser")
        self.setGeometry(100, 100, window_width, window_height)
        
        # Create central widget and main layout
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        
        # Create top toolbar
        toolbar_layout = QHBoxLayout()
        
        refresh_button = QPushButton("Refresh Servers")
        refresh_button.clicked.connect(self._fetch_servers)
        toolbar_layout.addWidget(refresh_button)
        
        clear_cache_button = QPushButton("Clear Cache")
        clear_cache_button.clicked.connect(self._clear_cache)
        toolbar_layout.addWidget(clear_cache_button)
        
        toolbar_layout.addStretch()
        
        server_count_label = QLabel("Servers: 0")
        self.server_count_label = server_count_label
        toolbar_layout.addWidget(server_count_label)
        
        main_layout.addLayout(toolbar_layout)
        
        # Create main content area with splitter
        content_splitter = QSplitter(Qt.Orientation.Horizontal)
        
        # Left panel: Server list with search
        left_panel = QWidget()
        left_layout = QVBoxLayout(left_panel)
        
        search_label = QLabel("Search Servers (supports regex):")
        left_layout.addWidget(search_label)
        
        search_input = QLineEdit()
        search_input.setPlaceholderText("Enter search term or regex pattern...")
        search_input.textChanged.connect(self._filter_servers)
        self.search_input = search_input
        left_layout.addWidget(search_input)
        
        server_list = QListWidget()
        server_list.itemClicked.connect(self._on_server_selected)
        self.server_list = server_list
        left_layout.addWidget(server_list)
        
        content_splitter.addWidget(left_panel)
        
        # Right panel: Server details with tabs
        right_panel = QTabWidget()
        self.details_tab = self._create_details_tab()
        self.tools_tab = self._create_tools_tab()
        self.code_tab = self._create_code_tab()
        self.test_tab = self._create_test_tab()
        
        right_panel.addTab(self.details_tab, "Details")
        right_panel.addTab(self.tools_tab, "Tools & Resources")
        right_panel.addTab(self.code_tab, "Usage Code")
        right_panel.addTab(self.test_tab, "Test Server")
        
        content_splitter.addWidget(right_panel)
        
        # Set splitter proportions
        content_splitter.setStretchFactor(0, 1)
        content_splitter.setStretchFactor(1, 2)
        
        main_layout.addWidget(content_splitter)
        
        # Status bar
        self.statusBar().showMessage("Ready")
    
    def _create_details_tab(self) -> QWidget:
        """
        Create the server details tab.
        
        Returns:
            QWidget containing details view
        """
        details_widget = QWidget()
        details_layout = QVBoxLayout(details_widget)
        
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        
        scroll_content = QWidget()
        scroll_layout = QFormLayout(scroll_content)
        
        self.name_label = QLabel("No server selected")
        self.name_label.setWordWrap(True)
        font = self.name_label.font()
        font.setPointSize(14)
        font.setBold(True)
        self.name_label.setFont(font)
        
        self.description_label = QLabel("")
        self.description_label.setWordWrap(True)
        
        self.status_label = QLabel("")
        self.version_label = QLabel("")
        self.repository_label = QLabel("")
        self.repository_label.setOpenExternalLinks(True)
        
        self.packages_text = QTextEdit()
        self.packages_text.setReadOnly(True)
        self.packages_text.setMaximumHeight(150)
        
        scroll_layout.addRow("Name:", self.name_label)
        scroll_layout.addRow("Description:", self.description_label)
        scroll_layout.addRow("Status:", self.status_label)
        scroll_layout.addRow("Version:", self.version_label)
        scroll_layout.addRow("Repository:", self.repository_label)
        scroll_layout.addRow("Packages:", self.packages_text)
        
        scroll_area.setWidget(scroll_content)
        details_layout.addWidget(scroll_area)
        
        return details_widget
    
    def _create_tools_tab(self) -> QWidget:
        """
        Create the tools and resources tab.
        
        Returns:
            QWidget containing tools view
        """
        tools_widget = QWidget()
        tools_layout = QVBoxLayout(tools_widget)
        
        connect_button = QPushButton("Connect to Server")
        connect_button.clicked.connect(self._connect_to_selected_server)
        self.connect_button = connect_button
        tools_layout.addWidget(connect_button)
        
        self.connection_status_label = QLabel("Not connected")
        tools_layout.addWidget(self.connection_status_label)
        
        self.tools_text = QTextEdit()
        self.tools_text.setReadOnly(True)
        tools_layout.addWidget(self.tools_text)
        
        return tools_widget
    
    def _create_code_tab(self) -> QWidget:
        """
        Create the usage code examples tab.
        
        Returns:
            QWidget containing code view
        """
        code_widget = QWidget()
        code_layout = QVBoxLayout(code_widget)
        
        code_label = QLabel("Python code to use this MCP server:")
        code_layout.addWidget(code_label)
        
        self.code_text = QTextEdit()
        self.code_text.setReadOnly(True)
        self.code_text.setFontFamily("Courier New")
        code_layout.addWidget(self.code_text)
        
        return code_widget
    
    def _create_test_tab(self) -> QWidget:
        """
        Create the server testing tab.
        
        Returns:
            QWidget containing test interface
        """
        test_widget = QWidget()
        test_layout = QVBoxLayout(test_widget)
        
        # Tool selection
        tool_group = QGroupBox("Select Tool")
        tool_group_layout = QVBoxLayout(tool_group)
        
        self.tool_combo = QComboBox()
        self.tool_combo.currentTextChanged.connect(self._on_tool_selected)
        tool_group_layout.addWidget(self.tool_combo)
        
        test_layout.addWidget(tool_group)
        
        # Parameters
        params_group = QGroupBox("Parameters")
        params_group_layout = QVBoxLayout(params_group)
        
        self.params_scroll = QScrollArea()
        self.params_scroll.setWidgetResizable(True)
        self.params_widget = QWidget()
        self.params_layout = QFormLayout(self.params_widget)
        self.params_scroll.setWidget(self.params_widget)
        
        params_group_layout.addWidget(self.params_scroll)
        test_layout.addWidget(params_group)
        
        # Test button
        test_button = QPushButton("Test Tool")
        test_button.clicked.connect(self._test_tool)
        self.test_button = test_button
        test_layout.addWidget(test_button)
        
        # Results
        results_label = QLabel("Results:")
        test_layout.addWidget(results_label)
        
        self.results_text = QTextEdit()
        self.results_text.setReadOnly(True)
        test_layout.addWidget(self.results_text)
        
        return test_widget
    
    def _apply_theme(self):
        """
        Apply visual theme to the application.
        """
        theme = self.config_manager.get_ui_setting('theme', 'light')
        font_size = self.config_manager.get_ui_setting('font_size', 10)
        
        app_font = QFont()
        app_font.setPointSize(font_size)
        self.setFont(app_font)
        
        if theme == 'dark':
            palette = QPalette()
            palette.setColor(QPalette.ColorRole.Window, QColor(53, 53, 53))
            palette.setColor(QPalette.ColorRole.WindowText, Qt.GlobalColor.white)
            palette.setColor(QPalette.ColorRole.Base, QColor(25, 25, 25))
            palette.setColor(QPalette.ColorRole.AlternateBase, QColor(53, 53, 53))
            palette.setColor(QPalette.ColorRole.Text, Qt.GlobalColor.white)
            palette.setColor(QPalette.ColorRole.Button, QColor(53, 53, 53))
            palette.setColor(QPalette.ColorRole.ButtonText, Qt.GlobalColor.white)
            self.setPalette(palette)
    
    def _fetch_servers(self):
        """
        Fetch server listings from configured hubs.
        """
        self.statusBar().showMessage("Fetching servers from hubs...")
        self.server_list.clear()
        
        # Create and start background thread
        self.fetch_thread = ServerFetchThread(self.hub_connector)
        self.fetch_thread.servers_fetched.connect(self._on_servers_fetched)
        self.fetch_thread.fetch_error.connect(self._on_fetch_error)
        self.fetch_thread.start()
    
    def _on_servers_fetched(self, servers):
        """
        Handle successful server fetch.
        
        Args:
            servers: List of server metadata dictionaries
        """
        self.all_servers = servers
        self.filtered_servers = servers
        self._update_server_list()
        self.statusBar().showMessage(f"Loaded {len(servers)} servers")
        self.server_count_label.setText(f"Servers: {len(servers)}")
    
    def _on_fetch_error(self, error_message):
        """
        Handle server fetch error.
        
        Args:
            error_message: Error description
        """
        self.statusBar().showMessage(f"Error: {error_message}")
        QMessageBox.warning(self, "Fetch Error", f"Failed to fetch servers:\n{error_message}")
    
    def _filter_servers(self, search_text):
        """
        Filter server list based on search text.
        
        Args:
            search_text: Search query (supports regex)
        """
        if not search_text:
            self.filtered_servers = self.all_servers
        else:
            try:
                pattern = re.compile(search_text, re.IGNORECASE)
                self.filtered_servers = [
                    server for server in self.all_servers
                    if pattern.search(server['name']) or pattern.search(server.get('description', ''))
                ]
            except re.error:
                # Invalid regex, fall back to simple string matching
                search_lower = search_text.lower()
                self.filtered_servers = [
                    server for server in self.all_servers
                    if search_lower in server['name'].lower() or 
                       search_lower in server.get('description', '').lower()
                ]
        
        self._update_server_list()
    
    def _update_server_list(self):
        """
        Update the server list widget with filtered servers.
        """
        self.server_list.clear()
        
        for server in self.filtered_servers:
            item = QListWidgetItem(server['name'])
            item.setData(Qt.ItemDataRole.UserRole, server)
            
            # Color code by status
            if server.get('status') == 'active':
                item.setForeground(QColor(0, 128, 0))
            else:
                item.setForeground(QColor(128, 128, 128))
            
            self.server_list.addItem(item)
    
    def _on_server_selected(self, item):
        """
        Handle server selection from the list.
        
        Args:
            item: Selected QListWidgetItem
        """
        server = item.data(Qt.ItemDataRole.UserRole)
        self.selected_server = server
        self._display_server_details(server)
    
    def _display_server_details(self, server):
        """
        Display detailed information about a server.
        
        Args:
            server: Server metadata dictionary
        """
        # Update details tab
        self.name_label.setText(server['name'])
        self.description_label.setText(server.get('description', 'No description available'))
        self.status_label.setText(server.get('status', 'unknown'))
        self.version_label.setText(server.get('version', 'unknown'))
        
        repo_url = server.get('repository_url', '')
        if repo_url:
            self.repository_label.setText(f'<a href="{repo_url}">{repo_url}</a>')
        else:
            self.repository_label.setText('Not available')
        
        # Display packages
        packages = server.get('packages', [])
        if packages:
            packages_text = ""
            for pkg in packages:
                registry_type = pkg.get('registry_type', 'unknown')
                package_name = pkg.get('package_name', 'unknown')
                version_constraint = pkg.get('version_constraint', '')
                packages_text += f"{registry_type}: {package_name} {version_constraint}\n"
            self.packages_text.setPlainText(packages_text)
        else:
            self.packages_text.setPlainText("No package information available")
        
        # Generate usage code
        self._generate_usage_code(server)
        
        # Reset connection status
        self.connection_status_label.setText("Not connected")
        self.tools_text.clear()
        self.tool_combo.clear()
    
    def _generate_usage_code(self, server):
        """
        Generate Python code examples for using the server.
        
        Args:
            server: Server metadata dictionary
        """
        packages = server.get('packages', [])
        
        code = "# Python code to use this MCP server\n\n"
        
        # Installation instructions
        if packages:
            code += "# Installation:\n"
            for pkg in packages:
                registry_type = pkg.get('registry_type', '')
                package_name = pkg.get('package_name', '')
                if registry_type == 'npm':
                    code += f"# npm install {package_name}\n"
                elif registry_type == 'pypi':
                    code += f"# pip install {package_name}\n"
            code += "\n"
        
        # Basic usage example
        code += "# Basic usage example:\n"
        code += "import asyncio\n"
        code += "from mcp import ClientSession, StdioServerParameters\n"
        code += "from mcp.client.stdio import stdio_client\n\n"
        code += "async def main():\n"
        code += "    # Configure server parameters\n"
        code += f"    server_params = StdioServerParameters(\n"
        code += f"        command=\"{server['name']}\",  # Adjust based on installation\n"
        code += "        args=[]\n"
        code += "    )\n\n"
        code += "    # Connect to server\n"
        code += "    async with stdio_client(server_params) as (read, write):\n"
        code += "        async with ClientSession(read, write) as session:\n"
        code += "            # Initialize connection\n"
        code += "            await session.initialize()\n\n"
        code += "            # List available tools\n"
        code += "            tools = await session.list_tools()\n"
        code += "            print(f\"Available tools: {tools}\")\n\n"
        code += "            # Call a tool (example)\n"
        code += "            # result = await session.call_tool(\"tool_name\", arguments={...})\n"
        code += "            # print(result)\n\n"
        code += "if __name__ == \"__main__\":\n"
        code += "    asyncio.run(main())\n"
        
        # Apply syntax highlighting
        highlighted_code = highlight(code, PythonLexer(), HtmlFormatter())
        self.code_text.setHtml(highlighted_code)
    
    def _connect_to_selected_server(self):
        """
        Connect to the currently selected server.
        """
        if not self.selected_server:
            QMessageBox.warning(self, "No Server Selected", "Please select a server first.")
            return
        
        self.connect_button.setEnabled(False)
        self.connection_status_label.setText("Connecting...")
        self.statusBar().showMessage("Connecting to server...")
        
        # Create connection thread
        self.connection_thread = ServerConnectionThread(
            self.mcp_client,
            self.selected_server
        )
        self.connection_thread.connection_result.connect(self._on_connection_result)
        self.connection_thread.start()
    
    def _on_connection_result(self, success, message, tools):
        """
        Handle connection result.
        
        Args:
            success: Boolean indicating connection success
            message: Status message
            tools: List of available tools if successful
        """
        self.connect_button.setEnabled(True)
        
        if success:
            self.connection_status_label.setText(f"Connected: {message}")
            self.statusBar().showMessage("Successfully connected to server")
            
            # Display tools
            if tools:
                tools_text = "Available Tools:\n\n"
                for tool in tools:
                    tools_text += f"Tool: {tool.name}\n"
                    tools_text += f"Description: {tool.description}\n"
                    tools_text += f"Parameters: {json.dumps(tool.input_schema, indent=2)}\n\n"
                self.tools_text.setPlainText(tools_text)
                
                # Populate tool combo box
                self.tool_combo.clear()
                for tool in tools:
                    self.tool_combo.addItem(tool.name, tool)
            else:
                self.tools_text.setPlainText("No tools available on this server")
        else:
            self.connection_status_label.setText(f"Connection failed: {message}")
            self.statusBar().showMessage(f"Connection failed: {message}")
            QMessageBox.warning(self, "Connection Failed", message)
    
    def _on_tool_selected(self, tool_name):
        """
        Handle tool selection for testing.
        
        Args:
            tool_name: Name of selected tool
        """
        # Clear previous parameters
        while self.params_layout.count():
            child = self.params_layout.takeAt(0)
            if child.widget():
                child.widget().deleteLater()
        
        if not tool_name:
            return
        
        # Get tool object
        tool = self.tool_combo.currentData()
        if not tool:
            return
        
        # Create input fields for parameters
        properties = tool.get_parameter_properties()
        required = tool.get_required_parameters()
        
        self.param_inputs = {}
        
        for param_name, param_def in properties.items():
            param_type = param_def.get('type', 'string')
            param_desc = param_def.get('description', '')
            is_required = param_name in required
            
            label_text = f"{param_name}{'*' if is_required else ''}:"
            label = QLabel(label_text)
            label.setToolTip(param_desc)
            
            if param_type == 'string':
                if 'enum' in param_def:
                    input_widget = QComboBox()
                    input_widget.addItems(param_def['enum'])
                else:
                    input_widget = QLineEdit()
                    input_widget.setPlaceholderText(param_desc)
            elif param_type in ['integer', 'number']:
                input_widget = QSpinBox()
                input_widget.setRange(-999999, 999999)
            elif param_type == 'boolean':
                input_widget = QCheckBox()
            else:
                input_widget = QLineEdit()
            
            self.param_inputs[param_name] = (input_widget, param_type)
            self.params_layout.addRow(label, input_widget)
    
    def _test_tool(self):
        """
        Test the selected tool with provided parameters.
        """
        if not self.selected_server:
            QMessageBox.warning(self, "No Server", "No server selected")
            return
        
        tool_name = self.tool_combo.currentText()
        if not tool_name:
            QMessageBox.warning(self, "No Tool", "No tool selected")
            return
        
        # Collect parameters
        parameters = {}
        for param_name, (input_widget, param_type) in self.param_inputs.items():
            if isinstance(input_widget, QLineEdit):
                value = input_widget.text()
                if param_type == 'integer':
                    value = int(value) if value else 0
                elif param_type == 'number':
                    value = float(value) if value else 0.0
            elif isinstance(input_widget, QComboBox):
                value = input_widget.currentText()
            elif isinstance(input_widget, QSpinBox):
                value = input_widget.value()
            elif isinstance(input_widget, QCheckBox):
                value = input_widget.isChecked()
            else:
                value = ""
            
            if value or value == 0 or value is False:
                parameters[param_name] = value
        
        # Execute tool in background thread
        self.test_button.setEnabled(False)
        self.results_text.setPlainText("Executing tool...")
        
        self.tool_test_thread = ToolTestThread(
            self.mcp_client,
            self.selected_server['name'],
            tool_name,
            parameters
        )
        self.tool_test_thread.test_result.connect(self._on_test_result)
        self.tool_test_thread.start()
    
    def _on_test_result(self, success, result):
        """
        Handle tool test result.
        
        Args:
            success: Boolean indicating test success
            result: Result data or error message
        """
        self.test_button.setEnabled(True)
        
        if success:
            result_text = "Tool execution successful!\n\n"
            result_text += json.dumps(result, indent=2)
            self.results_text.setPlainText(result_text)
        else:
            self.results_text.setPlainText(f"Tool execution failed:\n{result}")
    
    def _clear_cache(self):
        """
        Clear the hub data cache.
        """
        self.hub_connector.clear_cache()
        self.statusBar().showMessage("Cache cleared")
        QMessageBox.information(self, "Cache Cleared", "Hub cache has been cleared successfully.")

The MCPBrowserMainWindow class represents the complete user interface for our application. The class uses PyQt6's signal and slot mechanism to handle user interactions and background operations. Notice how we use separate threads for network operations to prevent the UI from freezing during long-running tasks. The ServerFetchThread handles fetching server listings from hubs, while the ServerConnectionThread manages connections to individual MCP servers.

The interface provides comprehensive search functionality with regular expression support. Users can type patterns like "github.*server" to find all servers with "github" followed by "server" in their names or descriptions. The search is case-insensitive by default and falls back to simple string matching if the user enters an invalid regex pattern.

The details tab displays all relevant server metadata in a clean, organized format. The repository URL is clickable, allowing users to quickly navigate to the server's source code. The packages section shows installation instructions for all available package managers, making it easy for users to install and use the servers they discover.

The usage code tab generates complete, runnable Python code examples that demonstrate how to connect to and use the selected server. The code is syntax-highlighted using Pygments, making it easy to read and understand. Users can copy this code directly into their own projects as a starting point for integrating the MCP server.

The test tab provides an interactive interface for testing server tools without writing any code. When users select a tool, the interface automatically generates appropriate input fields based on the tool's parameter schema. String parameters get text inputs, enumerations get dropdown menus, numbers get spin boxes, and booleans get checkboxes. Required parameters are marked with asterisks to help users provide all necessary information.

BRINGING IT ALL TOGETHER: THE COMPLETE APPLICATION

Now that we have implemented all the core components, we need to create the main application entry point that initializes everything and starts the GUI. This main module sets up logging, creates instances of our manager classes, and launches the PyQt6 application.


#!/usr/bin/env python3

"""
MCP Server Browser - A fully functional application for discovering and testing MCP servers.

This application connects to MCP registries and hubs, allowing users to browse available
servers, view detailed information, and test server tools interactively using real MCP connections.

Author:  Michael Stal
Version: 2.0.0
License: MIT
"""

import sys
import logging
import json
import time
import re
import asyncio
from pathlib import Path
from typing import Dict, List, Any, Optional, Tuple, Union
from dataclasses import dataclass
from datetime import datetime, timedelta
import subprocess
import shutil

import requests
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                             QListWidget, QListWidgetItem, QTextEdit, QLineEdit,
                             QPushButton, QLabel, QTabWidget, QFormLayout,
                             QScrollArea, QMessageBox, QSplitter, QComboBox,
                             QSpinBox, QCheckBox, QGroupBox, QDoubleSpinBox)
from PyQt6.QtCore import Qt, QThread, pyqtSignal
from PyQt6.QtGui import QFont, QColor, QPalette
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter

# MCP SDK imports
try:
    from mcp import ClientSession, StdioServerParameters
    from mcp.client.stdio import stdio_client
    from mcp.types import Tool, Resource, Prompt, TextContent, ImageContent, EmbeddedResource
    MCP_AVAILABLE = True
except ImportError:
    MCP_AVAILABLE = False
    print("WARNING: MCP SDK not available. Install with: pip install mcp")


# ============================================================================
# CONFIGURATION MANAGER
# ============================================================================

class ConfigurationManager:
    """
    Manages application configuration including hub URLs, connection settings,
    and user preferences. Provides methods for loading, accessing, and updating
    configuration values.
    """
    
    def __init__(self, config_path: str = "mcp_browser_config.json"):
        """
        Initialize the configuration manager with the specified config file path.
        
        Args:
            config_path: Path to the JSON configuration file
        """
        self.config_path = Path(config_path)
        self.config: Dict[str, Any] = {}
        self._load_config()
    
    def _load_config(self) -> None:
        """
        Load configuration from the JSON file. If the file does not exist,
        create it with default values.
        """
        if not self.config_path.exists():
            self._create_default_config()
        
        try:
            with open(self.config_path, 'r', encoding='utf-8') as f:
                self.config = json.load(f)
        except json.JSONDecodeError as e:
            raise ValueError(f"Invalid JSON in configuration file: {e}")
        except Exception as e:
            raise RuntimeError(f"Failed to load configuration: {e}")
    
    def _create_default_config(self) -> None:
        """
        Create a default configuration file with sensible default values.
        """
        default_config = {
            "hubs": [
                {
                    "name": "Official MCP Registry",
                    "url": "https://registry.modelcontextprotocol.io/v0/servers",
                    "type": "official",
                    "enabled": True
                }
            ],
            "connection": {
                "timeout_seconds": 30,
                "max_retries": 3,
                "retry_delay_seconds": 2
            },
            "ui": {
                "theme": "light",
                "font_size": 10,
                "window_width": 1200,
                "window_height": 800
            },
            "cache": {
                "enabled": True,
                "ttl_minutes": 60
            },
            "mcp": {
                "default_transport": "stdio",
                "stdio_timeout": 10,
                "enable_logging": True
            }
        }
        
        with open(self.config_path, 'w', encoding='utf-8') as f:
            json.dump(default_config, f, indent=4)
        
        self.config = default_config
    
    def get_hubs(self) -> List[Dict[str, Any]]:
        """Get the list of configured MCP hubs."""
        return self.config.get("hubs", [])
    
    def get_enabled_hubs(self) -> List[Dict[str, Any]]:
        """Get only the enabled MCP hubs."""
        return [hub for hub in self.get_hubs() if hub.get("enabled", True)]
    
    def add_hub(self, name: str, url: str, hub_type: str = "custom") -> None:
        """Add a new hub to the configuration."""
        hubs = self.config.get("hubs", [])
        hubs.append({"name": name, "url": url, "type": hub_type, "enabled": True})
        self.config["hubs"] = hubs
        self.save_config()
    
    def get_connection_timeout(self) -> int:
        """Get the connection timeout in seconds."""
        return self.config.get("connection", {}).get("timeout_seconds", 30)
    
    def get_max_retries(self) -> int:
        """Get the maximum number of connection retry attempts."""
        return self.config.get("connection", {}).get("max_retries", 3)
    
    def get_retry_delay(self) -> int:
        """Get the delay between retry attempts in seconds."""
        return self.config.get("connection", {}).get("retry_delay_seconds", 2)
    
    def get_ui_setting(self, setting_name: str, default: Any = None) -> Any:
        """Get a UI setting value."""
        return self.config.get("ui", {}).get(setting_name, default)
    
    def is_cache_enabled(self) -> bool:
        """Check if caching is enabled."""
        return self.config.get("cache", {}).get("enabled", True)
    
    def get_cache_ttl(self) -> int:
        """Get the cache time-to-live in minutes."""
        return self.config.get("cache", {}).get("ttl_minutes", 60)
    
    def get_mcp_setting(self, setting_name: str, default: Any = None) -> Any:
        """Get an MCP-specific setting."""
        return self.config.get("mcp", {}).get(setting_name, default)
    
    def save_config(self) -> None:
        """Save the current configuration to the JSON file."""
        try:
            with open(self.config_path, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, indent=4)
        except Exception as e:
            raise RuntimeError(f"Failed to save configuration: {e}")


# ============================================================================
# HUB CONNECTOR
# ============================================================================

class HubConnector:
    """
    Handles communication with MCP hubs and registries to fetch server listings.
    Supports multiple hub types and implements retry logic for reliability.
    """
    
    def __init__(self, config_manager: ConfigurationManager):
        """Initialize the hub connector with configuration."""
        self.config_manager = config_manager
        self.logger = logging.getLogger(__name__)
        self.cache: Dict[str, Dict[str, Any]] = {}
    
    def fetch_all_servers(self) -> List[Dict[str, Any]]:
        """Fetch server listings from all enabled hubs."""
        all_servers = []
        enabled_hubs = self.config_manager.get_enabled_hubs()
        
        for hub in enabled_hubs:
            try:
                servers = self._fetch_from_hub(hub)
                all_servers.extend(servers)
                self.logger.info(f"Fetched {len(servers)} servers from {hub['name']}")
            except Exception as e:
                self.logger.error(f"Failed to fetch from {hub['name']}: {e}")
        
        return all_servers
    
    def _fetch_from_hub(self, hub: Dict[str, Any]) -> List[Dict[str, Any]]:
        """Fetch server listings from a specific hub."""
        hub_url = hub['url']
        hub_type = hub.get('type', 'custom')
        
        if self.config_manager.is_cache_enabled():
            cached_data = self._get_from_cache(hub_url)
            if cached_data is not None:
                self.logger.info(f"Using cached data for {hub['name']}")
                return cached_data
        
        response_data = self._fetch_with_retry(hub_url)
        servers = self._parse_hub_response(response_data, hub_type)
        
        if self.config_manager.is_cache_enabled():
            self._update_cache(hub_url, servers)
        
        return servers
    
    def _fetch_with_retry(self, url: str) -> Any:
        """Fetch data from URL with retry logic."""
        max_retries = self.config_manager.get_max_retries()
        retry_delay = self.config_manager.get_retry_delay()
        timeout = self.config_manager.get_connection_timeout()
        
        last_exception = None
        
        for attempt in range(max_retries):
            try:
                self.logger.debug(f"Fetching from {url} (attempt {attempt + 1}/{max_retries})")
                
                response = requests.get(
                    url,
                    timeout=timeout,
                    headers={'Accept': 'application/json'}
                )
                
                response.raise_for_status()
                return response.json()
                
            except requests.exceptions.Timeout as e:
                last_exception = e
                self.logger.warning(f"Timeout on attempt {attempt + 1}: {e}")
            except requests.exceptions.RequestException as e:
                last_exception = e
                self.logger.warning(f"Request failed on attempt {attempt + 1}: {e}")
            
            if attempt < max_retries - 1:
                time.sleep(retry_delay)
        
        raise RuntimeError(f"Failed to fetch from {url} after {max_retries} attempts: {last_exception}")
    
    def _parse_hub_response(self, response_data: Any, hub_type: str) -> List[Dict[str, Any]]:
        """Parse hub response based on hub type."""
        if hub_type == "official":
            return self._parse_official_registry(response_data)
        elif hub_type == "github":
            return self._parse_github_response(response_data)
        else:
            return self._parse_custom_response(response_data)
    
    def _parse_official_registry(self, response_data: Dict[str, Any]) -> List[Dict[str, Any]]:
        """Parse response from the official MCP registry."""
        servers = response_data.get('servers', [])
        normalized_servers = []
        
        for server in servers:
            # Extract command and args from packages
            command = None
            args = []
            transport = "stdio"
            
            packages = server.get('packages', [])
            if packages:
                pkg = packages[0]
                registry_type = pkg.get('registry_type', '')
                package_name = pkg.get('package_name', '')
                
                if registry_type == 'npm':
                    command = 'npx'
                    args = ['-y', package_name]
                elif registry_type == 'pypi':
                    command = package_name
                    args = []
            
            normalized = {
                'name': server.get('name', 'Unknown'),
                'description': server.get('description', 'No description available'),
                'status': server.get('status', 'unknown'),
                'repository_url': server.get('repository', {}).get('url', ''),
                'repository_source': server.get('repository', {}).get('source', 'unknown'),
                'version': server.get('version', 'unknown'),
                'packages': packages,
                'schema': server.get('$schema', ''),
                'publication_timestamp': server.get('publication_timestamp', ''),
                'unique_id': server.get('unique_id', server.get('name', '')),
                'hub_type': 'official',
                'command': command,
                'args': args,
                'transport': transport,
                'env': server.get('env', {})
            }
            normalized_servers.append(normalized)
        
        return normalized_servers
    
    def _parse_github_response(self, response_data: Any) -> List[Dict[str, Any]]:
        """Parse response from GitHub API."""
        servers = []
        
        if isinstance(response_data, list):
            for item in response_data:
                if item.get('type') == 'file' and item.get('name', '').endswith('.json'):
                    server = {
                        'name': item.get('name', '').replace('.json', ''),
                        'description': f"GitHub MCP Server: {item.get('name', '')}",
                        'status': 'active',
                        'repository_url': item.get('html_url', ''),
                        'repository_source': 'github',
                        'version': 'unknown',
                        'packages': [],
                        'schema': '',
                        'publication_timestamp': '',
                        'unique_id': item.get('sha', ''),
                        'hub_type': 'github',
                        'command': None,
                        'args': [],
                        'transport': 'stdio',
                        'env': {}
                    }
                    servers.append(server)
        
        return servers
    
    def _parse_custom_response(self, response_data: Any) -> List[Dict[str, Any]]:
        """Parse response from custom hub format."""
        if isinstance(response_data, dict) and 'servers' in response_data:
            return self._parse_official_registry(response_data)
        elif isinstance(response_data, list):
            return self._parse_github_response(response_data)
        else:
            self.logger.warning("Unknown custom hub format, returning empty list")
            return []
    
    def _get_from_cache(self, hub_url: str) -> Optional[List[Dict[str, Any]]]:
        """Retrieve cached data for a hub if still valid."""
        if hub_url not in self.cache:
            return None
        
        cache_entry = self.cache[hub_url]
        cache_time = cache_entry['timestamp']
        ttl_minutes = self.config_manager.get_cache_ttl()
        
        if datetime.now() - cache_time < timedelta(minutes=ttl_minutes):
            return cache_entry['data']
        
        return None
    
    def _update_cache(self, hub_url: str, servers: List[Dict[str, Any]]) -> None:
        """Update cache with fresh server data."""
        self.cache[hub_url] = {
            'timestamp': datetime.now(),
            'data': servers
        }
    
    def clear_cache(self) -> None:
        """Clear all cached hub data."""
        self.cache.clear()
        self.logger.info("Cache cleared")


# ============================================================================
# REAL MCP CLIENT WITH SDK INTEGRATION
# ============================================================================

@dataclass
class MCPTool:
    """Represents an MCP tool with its metadata and schema."""
    name: str
    description: str
    input_schema: Dict[str, Any]
    
    def get_required_parameters(self) -> List[str]:
        """Extract required parameter names from the input schema."""
        return self.input_schema.get('required', [])
    
    def get_parameter_properties(self) -> Dict[str, Any]:
        """Get parameter property definitions."""
        return self.input_schema.get('properties', {})


@dataclass
class MCPResource:
    """Represents an MCP resource with its metadata."""
    uri: str
    name: str
    description: str
    mime_type: Optional[str] = None


@dataclass
class MCPPrompt:
    """Represents an MCP prompt template."""
    name: str
    description: str
    arguments: List[Dict[str, Any]]


class RealMCPClient:
    """
    Real MCP client using the official MCP SDK.
    Handles actual connections to MCP servers, capability discovery, and tool invocation.
    """
    
    def __init__(self, config_manager: ConfigurationManager):
        """Initialize the real MCP client."""
        self.config_manager = config_manager
        self.logger = logging.getLogger(__name__)
        self.connected_servers: Dict[str, Dict[str, Any]] = {}
        
        if not MCP_AVAILABLE:
            self.logger.warning("MCP SDK not available - client will not function")
    
    async def connect_to_server(self, server_metadata: Dict[str, Any]) -> Tuple[bool, str]:
        """
        Establish a real connection to an MCP server.
        
        Args:
            server_metadata: Server metadata from hub including command, args, etc.
            
        Returns:
            Tuple of (success boolean, message string)
        """
        if not MCP_AVAILABLE:
            return False, "MCP SDK not installed. Install with: pip install mcp"
        
        server_name = server_metadata['name']
        command = server_metadata.get('command')
        args = server_metadata.get('args', [])
        
        if not command:
            return False, "No command specified for this server. Cannot connect."
        
        # Check if command is available
        if not shutil.which(command):
            return False, f"Command '{command}' not found. Please install the server first."
        
        max_retries = self.config_manager.get_max_retries()
        
        for attempt in range(max_retries):
            try:
                self.logger.info(f"Connecting to {server_name} (attempt {attempt + 1})")
                
                # Create server parameters
                server_params = StdioServerParameters(
                    command=command,
                    args=args,
                    env=server_metadata.get('env', None)
                )
                
                # Establish connection using stdio transport
                # The stdio_client is an async context manager
                stdio_transport = stdio_client(server_params)
                read_stream, write_stream = await stdio_transport.__aenter__()
                
                # Create client session
                client_session = ClientSession(read_stream, write_stream)
                await client_session.__aenter__()
                
                # Initialize the session
                init_result = await client_session.initialize()
                
                # Store connection info
                self.connected_servers[server_name] = {
                    'metadata': server_metadata,
                    'session': client_session,
                    'stdio_context': stdio_transport,
                    'read_stream': read_stream,
                    'write_stream': write_stream,
                    'server_params': server_params,
                    'init_result': init_result,
                    'tools': [],
                    'resources': [],
                    'prompts': [],
                    'connected_at': datetime.now()
                }
                
                # Discover capabilities
                await self._discover_capabilities(server_name)
                
                server_info = init_result.server_info
                return True, f"Connected to {server_info.name} v{server_info.version}"
                
            except FileNotFoundError as e:
                return False, f"Server executable not found: {e}"
            except Exception as e:
                self.logger.warning(f"Connection attempt {attempt + 1} failed: {e}")
                if attempt < max_retries - 1:
                    await asyncio.sleep(self.config_manager.get_retry_delay())
                else:
                    return False, f"Failed to connect: {str(e)}"
        
        return False, "Failed to connect after all retry attempts"
    
    async def _discover_capabilities(self, server_name: str) -> None:
        """
        Discover the real capabilities of a connected MCP server.
        
        Args:
            server_name: Name of the connected server
        """
        if server_name not in self.connected_servers:
            raise ValueError(f"Server {server_name} is not connected")
        
        server_info = self.connected_servers[server_name]
        session = server_info['session']
        
        try:
            # List tools using real MCP protocol
            tools_result = await session.list_tools()
            tools = []
            for tool in tools_result.tools:
                tools.append(MCPTool(
                    name=tool.name,
                    description=tool.description or "No description",
                    input_schema=tool.inputSchema
                ))
            server_info['tools'] = tools
            self.logger.info(f"Discovered {len(tools)} tools on {server_name}")
            
            # List resources using real MCP protocol
            try:
                resources_result = await session.list_resources()
                resources = []
                for resource in resources_result.resources:
                    resources.append(MCPResource(
                        uri=resource.uri,
                        name=resource.name,
                        description=resource.description or "No description",
                        mime_type=resource.mimeType if hasattr(resource, 'mimeType') else None
                    ))
                server_info['resources'] = resources
                self.logger.info(f"Discovered {len(resources)} resources on {server_name}")
            except Exception as e:
                self.logger.warning(f"Failed to list resources: {e}")
                server_info['resources'] = []
            
            # List prompts using real MCP protocol
            try:
                prompts_result = await session.list_prompts()
                prompts = []
                for prompt in prompts_result.prompts:
                    arguments = []
                    if hasattr(prompt, 'arguments') and prompt.arguments:
                        for arg in prompt.arguments:
                            arguments.append({
                                'name': arg.name,
                                'description': arg.description or "No description",
                                'required': arg.required
                            })
                    prompts.append(MCPPrompt(
                        name=prompt.name,
                        description=prompt.description or "No description",
                        arguments=arguments
                    ))
                server_info['prompts'] = prompts
                self.logger.info(f"Discovered {len(prompts)} prompts on {server_name}")
            except Exception as e:
                self.logger.warning(f"Failed to list prompts: {e}")
                server_info['prompts'] = []
            
        except Exception as e:
            self.logger.error(f"Failed to discover capabilities for {server_name}: {e}")
            raise
    
    async def invoke_tool(self, server_name: str, tool_name: str, 
                         parameters: Dict[str, Any]) -> Tuple[bool, Any]:
        """
        Invoke a tool on a real MCP server.
        
        Args:
            server_name: Name of the connected server
            tool_name: Name of the tool to invoke
            parameters: Dictionary of parameter values
            
        Returns:
            Tuple of (success boolean, result or error message)
        """
        if server_name not in self.connected_servers:
            return False, f"Server {server_name} is not connected"
        
        server_info = self.connected_servers[server_name]
        session = server_info['session']
        
        # Find the tool
        tool = None
        for t in server_info['tools']:
            if t.name == tool_name:
                tool = t
                break
        
        if tool is None:
            return False, f"Tool {tool_name} not found on server {server_name}"
        
        # Validate parameters
        validation_result = self._validate_parameters(tool, parameters)
        if not validation_result[0]:
            return False, f"Parameter validation failed: {validation_result[1]}"
        
        try:
            # Actually invoke the tool using MCP protocol
            self.logger.info(f"Invoking tool {tool_name} with parameters: {parameters}")
            
            result = await session.call_tool(tool_name, arguments=parameters)
            
            # Parse the result
            parsed_result = {
                'isError': result.isError if hasattr(result, 'isError') else False,
                'content': []
            }
            
            for content_item in result.content:
                if isinstance(content_item, TextContent):
                    parsed_result['content'].append({
                        'type': 'text',
                        'text': content_item.text
                    })
                elif isinstance(content_item, ImageContent):
                    parsed_result['content'].append({
                        'type': 'image',
                        'data': content_item.data,
                        'mimeType': content_item.mimeType
                    })
                elif isinstance(content_item, EmbeddedResource):
                    parsed_result['content'].append({
                        'type': 'resource',
                        'resource': {
                            'uri': content_item.resource.uri,
                            'mimeType': content_item.resource.mimeType if hasattr(content_item.resource, 'mimeType') else None,
                            'text': content_item.resource.text if hasattr(content_item.resource, 'text') else None
                        }
                    })
                else:
                    # Handle generic content
                    parsed_result['content'].append({
                        'type': 'unknown',
                        'data': str(content_item)
                    })
            
            return True, parsed_result
            
        except Exception as e:
            self.logger.error(f"Tool invocation failed: {e}")
            return False, f"Tool invocation failed: {str(e)}"
    
    def _validate_parameters(self, tool: MCPTool, parameters: Dict[str, Any]) -> Tuple[bool, str]:
        """Validate parameters against tool's input schema."""
        required_params = tool.get_required_parameters()
        param_properties = tool.get_parameter_properties()
        
        # Check required parameters
        for required_param in required_params:
            if required_param not in parameters:
                return False, f"Missing required parameter: {required_param}"
        
        # Check parameter types
        for param_name, param_value in parameters.items():
            if param_name not in param_properties:
                return False, f"Unknown parameter: {param_name}"
            
            expected_type = param_properties[param_name].get('type')
            
            # Skip validation for None values on optional parameters
            if param_value is None and param_name not in required_params:
                continue
            
            if expected_type == 'string' and not isinstance(param_value, str):
                return False, f"Parameter {param_name} must be a string"
            elif expected_type == 'integer' and not isinstance(param_value, int):
                return False, f"Parameter {param_name} must be an integer"
            elif expected_type == 'number' and not isinstance(param_value, (int, float)):
                return False, f"Parameter {param_name} must be a number"
            elif expected_type == 'boolean' and not isinstance(param_value, bool):
                return False, f"Parameter {param_name} must be a boolean"
            elif expected_type == 'array' and not isinstance(param_value, list):
                return False, f"Parameter {param_name} must be an array"
            elif expected_type == 'object' and not isinstance(param_value, dict):
                return False, f"Parameter {param_name} must be an object"
        
        return True, "Valid"
    
    async def read_resource(self, server_name: str, resource_uri: str) -> Tuple[bool, Any]:
        """
        Read a resource from an MCP server.
        
        Args:
            server_name: Name of the connected server
            resource_uri: URI of the resource to read
            
        Returns:
            Tuple of (success boolean, resource content or error message)
        """
        if server_name not in self.connected_servers:
            return False, f"Server {server_name} is not connected"
        
        server_info = self.connected_servers[server_name]
        session = server_info['session']
        
        try:
            result = await session.read_resource(resource_uri)
            
            parsed_result = {
                'uri': resource_uri,
                'contents': []
            }
            
            for content_item in result.contents:
                if isinstance(content_item, TextContent):
                    parsed_result['contents'].append({
                        'type': 'text',
                        'text': content_item.text,
                        'mimeType': content_item.mimeType if hasattr(content_item, 'mimeType') else None
                    })
                elif isinstance(content_item, ImageContent):
                    parsed_result['contents'].append({
                        'type': 'image',
                        'data': content_item.data,
                        'mimeType': content_item.mimeType
                    })
                else:
                    parsed_result['contents'].append({
                        'type': 'unknown',
                        'data': str(content_item)
                    })
            
            return True, parsed_result
            
        except Exception as e:
            self.logger.error(f"Resource read failed: {e}")
            return False, f"Failed to read resource: {str(e)}"
    
    async def get_prompt(self, server_name: str, prompt_name: str, 
                        arguments: Dict[str, str]) -> Tuple[bool, Any]:
        """
        Get a prompt from an MCP server.
        
        Args:
            server_name: Name of the connected server
            prompt_name: Name of the prompt
            arguments: Arguments for the prompt
            
        Returns:
            Tuple of (success boolean, prompt content or error message)
        """
        if server_name not in self.connected_servers:
            return False, f"Server {server_name} is not connected"
        
        server_info = self.connected_servers[server_name]
        session = server_info['session']
        
        try:
            result = await session.get_prompt(prompt_name, arguments=arguments)
            
            parsed_result = {
                'description': result.description if hasattr(result, 'description') else None,
                'messages': []
            }
            
            for message in result.messages:
                msg = {
                    'role': message.role,
                    'content': []
                }
                
                if isinstance(message.content, str):
                    msg['content'].append({
                        'type': 'text',
                        'text': message.content
                    })
                elif isinstance(message.content, list):
                    for content_item in message.content:
                        if isinstance(content_item, TextContent):
                            msg['content'].append({
                                'type': 'text',
                                'text': content_item.text
                            })
                        elif isinstance(content_item, ImageContent):
                            msg['content'].append({
                                'type': 'image',
                                'data': content_item.data,
                                'mimeType': content_item.mimeType
                            })
                        else:
                            msg['content'].append({
                                'type': 'unknown',
                                'data': str(content_item)
                            })
                
                parsed_result['messages'].append(msg)
            
            return True, parsed_result
            
        except Exception as e:
            self.logger.error(f"Get prompt failed: {e}")
            return False, f"Failed to get prompt: {str(e)}"
    
    def get_server_tools(self, server_name: str) -> List[MCPTool]:
        """Get the list of tools for a connected server."""
        if server_name in self.connected_servers:
            return self.connected_servers[server_name].get('tools', [])
        return []
    
    def get_server_resources(self, server_name: str) -> List[MCPResource]:
        """Get the list of resources for a connected server."""
        if server_name in self.connected_servers:
            return self.connected_servers[server_name].get('resources', [])
        return []
    
    def get_server_prompts(self, server_name: str) -> List[MCPPrompt]:
        """Get the list of prompts for a connected server."""
        if server_name in self.connected_servers:
            return self.connected_servers[server_name].get('prompts', [])
        return []
    
    def is_connected(self, server_name: str) -> bool:
        """Check if a server is currently connected."""
        return server_name in self.connected_servers
    
    async def disconnect_server(self, server_name: str) -> None:
        """Disconnect from an MCP server and clean up resources."""
        if server_name in self.connected_servers:
            server_info = self.connected_servers[server_name]
            
            try:
                # Properly close the session
                session = server_info.get('session')
                if session:
                    await session.__aexit__(None, None, None)
            except Exception as e:
                self.logger.warning(f"Error closing session: {e}")
            
            try:
                # Close the stdio transport
                stdio_context = server_info.get('stdio_context')
                if stdio_context:
                    await stdio_context.__aexit__(None, None, None)
            except Exception as e:
                self.logger.warning(f"Error closing stdio transport: {e}")
            
            del self.connected_servers[server_name]
            self.logger.info(f"Disconnected from {server_name}")


# ============================================================================
# GUI COMPONENTS
# ============================================================================

class ServerFetchThread(QThread):
    """Background thread for fetching server listings from hubs."""
    
    servers_fetched = pyqtSignal(list)
    fetch_error = pyqtSignal(str)
    
    def __init__(self, hub_connector: HubConnector):
        super().__init__()
        self.hub_connector = hub_connector
    
    def run(self):
        """Execute the server fetch operation in background."""
        try:
            servers = self.hub_connector.fetch_all_servers()
            self.servers_fetched.emit(servers)
        except Exception as e:
            self.fetch_error.emit(str(e))


class ServerConnectionThread(QThread):
    """Background thread for connecting to MCP servers."""
    
    connection_result = pyqtSignal(bool, str, list)
    
    def __init__(self, mcp_client: RealMCPClient, server: Dict[str, Any]):
        super().__init__()
        self.mcp_client = mcp_client
        self.server = server
    
    def run(self):
        """Execute server connection in background."""
        try:
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            
            success, message = loop.run_until_complete(
                self.mcp_client.connect_to_server(self.server)
            )
            
            if success:
                tools = self.mcp_client.get_server_tools(self.server['name'])
                self.connection_result.emit(True, message, tools)
            else:
                self.connection_result.emit(False, message, [])
            
            loop.close()
                
        except Exception as e:
            self.connection_result.emit(False, str(e), [])


class ToolTestThread(QThread):
    """Background thread for testing MCP server tools."""
    
    test_result = pyqtSignal(bool, object)
    
    def __init__(self, mcp_client: RealMCPClient, server_name: str, 
                 tool_name: str, parameters: Dict[str, Any]):
        super().__init__()
        self.mcp_client = mcp_client
        self.server_name = server_name
        self.tool_name = tool_name
        self.parameters = parameters
    
    def run(self):
        """Execute tool test in background."""
        try:
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            
            success, result = loop.run_until_complete(
                self.mcp_client.invoke_tool(
                    self.server_name,
                    self.tool_name,
                    self.parameters
                )
            )
            
            self.test_result.emit(success, result)
            loop.close()
            
        except Exception as e:
            self.test_result.emit(False, str(e))


class MCPBrowserMainWindow(QMainWindow):
    """Main window for the MCP Server Browser application."""
    
    def __init__(self, config_manager: ConfigurationManager, 
                 hub_connector: HubConnector, mcp_client: RealMCPClient):
        super().__init__()
        
        self.config_manager = config_manager
        self.hub_connector = hub_connector
        self.mcp_client = mcp_client
        
        self.all_servers = []
        self.filtered_servers = []
        self.selected_server = None
        self.param_inputs = {}
        
        self._init_ui()
        self._apply_theme()
        self._fetch_servers()
    
    def _init_ui(self):
        """Initialize the user interface components."""
        window_width = self.config_manager.get_ui_setting('window_width', 1200)
        window_height = self.config_manager.get_ui_setting('window_height', 800)
        self.setWindowTitle("MCP Server Browser (Real SDK Integration)")
        self.setGeometry(100, 100, window_width, window_height)
        
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        
        # Toolbar
        toolbar_layout = QHBoxLayout()
        
        refresh_button = QPushButton("Refresh Servers")
        refresh_button.clicked.connect(self._fetch_servers)
        toolbar_layout.addWidget(refresh_button)
        
        clear_cache_button = QPushButton("Clear Cache")
        clear_cache_button.clicked.connect(self._clear_cache)
        toolbar_layout.addWidget(clear_cache_button)
        
        toolbar_layout.addStretch()
        
        # SDK status indicator
        sdk_status = QLabel("✓ MCP SDK Available" if MCP_AVAILABLE else "✗ MCP SDK Not Installed")
        sdk_status.setStyleSheet(
            "color: green; font-weight: bold;" if MCP_AVAILABLE else "color: red; font-weight: bold;"
        )
        toolbar_layout.addWidget(sdk_status)
        
        server_count_label = QLabel("Servers: 0")
        self.server_count_label = server_count_label
        toolbar_layout.addWidget(server_count_label)
        
        main_layout.addLayout(toolbar_layout)
        
        # Content area
        content_splitter = QSplitter(Qt.Orientation.Horizontal)
        
        # Left panel
        left_panel = QWidget()
        left_layout = QVBoxLayout(left_panel)
        
        search_label = QLabel("Search Servers (supports regex):")
        left_layout.addWidget(search_label)
        
        search_input = QLineEdit()
        search_input.setPlaceholderText("Enter search term or regex pattern...")
        search_input.textChanged.connect(self._filter_servers)
        self.search_input = search_input
        left_layout.addWidget(search_input)
        
        server_list = QListWidget()
        server_list.itemClicked.connect(self._on_server_selected)
        self.server_list = server_list
        left_layout.addWidget(server_list)
        
        content_splitter.addWidget(left_panel)
        
        # Right panel
        right_panel = QTabWidget()
        self.details_tab = self._create_details_tab()
        self.tools_tab = self._create_tools_tab()
        self.resources_tab = self._create_resources_tab()
        self.prompts_tab = self._create_prompts_tab()
        self.code_tab = self._create_code_tab()
        self.test_tab = self._create_test_tab()
        
        right_panel.addTab(self.details_tab, "Details")
        right_panel.addTab(self.tools_tab, "Tools")
        right_panel.addTab(self.resources_tab, "Resources")
        right_panel.addTab(self.prompts_tab, "Prompts")
        right_panel.addTab(self.code_tab, "Usage Code")
        right_panel.addTab(self.test_tab, "Test Tool")
        
        content_splitter.addWidget(right_panel)
        
        content_splitter.setStretchFactor(0, 1)
        content_splitter.setStretchFactor(1, 2)
        
        main_layout.addWidget(content_splitter)
        
        self.statusBar().showMessage("Ready - Using Real MCP SDK" if MCP_AVAILABLE else "Ready - MCP SDK Not Available")
    
    def _create_details_tab(self) -> QWidget:
        """Create the server details tab."""
        details_widget = QWidget()
        details_layout = QVBoxLayout(details_widget)
        
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        
        scroll_content = QWidget()
        scroll_layout = QFormLayout(scroll_content)
        
        self.name_label = QLabel("No server selected")
        self.name_label.setWordWrap(True)
        font = self.name_label.font()
        font.setPointSize(14)
        font.setBold(True)
        self.name_label.setFont(font)
        
        self.description_label = QLabel("")
        self.description_label.setWordWrap(True)
        
        self.status_label = QLabel("")
        self.version_label = QLabel("")
        self.repository_label = QLabel("")
        self.repository_label.setOpenExternalLinks(True)
        
        self.command_label = QLabel("")
        self.command_label.setWordWrap(True)
        
        self.packages_text = QTextEdit()
        self.packages_text.setReadOnly(True)
        self.packages_text.setMaximumHeight(150)
        
        scroll_layout.addRow("Name:", self.name_label)
        scroll_layout.addRow("Description:", self.description_label)
        scroll_layout.addRow("Status:", self.status_label)
        scroll_layout.addRow("Version:", self.version_label)
        scroll_layout.addRow("Repository:", self.repository_label)
        scroll_layout.addRow("Command:", self.command_label)
        scroll_layout.addRow("Packages:", self.packages_text)
        
        scroll_area.setWidget(scroll_content)
        details_layout.addWidget(scroll_area)
        
        return details_widget
    
    def _create_tools_tab(self) -> QWidget:
        """Create the tools tab."""
        tools_widget = QWidget()
        tools_layout = QVBoxLayout(tools_widget)
        
        connect_button = QPushButton("Connect to Server")
        connect_button.clicked.connect(self._connect_to_selected_server)
        self.connect_button = connect_button
        tools_layout.addWidget(connect_button)
        
        self.connection_status_label = QLabel("Not connected")
        tools_layout.addWidget(self.connection_status_label)
        
        self.tools_text = QTextEdit()
        self.tools_text.setReadOnly(True)
        tools_layout.addWidget(self.tools_text)
        
        return tools_widget
    
    def _create_resources_tab(self) -> QWidget:
        """Create the resources tab."""
        resources_widget = QWidget()
        resources_layout = QVBoxLayout(resources_widget)
        
        resources_label = QLabel("Available Resources:")
        resources_layout.addWidget(resources_label)
        
        self.resources_list = QListWidget()
        self.resources_list.itemDoubleClicked.connect(self._read_resource)
        resources_layout.addWidget(self.resources_list)
        
        read_button = QPushButton("Read Selected Resource")
        read_button.clicked.connect(lambda: self._read_resource(self.resources_list.currentItem()))
        resources_layout.addWidget(read_button)
        
        self.resource_content = QTextEdit()
        self.resource_content.setReadOnly(True)
        resources_layout.addWidget(self.resource_content)
        
        return resources_widget
    
    def _create_prompts_tab(self) -> QWidget:
        """Create the prompts tab."""
        prompts_widget = QWidget()
        prompts_layout = QVBoxLayout(prompts_widget)
        
        prompts_label = QLabel("Available Prompts:")
        prompts_layout.addWidget(prompts_label)
        
        self.prompts_text = QTextEdit()
        self.prompts_text.setReadOnly(True)
        prompts_layout.addWidget(self.prompts_text)
        
        return prompts_widget
    
    def _create_code_tab(self) -> QWidget:
        """Create the usage code examples tab."""
        code_widget = QWidget()
        code_layout = QVBoxLayout(code_widget)
        
        code_label = QLabel("Python code to use this MCP server:")
        code_layout.addWidget(code_label)
        
        self.code_text = QTextEdit()
        self.code_text.setReadOnly(True)
        self.code_text.setFontFamily("Courier New")
        code_layout.addWidget(self.code_text)
        
        return code_widget
    
    def _create_test_tab(self) -> QWidget:
        """Create the server testing tab."""
        test_widget = QWidget()
        test_layout = QVBoxLayout(test_widget)
        
        tool_group = QGroupBox("Select Tool")
        tool_group_layout = QVBoxLayout(tool_group)
        
        self.tool_combo = QComboBox()
        self.tool_combo.currentTextChanged.connect(self._on_tool_selected)
        tool_group_layout.addWidget(self.tool_combo)
        
        test_layout.addWidget(tool_group)
        
        params_group = QGroupBox("Parameters")
        params_group_layout = QVBoxLayout(params_group)
        
        self.params_scroll = QScrollArea()
        self.params_scroll.setWidgetResizable(True)
        self.params_widget = QWidget()
        self.params_layout = QFormLayout(self.params_widget)
        self.params_scroll.setWidget(self.params_widget)
        
        params_group_layout.addWidget(self.params_scroll)
        test_layout.addWidget(params_group)
        
        test_button = QPushButton("Test Tool")
        test_button.clicked.connect(self._test_tool)
        self.test_button = test_button
        test_layout.addWidget(test_button)
        
        results_label = QLabel("Results:")
        test_layout.addWidget(results_label)
        
        self.results_text = QTextEdit()
        self.results_text.setReadOnly(True)
        test_layout.addWidget(self.results_text)
        
        return test_widget
    
    def _apply_theme(self):
        """Apply visual theme to the application."""
        theme = self.config_manager.get_ui_setting('theme', 'light')
        font_size = self.config_manager.get_ui_setting('font_size', 10)
        
        app_font = QFont()
        app_font.setPointSize(font_size)
        self.setFont(app_font)
        
        if theme == 'dark':
            palette = QPalette()
            palette.setColor(QPalette.ColorRole.Window, QColor(53, 53, 53))
            palette.setColor(QPalette.ColorRole.WindowText, Qt.GlobalColor.white)
            palette.setColor(QPalette.ColorRole.Base, QColor(25, 25, 25))
            palette.setColor(QPalette.ColorRole.AlternateBase, QColor(53, 53, 53))
            palette.setColor(QPalette.ColorRole.Text, Qt.GlobalColor.white)
            palette.setColor(QPalette.ColorRole.Button, QColor(53, 53, 53))
            palette.setColor(QPalette.ColorRole.ButtonText, Qt.GlobalColor.white)
            self.setPalette(palette)
    
    def _fetch_servers(self):
        """Fetch server listings from configured hubs."""
        self.statusBar().showMessage("Fetching servers from hubs...")
        self.server_list.clear()
        
        self.fetch_thread = ServerFetchThread(self.hub_connector)
        self.fetch_thread.servers_fetched.connect(self._on_servers_fetched)
        self.fetch_thread.fetch_error.connect(self._on_fetch_error)
        self.fetch_thread.start()
    
    def _on_servers_fetched(self, servers):
        """Handle successful server fetch."""
        self.all_servers = servers
        self.filtered_servers = servers
        self._update_server_list()
        self.statusBar().showMessage(f"Loaded {len(servers)} servers")
        self.server_count_label.setText(f"Servers: {len(servers)}")
    
    def _on_fetch_error(self, error_message):
        """Handle server fetch error."""
        self.statusBar().showMessage(f"Error: {error_message}")
        QMessageBox.warning(self, "Fetch Error", f"Failed to fetch servers:\n{error_message}")
    
    def _filter_servers(self, search_text):
        """Filter server list based on search text."""
        if not search_text:
            self.filtered_servers = self.all_servers
        else:
            try:
                pattern = re.compile(search_text, re.IGNORECASE)
                self.filtered_servers = [
                    server for server in self.all_servers
                    if pattern.search(server['name']) or pattern.search(server.get('description', ''))
                ]
            except re.error:
                search_lower = search_text.lower()
                self.filtered_servers = [
                    server for server in self.all_servers
                    if search_lower in server['name'].lower() or 
                       search_lower in server.get('description', '').lower()
                ]
        
        self._update_server_list()
    
    def _update_server_list(self):
        """Update the server list widget with filtered servers."""
        self.server_list.clear()
        
        for server in self.filtered_servers:
            item = QListWidgetItem(server['name'])
            item.setData(Qt.ItemDataRole.UserRole, server)
            
            # Color code by status and availability
            if server.get('command'):
                if server.get('status') == 'active':
                    item.setForeground(QColor(0, 128, 0))
                else:
                    item.setForeground(QColor(128, 128, 0))
            else:
                item.setForeground(QColor(128, 128, 128))
            
            self.server_list.addItem(item)
    
    def _on_server_selected(self, item):
        """Handle server selection from the list."""
        server = item.data(Qt.ItemDataRole.UserRole)
        self.selected_server = server
        self._display_server_details(server)
    
    def _display_server_details(self, server):
        """Display detailed information about a server."""
        self.name_label.setText(server['name'])
        self.description_label.setText(server.get('description', 'No description available'))
        self.status_label.setText(server.get('status', 'unknown'))
        self.version_label.setText(server.get('version', 'unknown'))
        
        repo_url = server.get('repository_url', '')
        if repo_url:
            self.repository_label.setText(f'<a href="{repo_url}">{repo_url}</a>')
        else:
            self.repository_label.setText('Not available')
        
        # Display command
        command = server.get('command', 'Not specified')
        args = server.get('args', [])
        if command and args:
            command_str = f"{command} {' '.join(args)}"
        elif command:
            command_str = command
        else:
            command_str = "Not specified - cannot connect"
        self.command_label.setText(command_str)
        
        packages = server.get('packages', [])
        if packages:
            packages_text = ""
            for pkg in packages:
                registry_type = pkg.get('registry_type', 'unknown')
                package_name = pkg.get('package_name', 'unknown')
                version_constraint = pkg.get('version_constraint', '')
                packages_text += f"{registry_type}: {package_name} {version_constraint}\n"
            self.packages_text.setPlainText(packages_text)
        else:
            self.packages_text.setPlainText("No package information available")
        
        self._generate_usage_code(server)
        
        self.connection_status_label.setText("Not connected")
        self.tools_text.clear()
        self.tool_combo.clear()
        self.resources_list.clear()
        self.resource_content.clear()
        self.prompts_text.clear()
    
    def _generate_usage_code(self, server):
        """Generate Python code examples for using the server."""
        packages = server.get('packages', [])
        command = server.get('command', 'server-command')
        args = server.get('args', [])
        
        code = "# Python code to use this MCP server with the official SDK\n\n"
        
        if packages:
            code += "# Installation:\n"
            for pkg in packages:
                registry_type = pkg.get('registry_type', '')
                package_name = pkg.get('package_name', '')
                if registry_type == 'npm':
                    code += f"# npm install {package_name}\n"
                elif registry_type == 'pypi':
                    code += f"# pip install {package_name}\n"
            code += "\n"
        
        code += "# Install MCP SDK:\n"
        code += "# pip install mcp\n\n"
        
        code += "# Real working example:\n"
        code += "import asyncio\n"
        code += "from mcp import ClientSession, StdioServerParameters\n"
        code += "from mcp.client.stdio import stdio_client\n\n"
        code += "async def main():\n"
        code += "    # Configure server parameters\n"
        code += f"    server_params = StdioServerParameters(\n"
        code += f"        command=\"{command}\",\n"
        
        if args:
            code += f"        args={args}\n"
        else:
            code += "        args=[]\n"
        
        code += "    )\n\n"
        code += "    # Connect to server using stdio transport\n"
        code += "    async with stdio_client(server_params) as (read, write):\n"
        code += "        async with ClientSession(read, write) as session:\n"
        code += "            # Initialize connection\n"
        code += "            await session.initialize()\n\n"
        code += "            # List available tools\n"
        code += "            tools = await session.list_tools()\n"
        code += "            print(f\"Available tools: {[t.name for t in tools.tools]}\")\n\n"
        code += "            # Call a tool (example)\n"
        code += "            if tools.tools:\n"
        code += "                result = await session.call_tool(\n"
        code += "                    tools.tools[0].name,\n"
        code += "                    arguments={}\n"
        code += "                )\n"
        code += "                print(f\"Result: {result}\")\n\n"
        code += "if __name__ == \"__main__\":\n"
        code += "    asyncio.run(main())\n"
        
        highlighted_code = highlight(code, PythonLexer(), HtmlFormatter())
        self.code_text.setHtml(highlighted_code)
    
    def _connect_to_selected_server(self):
        """Connect to the currently selected server."""
        if not self.selected_server:
            QMessageBox.warning(self, "No Server Selected", "Please select a server first.")
            return
        
        if not MCP_AVAILABLE:
            QMessageBox.critical(
                self, 
                "MCP SDK Not Available", 
                "The MCP SDK is not installed. Please install it with:\n\npip install mcp"
            )
            return
        
        self.connect_button.setEnabled(False)
        self.connection_status_label.setText("Connecting...")
        self.statusBar().showMessage("Connecting to server...")
        
        self.connection_thread = ServerConnectionThread(
            self.mcp_client,
            self.selected_server
        )
        self.connection_thread.connection_result.connect(self._on_connection_result)
        self.connection_thread.start()
    
    def _on_connection_result(self, success, message, tools):
        """Handle connection result."""
        self.connect_button.setEnabled(True)
        
        if success:
            self.connection_status_label.setText(f"✓ Connected: {message}")
            self.connection_status_label.setStyleSheet("color: green; font-weight: bold;")
            self.statusBar().showMessage("Successfully connected to server")
            
            # Display tools
            if tools:
                tools_text = "Available Tools:\n\n"
                for tool in tools:
                    tools_text += f"Tool: {tool.name}\n"
                    tools_text += f"Description: {tool.description}\n"
                    tools_text += f"Parameters: {json.dumps(tool.input_schema, indent=2)}\n\n"
                self.tools_text.setPlainText(tools_text)
                
                self.tool_combo.clear()
                for tool in tools:
                    self.tool_combo.addItem(tool.name, tool)
            else:
                self.tools_text.setPlainText("No tools available on this server")
            
            # Display resources
            resources = self.mcp_client.get_server_resources(self.selected_server['name'])
            self.resources_list.clear()
            for resource in resources:
                item = QListWidgetItem(f"{resource.name} ({resource.uri})")
                item.setData(Qt.ItemDataRole.UserRole, resource)
                self.resources_list.addItem(item)
            
            # Display prompts
            prompts = self.mcp_client.get_server_prompts(self.selected_server['name'])
            if prompts:
                prompts_text = "Available Prompts:\n\n"
                for prompt in prompts:
                    prompts_text += f"Prompt: {prompt.name}\n"
                    prompts_text += f"Description: {prompt.description}\n"
                    prompts_text += f"Arguments: {json.dumps(prompt.arguments, indent=2)}\n\n"
                self.prompts_text.setPlainText(prompts_text)
            else:
                self.prompts_text.setPlainText("No prompts available on this server")
            
        else:
            self.connection_status_label.setText(f"✗ Connection failed: {message}")
            self.connection_status_label.setStyleSheet("color: red; font-weight: bold;")
            self.statusBar().showMessage(f"Connection failed: {message}")
            QMessageBox.warning(self, "Connection Failed", message)
    
    def _read_resource(self, item):
        """Read a resource from the connected server."""
        if not item:
            return
        
        if not self.selected_server or not self.mcp_client.is_connected(self.selected_server['name']):
            QMessageBox.warning(self, "Not Connected", "Please connect to the server first.")
            return
        
        resource = item.data(Qt.ItemDataRole.UserRole)
        
        # Create async task to read resource
        async def read():
            return await self.mcp_client.read_resource(self.selected_server['name'], resource.uri)
        
        try:
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            success, result = loop.run_until_complete(read())
            loop.close()
            
            if success:
                content_text = f"Resource: {result['uri']}\n\n"
                for content in result['contents']:
                    if content['type'] == 'text':
                        content_text += content['text'] + "\n"
                    elif content['type'] == 'image':
                        content_text += f"[Image: {content['mimeType']}]\n"
                    else:
                        content_text += f"[{content['type']}]\n"
                self.resource_content.setPlainText(content_text)
            else:
                QMessageBox.warning(self, "Read Failed", f"Failed to read resource:\n{result}")
        except Exception as e:
            QMessageBox.critical(self, "Error", f"Error reading resource:\n{str(e)}")
    
    def _on_tool_selected(self, tool_name):
        """Handle tool selection for testing."""
        # Clear previous parameters
        while self.params_layout.count():
            child = self.params_layout.takeAt(0)
            if child.widget():
                child.widget().deleteLater()
        
        if not tool_name:
            return
        
        tool = self.tool_combo.currentData()
        if not tool:
            return
        
        properties = tool.get_parameter_properties()
        required = tool.get_required_parameters()
        
        self.param_inputs = {}
        
        for param_name, param_def in properties.items():
            param_type = param_def.get('type', 'string')
            param_desc = param_def.get('description', '')
            is_required = param_name in required
            
            label_text = f"{param_name}{'*' if is_required else ''}:"
            label = QLabel(label_text)
            label.setToolTip(param_desc)
            
            # Create appropriate input widget based on type
            if param_type == 'string':
                if 'enum' in param_def:
                    input_widget = QComboBox()
                    input_widget.addItems(param_def['enum'])
                else:
                    input_widget = QLineEdit()
                    input_widget.setPlaceholderText(param_desc)
            elif param_type == 'integer':
                input_widget = QSpinBox()
                input_widget.setRange(-2147483648, 2147483647)
                if 'minimum' in param_def:
                    input_widget.setMinimum(param_def['minimum'])
                if 'maximum' in param_def:
                    input_widget.setMaximum(param_def['maximum'])
            elif param_type == 'number':
                input_widget = QDoubleSpinBox()
                input_widget.setRange(-1e10, 1e10)
                input_widget.setDecimals(6)
                if 'minimum' in param_def:
                    input_widget.setMinimum(param_def['minimum'])
                if 'maximum' in param_def:
                    input_widget.setMaximum(param_def['maximum'])
            elif param_type == 'boolean':
                input_widget = QCheckBox()
            elif param_type == 'array':
                input_widget = QLineEdit()
                input_widget.setPlaceholderText("Enter JSON array, e.g., [1, 2, 3]")
            elif param_type == 'object':
                input_widget = QTextEdit()
                input_widget.setPlaceholderText("Enter JSON object, e.g., {\"key\": \"value\"}")
                input_widget.setMaximumHeight(100)
            else:
                input_widget = QLineEdit()
                input_widget.setPlaceholderText(param_desc)
            
            self.param_inputs[param_name] = (input_widget, param_type)
            self.params_layout.addRow(label, input_widget)
    
    def _test_tool(self):
        """Test the selected tool with provided parameters."""
        if not self.selected_server:
            QMessageBox.warning(self, "No Server", "No server selected")
            return
        
        if not self.mcp_client.is_connected(self.selected_server['name']):
            QMessageBox.warning(self, "Not Connected", "Please connect to the server first.")
            return
        
        tool_name = self.tool_combo.currentText()
        if not tool_name:
            QMessageBox.warning(self, "No Tool", "No tool selected")
            return
        
        # Collect parameters
        parameters = {}
        try:
            for param_name, (input_widget, param_type) in self.param_inputs.items():
                value = None
                
                if isinstance(input_widget, QLineEdit):
                    text = input_widget.text().strip()
                    if text:
                        if param_type == 'integer':
                            value = int(text)
                        elif param_type == 'number':
                            value = float(text)
                        elif param_type == 'array':
                            value = json.loads(text)
                        else:
                            value = text
                elif isinstance(input_widget, QTextEdit):
                    text = input_widget.toPlainText().strip()
                    if text:
                        if param_type == 'object':
                            value = json.loads(text)
                        else:
                            value = text
                elif isinstance(input_widget, QComboBox):
                    value = input_widget.currentText()
                elif isinstance(input_widget, (QSpinBox, QDoubleSpinBox)):
                    value = input_widget.value()
                elif isinstance(input_widget, QCheckBox):
                    value = input_widget.isChecked()
                
                # Only add non-None values
                if value is not None or (isinstance(value, bool) and value is False):
                    parameters[param_name] = value
                    
        except (ValueError, json.JSONDecodeError) as e:
            QMessageBox.warning(self, "Invalid Input", f"Invalid parameter value:\n{str(e)}")
            return
        
        self.test_button.setEnabled(False)
        self.results_text.setPlainText("Executing tool via real MCP connection...")
        
        self.tool_test_thread = ToolTestThread(
            self.mcp_client,
            self.selected_server['name'],
            tool_name,
            parameters
        )
        self.tool_test_thread.test_result.connect(self._on_test_result)
        self.tool_test_thread.start()
    
    def _on_test_result(self, success, result):
        """Handle tool test result."""
        self.test_button.setEnabled(True)
        
        if success:
            result_text = "✓ Tool execution successful!\n\n"
            result_text += "Result:\n"
            result_text += json.dumps(result, indent=2)
            self.results_text.setPlainText(result_text)
        else:
            self.results_text.setPlainText(f"✗ Tool execution failed:\n{result}")
    
    def _clear_cache(self):
        """Clear the hub data cache."""
        self.hub_connector.clear_cache()
        self.statusBar().showMessage("Cache cleared")
        QMessageBox.information(self, "Cache Cleared", "Hub cache has been cleared successfully.")
    
    def closeEvent(self, event):
        """Handle application close event to clean up connections."""
        # Disconnect all servers
        if self.mcp_client.connected_servers:
            reply = QMessageBox.question(
                self,
                "Disconnect Servers",
                "Disconnect from all connected servers before closing?",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                QMessageBox.StandardButton.Yes
            )
            
            if reply == QMessageBox.StandardButton.Yes:
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)
                
                for server_name in list(self.mcp_client.connected_servers.keys()):
                    try:
                        loop.run_until_complete(self.mcp_client.disconnect_server(server_name))
                    except Exception as e:
                        self.logger.warning(f"Error disconnecting from {server_name}: {e}")
                
                loop.close()
        
        event.accept()


# ============================================================================
# MAIN APPLICATION
# ============================================================================

def setup_logging():
    """Configure application logging."""
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler('mcp_browser.log'),
            logging.StreamHandler()
        ]
    )


def main():
    """Main application entry point."""
    setup_logging()
    logger = logging.getLogger(__name__)
    
    logger.info("Starting MCP Server Browser application")
    
    if not MCP_AVAILABLE:
        logger.warning("MCP SDK not available - limited functionality")
    
    try:
        config_manager = ConfigurationManager()
        hub_connector = HubConnector(config_manager)
        mcp_client = RealMCPClient(config_manager)
        
        app = QApplication(sys.argv)
        app.setApplicationName("MCP Server Browser")
        app.setOrganizationName("MCP Tools")
        
        main_window = MCPBrowserMainWindow(config_manager, hub_connector, mcp_client)
        main_window.show()
        
        logger.info("Application started successfully")
        
        sys.exit(app.exec())
        
    except Exception as e:
        logger.error(f"Application failed to start: {e}", exc_info=True)
        QMessageBox.critical(None, "Startup Error", f"Failed to start application:\n{str(e)}")
        sys.exit(1)


if __name__ == "__main__":
    main()


Configuration file (mcp_browser_config.json):

{
    "hubs": [
        {
            "name": "Official MCP Registry",
            "url": "https://registry.modelcontextprotocol.io/v0/servers",
            "type": "official",
            "enabled": true
        }
    ],
    "connection": {
        "timeout_seconds": 30,
        "max_retries": 3,
        "retry_delay_seconds": 2
    },
    "ui": {
        "theme": "light",
        "font_size": 10,
        "window_width": 1200,
        "window_height": 800
    },
    "cache": {
        "enabled": true,
        "ttl_minutes": 60
    },
    "mcp": {
        "default_transport": "stdio",
        "stdio_timeout": 10,
        "enable_logging": true
    }
}

Requirements (requirements.txt):

mcp>=1.0.0
PyQt6>=6.6.0
requests>=2.31.0
Pygments>=2.17.0



How to Use:

  1. Install dependencies: pip install -r requirements.txt
  2. Install an MCP server (e.g., npm install -g @modelcontextprotocol/server-filesystem)
  3. Run: python mcp_browser.py
  4. Browse servers from the registry
  5. Click "Connect to Server" to establish real connection
  6. Test tools with actual execution!