{"id":27906318,"url":"https://github.com/Dicklesworthstone/ultimate_mcp_client","last_synced_at":"2025-05-06T01:02:02.399Z","repository":{"id":286833842,"uuid":"962698126","full_name":"Dicklesworthstone/ultimate_mcp_client","owner":"Dicklesworthstone","description":null,"archived":false,"fork":false,"pushed_at":"2025-04-25T08:31:53.000Z","size":9637,"stargazers_count":88,"open_issues_count":3,"forks_count":4,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-04-26T15:43:42.494Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Dicklesworthstone.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-04-08T14:39:57.000Z","updated_at":"2025-04-25T08:31:57.000Z","dependencies_parsed_at":null,"dependency_job_id":"4a6bb993-0672-44d2-a658-05d18a15c4a4","html_url":"https://github.com/Dicklesworthstone/ultimate_mcp_client","commit_stats":null,"previous_names":["dicklesworthstone/ultimate_mcp_client"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dicklesworthstone%2Fultimate_mcp_client","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dicklesworthstone%2Fultimate_mcp_client/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dicklesworthstone%2Fultimate_mcp_client/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dicklesworthstone%2Fultimate_mcp_client/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Dicklesworthstone","download_url":"https://codeload.github.com/Dicklesworthstone/ultimate_mcp_client/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252601722,"owners_count":21774663,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-05-06T01:01:59.362Z","updated_at":"2025-05-06T01:02:02.383Z","avatar_url":"https://github.com/Dicklesworthstone.png","language":"Python","funding_links":[],"categories":["Python","📚 Projects (2474 total)","Uncategorized"],"sub_categories":["MCP Servers","Uncategorized"],"readme":"# 🧠 Ultimate MCP Client\n\n\u003cdiv align=\"center\"\u003e\n\n[![Python 3.13+](https://img.shields.io/badge/python-3.13+-blue.svg)](https://www.python.org/downloads/release/python-3130/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![MCP Protocol](https://img.shields.io/badge/Protocol-MCP-purple.svg)](https://github.com/mpctechdebt/mcp)\n[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)\n\nA comprehensive, asynchronous client for the **Model Context Protocol (MCP)**. It bridges the gap between powerful AI models like Anthropic's Claude and a universe of external tools, local/remote servers, and contextual data sources, enabling complex, stateful interactions.\n\n![Web UI Screenshot](https://github.com/Dicklesworthstone/ultimate_mcp_client/blob/main/banner.webp)\n\n\u003c/div\u003e\n\n\u003e Built by Jeffrey Emanuel\n\n---\n\n## 🎯 Purpose \u0026 Motivation\n\nThe Model Context Protocol (MCP) standardizes how AI models interact with external capabilities (tools, resources, prompts). This client aims to be the **ultimate interface** for leveraging MCP, providing:\n\n1.  **Robust Connectivity:** Reliably connect to diverse MCP servers (`stdio`, `sse`) with built-in resilience, advanced error handling, and intelligent discovery.\n2.  **Rich User Experience:** Offer both a powerful interactive CLI and a modern, reactive Web UI, ensuring usability for diverse workflows.\n3.  **Advanced State Management:** Go beyond simple chat history with forkable conversation graphs, persistent state across sessions, and smart context optimization techniques.\n4.  **Developer Introspection:** Provide deep observability via OpenTelemetry metrics and traces, alongside live dashboards for monitoring client and server health and performance.\n5.  **Seamless Integration:** Easily discover and integrate local filesystem scripts, local network (mDNS) servers, local port scan results, remote registry entries, and even configurations from existing tools like the Claude Desktop app.\n\n**This project tackles significant engineering challenges**, especially around reliable `stdio` communication, asynchronous state management, and providing a consistent experience across both CLI and Web interfaces, to deliver a truly comprehensive MCP client solution.\n\n---\n\n## 🔌 Key Features\n\n-   **Dual Interfaces: Web UI \u0026 CLI**\n    -   **Web UI:** Beautiful, reactive interface built with **Alpine.js**, **DaisyUI**, and **Tailwind CSS**. Features real-time chat streaming via WebSockets, server/tool management modals, **visual conversation branching view**, settings configuration, **multiple theme switching** (respecting light/dark modes for code highlighting), and direct tool execution capabilities.\n    -   **CLI:** Feature-rich interactive shell (`/commands`, autocompletion, **Rich** Markdown rendering) and batch-mode operation via **Typer**. Includes a live **Textual User Interface (TUI) dashboard** for monitoring.\n\n-   **Robust Server Connectivity \u0026 Management**\n    -   Supports `stdio` and `sse` (HTTP Server-Sent Events) MCP servers.\n    -   **Advanced STDIO Handling (Key Engineering Effort):** Features a custom `RobustStdioSession` designed to gracefully handle potentially noisy or non-compliant `stdio` servers. It includes:\n        -   *Noise Filtering:* Ignores non-JSON-RPC output that could corrupt the protocol.\n        -   *Direct Future Resolution:* Avoids complex queueing for faster response handling.\n        -   *Process Lifecycle Management:* Reliably starts, monitors, terminates, and kills `stdio` server processes.\n        -   **Critical STDIO Safety:** A multi-layered system (`StdioProtectionWrapper`, `safe_stdout` context manager, `get_safe_console()` function) prevents accidental writes to `sys.stdout` from corrupting the `stdio` channel, ensuring safe coexistence of multiple `stdio` servers and user output (redirected to `stderr` when necessary). This was crucial for stability.\n    -   **Resilience:** Automatic connection retries with exponential backoff and circuit breakers for failing servers (`@retry_with_circuit_breaker`). Background health monitoring (`ServerMonitor`) checks server responsiveness.\n\n-   **Intelligent Server Discovery**\n    -   Auto-discovers local `stdio` servers (Python/JS scripts) in configured filesystem paths.\n    -   **mDNS Discovery (Zeroconf):** Real-time discovery and notification of MCP servers (`_mcp._tcp.local.`) on the local network. Interactive commands (`/discover list`, `/discover connect`, etc.) for managing LAN servers.\n    -   **Local Port Scanning:** Actively scans a configurable range of local ports (e.g., 8000-9000) for MCP servers by attempting an `initialize` handshake. Useful for servers not advertising via mDNS. Configurable via `/config port-scan ...` commands.\n    -   **Registry Integration:** Connects to remote MCP registries (specified in config) to find and add shared servers.\n    -   **Claude Desktop Import:** Automatically detects `claude_desktop_config.json` in the project root. **Intelligently adapts configurations:**\n        -   Remaps `wsl.exe ... bash -c \"cmd\"` calls to direct Linux shell execution (`/bin/bash -c \"cmd\"`).\n        -   Converts Windows-style paths (`C:\\...`) in arguments to their Linux/WSL equivalents (`/mnt/c/...`) using `adapt_path_for_platform` for seamless integration.\n\n-   **Powerful AI Integration \u0026 Streaming**\n    -   Deep integration with Claude models via the official `anthropic` SDK, supporting multi-turn tool use scenarios.\n    -   **Real-time Streaming:** Streams AI responses and tool status updates via WebSockets (Web UI) and live `Rich` rendering (CLI). Handles complex streaming events, including **partial JSON input accumulation (`input_json_delta`)** for tools requiring structured input.\n    -   **Intelligent Tool Routing:** Directs tool calls to the correct originating server based on loaded capabilities, using sanitized names for API compatibility while tracking original names internally.\n    -   **Direct Tool Execution:** Run specific tools with custom JSON parameters via the `/tool` command (CLI) or a dedicated modal (Web UI).\n\n-   **Advanced Conversation Management**\n    -   **Branching:** Forkable conversation graphs (`ConversationGraph`) allow exploring different interaction paths without losing history. Visually represented and navigable in the Web UI.\n    -   **Persistence:** Conversation graphs (including all branches and messages) are automatically saved to JSON files in the config directory, preserving state across sessions.\n    -   **Context Optimization:** Automatic or manual summarization (`/optimize`) of long conversation histories using a specified AI model (configurable) to stay within context limits.\n    -   **Dynamic Prompts:** Inject pre-defined prompt templates obtained from servers into the current conversation context using the `/prompt` command.\n    -   **Import/Export:** Easily save (`/export`) and load (`/import`) entire conversation branches in a portable JSON format for sharing or backup.\n\n-   **Observability \u0026 Monitoring**\n    -   **OpenTelemetry:** Integrated metrics (counters, histograms using `opentelemetry-sdk`) and tracing (spans) for monitoring client operations, server requests, and tool execution performance. Console exporters can be enabled for debugging.\n    -   **Live Dashboards:**\n        -   **CLI:** Real-time TUI dashboard (`/dashboard`) built with `Rich`, showing server health, tool usage stats, and client info.\n        -   **Web UI:** Dynamically updates server status, health indicators, and capability counts.\n\n-   **Smart Caching**\n    -   Optional disk (`diskcache`) and in-memory caching for tool results to improve speed and reduce costs.\n    -   Configurable Time-To-Live (TTL) per tool category (e.g., `weather`, `filesystem`).\n    -   **Dependency Tracking:** Define relationships between tools. Invalidating one tool's cache (e.g., `stock:lookup`) can automatically invalidate dependent caches (e.g., `stock:analyze`). View the graph via `/cache dependencies`.\n\n---\n\n## 📸 Screenshots\n\nA glimpse into the Ultimate MCP Client's interfaces:\n\n\u003cbr/\u003e\n\n\u003ctable\u003e\n  \u003ctbody\u003e\n    \u003ctr\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"50%\"\u003e\n        \u003cimg src=\"https://github.com/Dicklesworthstone/ultimate_mcp_client/blob/main/screenshots/terminal_example_01.webp?raw=true\" alt=\"CLI Interactive Mode showing tool execution and streaming\" width=\"95%\"\u003e\n        \u003cbr/\u003e\n        \u003cp align=\"center\"\u003e\u003csmall\u003e\u003cem\u003eInteractive CLI: Streaming response with tool call/result.\u003c/em\u003e\u003c/small\u003e\u003c/p\u003e\n      \u003c/td\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"50%\"\u003e\n        \u003cimg src=\"https://github.com/Dicklesworthstone/ultimate_mcp_client/blob/main/screenshots/terminal_example_02.webp?raw=true\" alt=\"CLI TUI Dashboard showing server status\" width=\"95%\"\u003e\n        \u003cbr/\u003e\n        \u003cp align=\"center\"\u003e\u003csmall\u003e\u003cem\u003eLive TUI Dashboard: Real-time server \u0026 tool monitoring (\u003ccode\u003e/dashboard\u003c/code\u003e).\u003c/em\u003e\u003c/small\u003e\u003c/p\u003e\n      \u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"33%\"\u003e\n        \u003cimg src=\"https://github.com/Dicklesworthstone/ultimate_mcp_client/blob/main/screenshots/webui_example_01.webp?raw=true\" alt=\"Web UI Chat Interface\" width=\"95%\"\u003e\n        \u003cbr/\u003e\n        \u003cp align=\"center\"\u003e\u003csmall\u003e\u003cem\u003eWeb UI: Main chat interface showing messages and tool interactions.\u003c/em\u003e\u003c/small\u003e\u003c/p\u003e\n      \u003c/td\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"33%\"\u003e\n        \u003cimg src=\"https://github.com/Dicklesworthstone/ultimate_mcp_client/blob/main/screenshots/webui_example_02.webp?raw=true\" alt=\"Web UI Server Management Tab\" width=\"95%\"\u003e\n        \u003cbr/\u003e\n        \u003cp align=\"center\"\u003e\u003csmall\u003e\u003cem\u003eWeb UI: Server management tab with connection status and controls.\u003c/em\u003e\u003c/small\u003e\u003c/p\u003e\n      \u003c/td\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"33%\"\u003e\n        \u003cimg src=\"https://github.com/Dicklesworthstone/ultimate_mcp_client/blob/main/screenshots/webui_example_03.webp?raw=true\" alt=\"Web UI Conversation Branching View\" width=\"95%\"\u003e\n        \u003cbr/\u003e\n        \u003cp align=\"center\"\u003e\u003csmall\u003e\u003cem\u003eWeb UI: Conversation tab showing the branching graph structure.\u003c/em\u003e\u003c/small\u003e\u003c/p\u003e\n      \u003c/td\u003e\n    \u003c/tr\u003e\n  \u003c/tbody\u003e\n\u003c/table\u003e\n\n\u003e **Note:** Some screenshots feature tools like `llm_gateway:generate_completion`. These are provided by the [LLM Gateway MCP Server](https://github.com/Dicklesworthstone/llm_gateway_mcp_server), another project by the same author. This server acts as an MCP-native gateway, enabling advanced agents (like Claude, used by *this* client) to intelligently delegate tasks to various other LLMs (e.g., Gemini, GPT-4o-mini), often optimizing for cost and performance.\n\n\u003cbr/\u003e\n\n---\n\n## 🚀 Quickstart\n\n### Install Dependencies\n\n\u003e **Requires Python 3.13+**\n\nFirst, install [uv](https://github.com/astral-sh/uv) (the recommended fast Python package installer):\n\n```bash\n# macOS / Linux\ncurl -LsSf https://astral.sh/uv/install.sh | sh\n# Windows\npowershell -c \"irm https://astral.sh/uv/install.ps1 | iex\"\n```\n\nThen clone the repository, set up a virtual environment using Python 3.13+, and install packages:\n\n```bash\ngit clone https://github.com/Dicklesworthstone/ultimate_mcp_client\ncd ultimate_mcp_client\n\n# Create venv using uv (recommended)\nuv venv --python 3.13\n# Or using standard venv\n# python3.13 -m venv .venv\n\n# Activate environment\nsource .venv/bin/activate # Linux/macOS\n# .venv\\Scripts\\activate # Windows Powershell\n# .\\venv\\Scripts\\activate.bat # Windows CMD\n\n# Install dependencies using uv (fastest)\nuv sync --all-extras\n# Or using pip (slower)\n# pip install -e . # Installs only core dependencies\n```\n\n### Configure API Key\n\nSet your Anthropic API key as an environment variable:\n\n```bash\nexport ANTHROPIC_API_KEY=\"sk-ant-...\"\n# Or add ANTHROPIC_API_KEY=\"sk-ant-...\" to a .env file in the project root\n```\n\nAlternatively, set it later using the `/config api-key ...` command in the interactive CLI or via the Web UI settings panel.\n\n### Launch the Web UI (Recommended)\n\n```bash\nmcpclient run --webui\n```\n\nThen open your browser to `http://127.0.0.1:8017` (or the configured host/port).\n\nYou can customize the host and port:\n\n```bash\nmcpclient run --webui --host 0.0.0.0 --port 8080\n```\n\n### Run Interactive CLI Mode\n\n```bash\nmcpclient run --interactive\n```\n\n### Run a One-Off Query\n\n```bash\nmcpclient run --query \"What's the weather in New York?\"\n```\n\n### Show the CLI Dashboard\n\n```bash\nmcpclient run --dashboard\n```\n\n### Configure Port Scanning\n\n```bash\n# Enable port scanning (if disabled)\nmcpclient config port-scan enable true\n\n# Set the range (example)\nmcpclient config port-scan range 8000 8999\n```\n\n### Import and Export Conversations\n\n```bash\n# Export current conversation branch to a default filename\nmcpclient export\n\n# Export current branch to a specific file\nmcpclient export --output my_conversation.json\n\n# Export specific conversation branch by ID (first 8 chars often suffice)\nmcpclient export --id 12345678 --output specific_branch.json\n\n# Import a conversation file (creates a new branch under the current node)\nmcpclient import-conv my_conversation.json\n```\n\n---\n\n## 🌐 Web UI Features\n\nThe web UI (`mcpclient run --webui`) provides a modern, user-friendly interface built with Alpine.js, Tailwind CSS, and DaisyUI:\n\n-   **Real-time Chat:** Streamed responses from Claude via WebSockets, rich Markdown rendering (via `Marked.js`), code block syntax highlighting (via `highlight.js`) with copy buttons, and clear display of system messages and status updates.\n-   **Tool Interaction:** Visual separation and display of tool calls (arguments) and their results (success or error) directly within the chat flow. A modal allows direct execution of any available tool with custom JSON parameters for testing and debugging.\n-   **Server Management:** A dedicated sidebar tab lists configured servers. Users can:\n    -   Add new servers (STDIO/SSE) via a modal form.\n    -   Connect/disconnect from servers with status indicators (loading, connected, disconnected, error).\n    -   Enable/disable servers (automatically disconnects if disabled).\n    -   Remove server configurations.\n    -   View basic health/status and the number of tools provided by each server.\n-   **Discovery:** Buttons in the Servers tab trigger discovery scans (local filesystem, remote registry, mDNS). Discovered servers are listed, allowing users to add them to the configuration with one click.\n-   **Conversation Branching:** An interactive tree view in the Conversation tab visualizes the `ConversationGraph`. Users can click to checkout different branches (updating the chat view) or fork the current point to create new branches.\n-   **Context Management:** Buttons in the Conversation tab allow users to clear the current branch's messages (resetting to parent/root state) or trigger context optimization/summarization via the API.\n-   **Import/Export:** Buttons in the Conversation tab allow exporting the current branch to a JSON file or importing a previously exported JSON file via file selection (uploading to the backend).\n-   **Settings:** A dedicated sidebar tab allows users to view and modify key configuration options (API Key, Default Model, Max Tokens, Temperature, feature toggles like Streaming, Caching, Auto-Discovery, mDNS) which are persisted to the server's config file.\n-   **Theme Switching:** A dropdown menu allows selecting from a wide range of DaisyUI themes. The UI adapts instantly, and code highlighting automatically switches between light/dark styles based on the selected theme.\n-   **Status Indicators:** Real-time WebSocket connection status icon, overall server connection count, and total available tool count are displayed in the header. Transient status messages (e.g., \"Executing tool...\") appear below the chat input.\n\n---\n\n## 🔌 API Server\n\nWhen running with `--webui`, a FastAPI server provides programmatic access:\n\n```\nGET    /api/status                     - Client overview (model, servers, tools, history count, current node)\nGET    /api/config                     - Get current (non-sensitive) configuration\nPUT    /api/config                     - Update configuration settings (e.g., { \"temperature\": 0.8 })\nGET    /api/servers                    - List all configured servers with status, health, tools\nPOST   /api/servers                    - Add a new server configuration (Requires ServerAddRequest model)\nDELETE /api/servers/{server_name}    - Remove a server configuration\nPOST   /api/servers/{server_name}/connect    - Connect to a specific server\nPOST   /api/servers/{server_name}/disconnect - Disconnect from a specific server\nPUT    /api/servers/{server_name}/enable?enabled={true|false} - Enable/disable a server\nGET    /api/tools                      - List all available tools from connected servers\nGET    /api/resources                  - List all available resources\nGET    /api/prompts                    - List all available prompts\nGET    /api/conversation               - Get current conversation state (messages, current node ID/name, full node graph)\nPOST   /api/conversation/fork          - Create a fork (optionally named) from the current conversation node\nPOST   /api/conversation/checkout      - Switch the current context to a different conversation node/branch (by ID)\nPOST   /api/conversation/clear         - Clear messages on the current node and switch to root\nPOST   /api/conversation/optimize      - Trigger context summarization for the current node (optional model/token args)\nPOST   /api/tool/execute               - Execute a specific tool with given parameters (Requires ToolExecuteRequest model)\nWS     /ws/chat                        - WebSocket endpoint for streaming chat (`query`, `command`), receiving updates (`text_chunk`, `status`, `query_complete`, `error`, `state_update`).\n```\n\n*(Note: The actual request/response models like `ServerAddRequest`, `ToolExecuteRequest` are defined in the Python code and used by FastAPI for validation.)*\n\n---\n\n## ⚙️ Commands\n\n### CLI Options\n\nRun `mcpclient --help` or `mcpclient [COMMAND] --help` for details.\n\n### Interactive Shell Commands (`mcpclient run --interactive`)\n\nType `/` followed by a command:\n\n```text\n/help         Show this help message\n/exit, /quit  Exit the client\n/config       Manage configuration (api-key, model, max-tokens, history-size, auto-discover, discovery-path, port-scan)\n/servers      Manage MCP servers (list, add, remove, connect, disconnect, enable, disable, status)\n/discover     Discover/manage LAN servers (list, connect \u003cNAME\u003e, refresh, auto \u003con|off\u003e)\n/tools        List available tools (optionally filter by server: /tools \u003cserver_name\u003e)\n/tool         Directly execute a tool: /tool \u003ctool_name\u003e '{\"param\": \"value\"}'\n/resources    List available resources (optionally filter by server: /resources \u003cserver_name\u003e)\n/prompts      List available prompt templates (optionally filter by server: /prompts \u003cserver_name\u003e)\n/prompt       Apply a prompt template to the current conversation context: /prompt \u003cprompt_name\u003e\n/model        View or change the current AI model: /model [\u003cmodel_name\u003e]\n/fork         Create a new branch from the current conversation point: /fork [Optional Branch Name]\n/branch       Manage branches (list, checkout \u003cnode_id_prefix\u003e)\n/export       Export current branch: /export [--id \u003cnode_id\u003e] [--output \u003cfile.json\u003e]\n/import       Import conversation file: /import \u003cfile.json\u003e\n/history      View recent conversation history (optionally specify number: /history 10)\n/cache        Manage tool cache (list, clear [--all|tool_name], clean, dependencies [tool_name])\n/dashboard    Show the live Textual User Interface (TUI) dashboard (requires separate run)\n/optimize     Summarize current conversation context: /optimize [--model \u003cmodel\u003e] [--tokens \u003cnum\u003e]\n/reload       Disconnect, reload capabilities, and reconnect to enabled servers\n/clear        Clear messages in the current branch and optionally reset to root\n```\n\n---\n\n## 🏗️ Architecture \u0026 Engineering Highlights\n\nThis client employs several techniques to provide a robust and feature-rich experience:\n\n-   **Asynchronous Core:** Built entirely on Python's `asyncio` for efficient handling of network I/O (HTTP, WebSockets, SSE), subprocess communication (`stdio`), filesystem operations (`aiofiles`), and concurrent background tasks (monitoring, discovery, port scanning).\n-   **Component-Based Design:** While packaged primarily as a single script for ease of use, it internally separates concerns into distinct classes:\n    -   `MCPClient`: The main application class, orchestrating UI loops, command handling, and core logic.\n    -   `ServerManager`: Handles server configuration, lifecycle (connecting, disconnecting, restarting), discovery mechanisms, capability aggregation (tools, resources, prompts), and manages server processes/sessions. Uses `AsyncExitStack` for reliable resource cleanup.\n    -   **`RobustStdioSession` (Key Engineering Effort):** A custom implementation of the `mcp.ClientSession` tailored specifically for `stdio` servers. It includes logic to:\n        -   Filter non-JSON-RPC output from the server's `stdout` to prevent protocol errors.\n        -   Handle responses by directly resolving `asyncio.Future` objects associated with request IDs, offering a potentially more performant alternative to queue-based approaches.\n        -   Manage background tasks for reading `stdout` and writing captured `stderr` to log files asynchronously.\n        -   Gracefully handle process termination and cleanup.\n    -   **STDIO Safety Mechanisms (Crucial):** A multi-layered defense against accidental `stdout` pollution, which is fatal for `stdio`-based protocols:\n        -   `StdioProtectionWrapper`: Globally wraps `sys.stdout` to intercept writes, redirecting them to `stderr` if any `stdio` server is active.\n        -   `safe_stdout()`: A context manager used during critical operations (like server connection) to temporarily redirect `stdout` to `stderr`.\n        -   `get_safe_console()` / `safe_print()`: Utility functions ensuring that UI output (via `Rich`) uses the correct stream (`stdout` or `stderr`) based on active `stdio` servers.\n        -   These measures allow the client UI and logging to function correctly even when communicating with sensitive `stdio` servers.\n    -   `ConversationGraph`: Manages the non-linear, branching conversation structure using `ConversationNode` objects. Handles persistence to/from JSON.\n    -   `ToolCache`: Implements caching logic using `diskcache` for persistence and an in-memory layer for speed. Includes TTL management and dependency invalidation.\n    -   `ServerRegistry` / `ServerMonitor`: Handle mDNS/Zeroconf discovery/registration and background server health checks with recovery attempts.\n-   **Dual Interface Implementation:**\n    -   **Web Backend:** Uses `FastAPI` for a clean REST API structure, `uvicorn` for the ASGI server, and `websockets` for bidirectional real-time chat. A FastAPI `lifespan` context manager ensures the `MCPClient` is properly initialized on startup and cleaned up on shutdown. Dependency injection provides endpoint access to the client instance.\n    -   **Web Frontend:** Leverages `Alpine.js` for lightweight reactivity and component logic directly in the HTML. `Tailwind CSS` and `DaisyUI` provide styling and pre-built components. `Marked.js`, `highlight.js`, and `DOMPurify` handle secure and attractive rendering of Markdown and code. `Tippy.js` provides tooltips.\n    -   **CLI/TUI:** Uses `Typer` for defining the command-line interface and parsing arguments. `Rich` is heavily used for formatted console output, tables, progress bars, Markdown rendering, syntax highlighting, and the live TUI dashboard. Careful management (`_run_with_progress`, `_run_with_simple_progress` helpers) prevents issues with nested `Rich Live` displays during complex operations.\n-   **Resilience \u0026 Error Handling:** Employs decorators (`@retry_with_circuit_breaker`, `@with_tool_error_handling`) for common patterns like retries and standardized error reporting during tool execution. Structured `try...except...finally` blocks are used throughout for robustness.\n-   **Observability:** Integrates `OpenTelemetry` for structured metrics (request counters, latency histograms, tool executions) and distributed tracing (spans track operations like query processing, server connections, tool calls). This aids in performance analysis and debugging.\n-   **Configuration:** Flexible configuration system using a `config.yaml` file, environment variables (especially for sensitive keys like `ANTHROPIC_API_KEY`), and interactive commands or Web UI settings that persist changes back to the YAML file.\n\n---\n\n## 🔄 Smart Cache Dependency Tracking\n\nThe Smart Cache Dependency system allows tools to declare dependencies on other tools:\n\n- When a tool's cache is invalidated, all dependent tools are automatically invalidated\n- Dependencies are registered when servers declare tool relationships\n- View the dependency graph with `/cache dependencies`\n- Improves data consistency by ensuring related tools use fresh data\n\nExample dependency flow:\n```\nweather:current → weather:forecast → travel:recommendations\n```\nIf the current weather data is updated, both the forecast and travel recommendations caches are automatically invalidated.\n\n---\n\n## 🔍 Tool \u0026 Server Discovery\n\nThis client offers multiple ways to find and integrate MCP servers:\n\n-   **Configured Paths:** Searches directories specified in `config.yaml` (under `discovery_paths`) for local `stdio` server scripts (e.g., `.py`, `.js`). Defaults include:\n    -   `.mcpclient_config/servers` (in project root)\n    -   `~/mcp-servers`\n    -   `~/modelcontextprotocol/servers`\n-   **Claude Desktop Config (`claude_desktop_config.json`):** If this file exists in the project root, the client automatically imports server definitions from it during setup.\n    -   **Intelligent Command Adaptation:**\n        -   Detects `wsl.exe ... \u003cshell\u003e -c \"command ...\"` patterns.\n        -   Extracts the Linux `\u003cshell\u003e` (e.g., `bash`, `sh`) and the `\"command ...\"`.\n        -   Remaps the configuration to execute the command directly using the identified Linux shell (e.g., `/bin/bash -c \"command ...\"`), bypassing `wsl.exe`.\n        -   For other command types (e.g., `npx ...`), it uses `adapt_path_for_platform` to scan arguments for Windows-style paths (`C:\\Users\\...`) and converts them to their `/mnt/c/Users/...` equivalents, ensuring compatibility when running the client in WSL/Linux.\n-   **Remote Registries:** Connects to MCP registry server URLs defined in `config.yaml` (`registry_urls`) to discover publicly available or shared servers (typically SSE).\n-   **Local Network (mDNS/Zeroconf):**\n    -   Uses the `zeroconf` library to listen for services advertised under `_mcp._tcp.local.` on the local network.\n    -   Provides real-time notifications in the interactive CLI when new servers appear or disappear.\n    -   The `/discover` command suite allows managing these discovered servers:\n        -   `/discover list`: View details of currently visible LAN servers.\n        -   `/discover connect \u003cNAME\u003e`: Add a discovered server to the configuration file and attempt to connect.\n        -   `/discover refresh`: Manually trigger a re-scan of the network.\n        -   `/discover auto [on|off]`: Toggle continuous background mDNS scanning (requires `enable_local_discovery: true` in config).\n  -   **Local Port Scanning:**\n      -   If enabled (`enable_port_scanning: true` in `config.yaml` or via `/config port-scan enable true`), actively scans a range of ports on specified local IP addresses during startup discovery.\n      -   Attempts a basic MCP `initialize` handshake on each port to detect responsive MCP servers (primarily SSE).\n      -   Useful for finding servers that don't use mDNS advertisement.\n      -   The range, target IPs, concurrency, and timeout are configurable via `config.yaml` or the `/config port-scan ...` commands.\n      -   Found servers are presented alongside other discovered servers for optional addition to the configuration.\n---\n\n## 📡 Telemetry + Debugging\n\n-   **OpenTelemetry:** Generates traces and metrics for key operations. By default, data is collected but not exported. Set `use_console_exporter = True` near the top of `mcpclient.py` to enable noisy console output for debugging traces and metrics. For production, configure appropriate OTel exporters (e.g., Jaeger, Prometheus).\n-   **Dashboards:**\n    -   **CLI:** Run `mcpclient run --dashboard` for a live TUI monitoring view powered by `Rich`. Shows server status, health, connection state, basic tool usage stats, and client info. Refreshes periodically.\n    -   **Web UI:** The \"Servers\" tab provides visual server status (connection, health via icons), and the header shows overall counts.\n-   **Logging:** Uses Python's standard `logging` configured with `RichHandler` for pretty console output (to `stderr` to avoid `stdio` conflicts).\n    -   Use the `--verbose` or `-v` flag to increase log level to DEBUG for detailed internal information.\n    -   Verbose mode also enables detailed `stdio` session logging (`USE_VERBOSE_SESSION_LOGGING = True`) to see raw JSON-RPC messages (useful for debugging MCP servers).\n-   **Error Tracebacks:** Set the environment variable `MCP_CLIENT_DEBUG=1` before running to make the CLI print full Python tracebacks for unexpected errors, aiding in debugging client-side issues.\n-   **STDIO Server Logs:** The `stderr` output from `stdio` servers is captured asynchronously and written to log files in the configuration directory (e.g., `.mcpclient_config/\u003cserver_name\u003e_stderr.log`), crucial for diagnosing server-side problems.\n\n---\n\n## 📦 Configuration\n\n-   **Primary File:** Configuration is loaded from and saved to `.mcpclient_config/config.yaml` located in the project's root directory.\n-   **Environment Variables:** `ANTHROPIC_API_KEY` is the primary way to provide the API key and overrides any key stored in the config file. `EDITOR` is used by `/config edit`. `MCP_CLIENT_DEBUG=1` enables tracebacks.\n-   **Interactive CLI:** The `/config` command allows viewing and modifying settings like `api-key`, `model`, `max-tokens`, `discovery-path`, port scanning parameters, etc. Changes are saved back to `config.yaml`.\n-   **Web UI Settings:** The \"Settings\" tab in the Web UI provides controls for common configuration options. Changes made here are sent via the API and saved to `config.yaml`.\n\n**View Current Config:**\n\n```bash\nmcpclient config --show\n# OR in interactive mode:\n/config\n```\n\n**Edit Config File Manually:**\n\n```bash\nmcpclient config --edit\n# (This will open .mcpclient_config/config.yaml in the editor specified by your $EDITOR environment variable)\n```\n\n---\n\n## 🧪 Development Notes\n\n-   **Core:** Python 3.13+, `asyncio`\n-   **CLI:** `Typer`, `Rich`\n-   **Web:** `FastAPI`, `Uvicorn`, `WebSockets`, `Alpine.js`, `Tailwind CSS`, `DaisyUI`\n-   **MCP:** `mcp` SDK (`mcp\u003e=1.0.0`)\n-   **AI:** `anthropic` SDK (`anthropic\u003e=0.15.0`)\n-   **Observability:** `opentelemetry-sdk`, `opentelemetry-api`, `opentelemetry-instrumentation`\n-   **Utilities:** `httpx`, `PyYAML`, `python-dotenv`, `psutil`, `aiofiles`, `diskcache`, `tiktoken`, `zeroconf`, `colorama`\n-   **Linting/Formatting:** `ruff` is configured in `pyproject.toml`. Use `uv run lint` or `ruff check . \u0026\u0026 ruff format .`.\n-   **Type Checking:** `mypy` is configured in `pyproject.toml`. Use `uv run typecheck` or `mypy mcpclient.py`.\n\nThe project is primarily structured within `mcpclient.py` for easier distribution and introspection, although internal class-based modularity is maintained. The Web UI is served from the self-contained `mcp_client_ui.html` file, utilizing CDN-hosted libraries for simplicity. Key complex logic, such as the robust `stdio` handling and asynchronous management, resides within dedicated classes like `RobustStdioSession` and `ServerManager`.\n\n---\n\n## 📝 License\n\nMIT License. Refer to standard MIT terms.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDicklesworthstone%2Fultimate_mcp_client","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FDicklesworthstone%2Fultimate_mcp_client","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDicklesworthstone%2Fultimate_mcp_client/lists"}