Skip to content
Back to search

ultimate_mcp_client

Async Python client for the Model Context Protocol with interactive CLI and reactive Web UI, connecting AI models to MCP servers via stdio and SSE

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/dicklesworthstone--ultimate-mcp-client/badge.svg)](/listings/dicklesworthstone--ultimate-mcp-client)

HTML

<a href="/listings/dicklesworthstone--ultimate-mcp-client"><img src="/api/listings/dicklesworthstone--ultimate-mcp-client/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

Install Dependencies

> **Requires Python 3.13+**

First, install [uv](https://github.com/astral-sh/uv) (the recommended fast Python package installer):

# macOS / Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
# Windows
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"

Then clone the repository, set up a virtual environment using Python 3.13+, and install packages:

git clone https://github.com/Dicklesworthstone/ultimate_mcp_client
cd ultimate_mcp_client

# Create venv using uv (recommended)
uv venv --python 3.13
# Or using standard venv
# python3.13 -m venv .venv

# Activate environment
source .venv/bin/activate # Linux/macOS
# .venv\Scripts\activate # Windows Powershell
# .\venv\Scripts\activate.bat # Windows CMD

# Install dependencies using uv (fastest)
uv sync --all-extras
# Or using pip (slower)
# pip install -e . # Installs only core dependencies

Configure API Key

Set your Anthropic API key as an environment variable:

export ANTHROPIC_API_KEY="sk-ant-..."
# Or add ANTHROPIC_API_KEY="sk-ant-..." to a .env file in the project root

Alternatively, set it later using the `/config api-key ...` command in the interactive CLI or via the Web UI settings panel.

Launch the Web UI (Recommended)

mcpclient run --webui

Then open your browser to `http://127.0.0.1:8017` (or the configured host/port).

You can customize the host and port:

mcpclient run --webui --host 0.0.0.0 --port 8080

Run Interactive CLI Mode

mcpclient run --interactive

Run a One-Off Query

mcpclient run --query "What's the weather in New York?"

Show the CLI Dashboard

mcpclient run --dashboard

Configure Port Scanning

# Enable port scanning (if disabled)
mcpclient config port-scan enable true

# Set the range (example)
mcpclient config port-scan range 8000 8999

Import and Export Conversations

# Export current conversation branch to a default filename
mcpclient export

# Export current branch to a specific file
mcpclient export --output my_conversation.json

# Export specific conversation branch by ID (first 8 chars often suffice)
mcpclient export --id 12345678 --output specific_branch.json

# Import a conversation file (creates a new branch under the current node)
mcpclient import-conv my_conversation.json

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 468 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # 🧠 Ultimate MCP Client
  2. <div align="center">
  3. [![Python 3.13+](https://img.shields.io/badge/python-3.13+-blue.svg)](https://www.python.org/downloads/release/python-3130/)
  4. [![License: MIT](https://img.shields.io/badge/License-MIT%2BOpenAI%2FAnthropic%20Rider-blue.svg)](./LICENSE)
  5. [![MCP Protocol](https://img.shields.io/badge/Protocol-MCP-purple.svg)](https://github.com/mpctechdebt/mcp)
  6. [![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)
  7. A 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.
  8. ![Web UI Screenshot](https://github.com/Dicklesworthstone/ultimate_mcp_client/blob/main/banner.webp)
  9. </div>
  10. > Built by Jeffrey Emanuel
  11. ---
  12. ## 🎯 Purpose & Motivation
  13. The 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:
  14. 1. **Robust Connectivity:** Reliably connect to diverse MCP servers (`stdio`, `sse`) with built-in resilience, advanced error handling, and intelligent discovery.
  15. 2. **Rich User Experience:** Offer both a powerful interactive CLI and a modern, reactive Web UI, ensuring usability for diverse workflows.
  16. 3. **Advanced State Management:** Go beyond simple chat history with forkable conversation graphs, persistent state across sessions, and smart context optimization techniques.
  17. 4. **Developer Introspection:** Provide deep observability via OpenTelemetry metrics and traces, alongside live dashboards for monitoring client and server health and performance.
  18. 5. **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.
  19. **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.
  20. ---
  21. ## 🔌 Key Features
  22. - **Dual Interfaces: Web UI & CLI**
  23. - **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.
  24. - **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.
  25. - **Robust Server Connectivity & Management**
  26. - Supports `stdio`, `sse` (HTTP Server-Sent Events), and `streaming-http` MCP servers.
  27. - **Advanced STDIO Handling (Key Engineering Effort):** Features a custom `RobustStdioSession` designed to gracefully handle potentially noisy or non-compliant `stdio` servers. It includes:
  28. - *Noise Filtering:* Ignores non-JSON-RPC output that could corrupt the protocol.
  29. - *Direct Future Resolution:* Avoids complex queueing for faster response handling.
  30. - *Process Lifecycle Management:* Reliably starts, monitors, terminates, and kills `stdio` server processes.
  31. - **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.
  32. - **Resilience:** Automatic connection retries with exponential backoff and circuit breakers for failing servers (`@retry_with_circuit_breaker`). Background health monitoring (`ServerMonitor`) checks server responsiveness.
  33. - **Modern Transport Support**
  34. - **Streaming-HTTP:** Native support for the modern `streaming-http` transport protocol via the FastMCP library. This transport provides efficient bidirectional communication over HTTP with built-in streaming capabilities, making it ideal for modern MCP server deployments.
  35. - **Intelligent Transport Detection:** Automatically detects and suggests the appropriate transport type based on server URLs and discovery information:
  36. - Local file paths → `stdio`
  37. - URLs with `/sse` or `/events` paths → `sse`
  38. - General HTTP/HTTPS URLs → `streaming-http` (default for modern servers)
  39. - **Intelligent Server Discovery**
  40. - Auto-discovers local `stdio` servers (Python/JS scripts) in configured filesystem paths.
  41. - **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.
  42. - **Local Port Scanning:** Actively scans a configurable range of local ports (e.g., 8000-9000) for MCP servers by attempting an `initialize` handshake. Supports detection of all transport types (`stdio`, `sse`, `streaming-http`). Configurable via `/config port-scan ...` commands.
  43. - **Registry Integration:** Connects to remote MCP registries (specified in config) to find and add shared servers.
  44. - **Claude Desktop Import:** Automatically detects `claude_desktop_config.json` in the project root. **Intelligently adapts configurations:**
  45. - Remaps `wsl.exe ... bash -c "cmd"` calls to direct Linux shell execution (`/bin/bash -c "cmd"`).
  46. - Converts Windows-style paths (`C:\...`) in arguments to their Linux/WSL equivalents (`/mnt/c/...`) using `adapt_path_for_platform` for seamless integration.
  47. - **Powerful AI Integration & Streaming**
  48. - Deep integration with Claude models via the official `anthropic` SDK, supporting multi-turn tool use scenarios.
  49. - **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.
  50. - **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.
  51. - **Direct Tool Execution:** Run specific tools with custom JSON parameters via the `/tool` command (CLI) or a dedicated modal (Web UI).
  52. - **Advanced Conversation Management**
  53. - **Branching:** Forkable conversation graphs (`ConversationGraph`) allow exploring different interaction paths without losing history. Visually represented and navigable in the Web UI.
  54. - **Persistence:** Conversation graphs (including all branches and messages) are automatically saved to JSON files in the config directory, preserving state across sessions.
  55. - **Context Optimization:** Automatic or manual summarization (`/optimize`) of long conversation histories using a specified AI model (configurable) to stay within context limits.
  56. - **Dynamic Prompts:** Inject pre-defined prompt templates obtained from servers into the current conversation context using the `/prompt` command.
  57. - **Import/Export:** Easily save (`/export`) and load (`/import`) entire conversation branches in a portable JSON format for sharing or backup.
  58. - **Observability & Monitoring**
  59. - **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.
  60. - **Live Dashboards:**
  61. - **CLI:** Real-time TUI dashboard (`/dashboard`) built with `Rich`, showing server health, tool usage stats, and client info.
  62. - **Web UI:** Dynamically updates server status, health indicators, and capability counts.
  63. - **Smart Caching**
  64. - Optional disk (`diskcache`) and in-memory caching for tool results to improve speed and reduce costs.
  65. - Configurable Time-To-Live (TTL) per tool category (e.g., `weather`, `filesystem`).
  66. - **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`.
  67. ---
  68. ## 📸 Screenshots
  69. A glimpse into the Ultimate MCP Client's interfaces:
  70. <br/>
  71. <table>
  72. <tbody>
  73. <tr>
  74. <td align="center" valign="top" width="50%">
  75. <img 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%">
  76. <br/>
  77. <p align="center"><small><em>Interactive CLI: Streaming response with tool call/result.</em></small></p>
  78. </td>
  79. <td align="center" valign="top" width="50%">
  80. <img 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%">
  81. <br/>
  82. <p align="center"><small><em>Live TUI Dashboard: Real-time server & tool monitoring (<code>/dashboard</code>).</em></small></p>
  83. </td>
  84. </tr>
  85. <tr>
  86. <td align="center" valign="top" width="33%">
  87. <img src="https://github.com/Dicklesworthstone/ultimate_mcp_client/blob/main/screenshots/webui_example_01.webp?raw=true" alt="Web UI Chat Interface" width="95%">
  88. <br/>
  89. <p align="center"><small><em>Web UI: Main chat interface showing messages and tool interactions.</em></small></p>
  90. </td>
  91. <td align="center" valign="top" width="33%">
  92. <img 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%">
  93. <br/>
  94. <p align="center"><small><em>Web UI: Server management tab with connection status and controls.</em></small></p>
  95. </td>
  96. <td align="center" valign="top" width="33%">
  97. <img 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%">
  98. <br/>
  99. <p align="center"><small><em>Web UI: Conversation tab showing the branching graph structure.</em></small></p>
  100. </td>
  101. </tr>
  102. </tbody>
  103. </table>
  104. > **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.
  105. <br/>
  106. ---
  107. ## 🚀 Quickstart
  108. ### Install Dependencies
  109. > **Requires Python 3.13+**
  110. First, install [uv](https://github.com/astral-sh/uv) (the recommended fast Python package installer):
  111. ```bash
  112. # macOS / Linux
  113. curl -LsSf https://astral.sh/uv/install.sh | sh
  114. # Windows
  115. powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
  116. ```
  117. Then clone the repository, set up a virtual environment using Python 3.13+, and install packages:
  118. ```bash
  119. git clone https://github.com/Dicklesworthstone/ultimate_mcp_client
  120. cd ultimate_mcp_client
  121. # Create venv using uv (recommended)
  122. uv venv --python 3.13
  123. # Or using standard venv
  124. # python3.13 -m venv .venv
  125. # Activate environment
  126. source .venv/bin/activate # Linux/macOS
  127. # .venv\Scripts\activate # Windows Powershell
  128. # .\venv\Scripts\activate.bat # Windows CMD
  129. # Install dependencies using uv (fastest)
  130. uv sync --all-extras
  131. # Or using pip (slower)
  132. # pip install -e . # Installs only core dependencies
  133. ```
  134. ### Configure API Key
  135. Set your Anthropic API key as an environment variable:
  136. ```bash
  137. export ANTHROPIC_API_KEY="sk-ant-..."
  138. # Or add ANTHROPIC_API_KEY="sk-ant-..." to a .env file in the project root
  139. ```
  140. Alternatively, set it later using the `/config api-key ...` command in the interactive CLI or via the Web UI settings panel.
  141. ### Launch the Web UI (Recommended)
  142. ```bash
  143. mcpclient run --webui
  144. ```
  145. Then open your browser to `http://127.0.0.1:8017` (or the configured host/port).
  146. You can customize the host and port:
  147. ```bash
  148. mcpclient run --webui --host 0.0.0.0 --port 8080
  149. ```
  150. ### Run Interactive CLI Mode
  151. ```bash
  152. mcpclient run --interactive
  153. ```
  154. ### Run a One-Off Query
  155. ```bash
  156. mcpclient run --query "What's the weather in New York?"
  157. ```
  158. ### Show the CLI Dashboard
  159. ```bash
  160. mcpclient run --dashboard
  161. ```
  162. ### Configure Port Scanning
  163. ```bash
  164. # Enable port scanning (if disabled)
  165. mcpclient config port-scan enable true
  166. # Set the range (example)
  167. mcpclient config port-scan range 8000 8999
  168. ```
  169. ### Import and Export Conversations
  170. ```bash
  171. # Export current conversation branch to a default filename
  172. mcpclient export
  173. # Export current branch to a specific file
  174. mcpclient export --output my_conversation.json
  175. # Export specific conversation branch by ID (first 8 chars often suffice)
  176. mcpclient export --id 12345678 --output specific_branch.json
  177. # Import a conversation file (creates a new branch under the current node)
  178. mcpclient import-conv my_conversation.json
  179. ```
  180. ---
  181. ## 🌐 Web UI Features
  182. The web UI (`mcpclient run --webui`) provides a modern, user-friendly interface built with Alpine.js, Tailwind CSS, and DaisyUI:
  183. - **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.
  184. - **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.
  185. - **Server Management:** A dedicated sidebar tab lists configured servers. Users can:
  186. - Add new servers (STDIO/SSE/Streaming-HTTP) via a modal form.
  187. - Connect/disconnect from servers with status indicators (loading, connected, disconnected, error).
  188. - Enable/disable servers (automatically disconnects if disabled).
  189. - Remove server configurations.
  190. - View basic health/status and the number of tools provided by each server.
  191. - **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.
  192. - **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.
  193. - **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.
  194. - **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).
  195. - **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.
  196. - **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.
  197. - **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.
  198. ---
  199. ## 🔌 API Server
  200. When running with `--webui`, a FastAPI server provides programmatic access:
  201. ```
  202. GET /api/status - Client overview (model, servers, tools, history count, current node)
  203. GET /api/config - Get current (non-sensitive) configuration
  204. PUT /api/config - Update configuration settings (e.g., { "temperature": 0.8 })
  205. GET /api/servers - List all configured servers with status, health, tools
  206. POST /api/servers - Add a new server configuration (Supports stdio/sse/streaming-http transports)
  207. DELETE /api/servers/{server_name} - Remove a server configuration
  208. POST /api/servers/{server_name}/connect - Connect to a specific server
  209. POST /api/servers/{server_name}/disconnect - Disconnect from a specific server
  210. PUT /api/servers/{server_name}/enable?enabled={true|false} - Enable/disable a server
  211. GET /api/tools - List all available tools from connected servers
  212. GET /api/resources - List all available resources
  213. GET /api/prompts - List all available prompts
  214. GET /api/conversation - Get current conversation state (messages, current node ID/name, full node graph)
  215. POST /api/conversation/fork - Create a fork (optionally named) from the current conversation node
  216. POST /api/conversation/checkout - Switch the current context to a different conversation node/branch (by ID)
  217. POST /api/conversation/clear - Clear messages on the current node and switch to root
  218. POST /api/conversation/optimize - Trigger context summarization for the current node (optional model/token args)
  219. POST /api/tool/execute - Execute a specific tool with given parameters (Requires ToolExecuteRequest model)
  220. WS /ws/chat - WebSocket endpoint for streaming chat (`query`, `command`), receiving updates (`text_chunk`, `status`, `query_complete`, `error`, `state_update`).
  221. ```
  222. *(Note: The actual request/response models like `ServerAddRequest`, `ToolExecuteRequest` are defined in the Python code and used by FastAPI for validation.)*
  223. ---
  224. ## ⚙️ Commands
  225. ### CLI Options
  226. Run `mcpclient --help` or `mcpclient [COMMAND] --help` for details.
  227. ### Interactive Shell Commands (`mcpclient run --interactive`)
  228. Type `/` followed by a command:
  229. ```text
  230. /help Show this help message
  231. /exit, /quit Exit the client
  232. /config Manage configuration (api-key, model, max-tokens, history-size, auto-discover, discovery-path, port-scan)
  233. /servers Manage MCP servers (list, add, remove, connect, disconnect, enable, disable, status)
  234. /discover Discover/manage LAN servers (list, connect <NAME>, refresh, auto <on|off>)
  235. /tools List available tools (optionally filter by server: /tools <server_name>)
  236. /tool Directly execute a tool: /tool <tool_name> '{"param": "value"}'
  237. /resources List available resources (optionally filter by server: /resources <server_name>)
  238. /prompts List available prompt templates (optionally filter by server: /prompts <server_name>)
  239. /prompt Apply a prompt template to the current conversation context: /prompt <prompt_name>
  240. /model View or change the current AI model: /model [<model_name>]
  241. /fork Create a new branch from the current conversation point: /fork [Optional Branch Name]
  242. /branch Manage branches (list, checkout <node_id_prefix>)
  243. /export Export current branch: /export [--id <node_id>] [--output <file.json>]
  244. /import Import conversation file: /import <file.json>
  245. /history View recent conversation history (optionally specify number: /history 10)
  246. /cache Manage tool cache (list, clear [--all|tool_name], clean, dependencies [tool_name])
  247. /dashboard Show the live Textual User Interface (TUI) dashboard (requires separate run)
  248. /optimize Summarize current conversation context: /optimize [--model <model>] [--tokens <num>]
  249. /reload Disconnect, reload capabilities, and reconnect to enabled servers
  250. /clear Clear messages in the current branch and optionally reset to root
  251. ```
  252. ---
  253. ## 🏗️ Architecture & Engineering Highlights
  254. This client employs several techniques to provide a robust and feature-rich experience:
  255. - **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).
  256. - **Component-Based Design:** While packaged primarily as a single script for ease of use, it internally separates concerns into distinct classes:
  257. - `MCPClient`: The main application class, orchestrating UI loops, command handling, and core logic.
  258. - `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. Supports all transport types including the modern `streaming-http` protocol via FastMCP integration.
  259. - **`RobustStdioSession` (Key Engineering Effort):** A custom implementation of the `mcp.ClientSession` tailored specifically for `stdio` servers. It includes logic to:
  260. - Filter non-JSON-RPC output from the server's `stdout` to prevent protocol errors.
  261. - Handle responses by directly resolving `asyncio.Future` objects associated with request IDs, offering a potentially more performant alternative to queue-based approaches.
  262. - Manage background tasks for reading `stdout` and writing captured `stderr` to log files asynchronously.
  263. - Gracefully handle process termination and cleanup.
  264. - **STDIO Safety Mechanisms (Crucial):** A multi-layered defense against accidental `stdout` pollution, which is fatal for `stdio`-based protocols:
  265. - `StdioProtectionWrapper`: Globally wraps `sys.stdout` to intercept writes, redirecting them to `stderr` if any `stdio` server is active.
  266. - `safe_stdout()`: A context manager used during critical operations (like server connection) to temporarily redirect `stdout` to `stderr`.
  267. - `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.
  268. - These measures allow the client UI and logging to function correctly even when communicating with sensitive `stdio` servers.
  269. - `ConversationGraph`: Manages the non-linear, branching conversation structure using `ConversationNode` objects. Handles persistence to/from JSON.
  270. - `ToolCache`: Implements caching logic using `diskcache` for persistence and an in-memory layer for speed. Includes TTL management and dependency invalidation.
  271. - `ServerRegistry` / `ServerMonitor`: Handle mDNS/Zeroconf discovery/registration and background server health checks with recovery attempts.
  272. - **Dual Interface Implementation:**
  273. - **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.
  274. - **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.
  275. - **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.
  276. - **Resilience & 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.
  277. - **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.
  278. - **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.
  279. ---
  280. ## 🔄 Smart Cache Dependency Tracking
  281. The Smart Cache Dependency system allows tools to declare dependencies on other tools:
  282. - When a tool's cache is invalidated, all dependent tools are automatically invalidated
  283. - Dependencies are registered when servers declare tool relationships
  284. - View the dependency graph with `/cache dependencies`
  285. - Improves data consistency by ensuring related tools use fresh data
  286. Example dependency flow:
  287. ```
  288. weather:current → weather:forecast → travel:recommendations
  289. ```
  290. If the current weather data is updated, both the forecast and travel recommendations caches are automatically invalidated.
  291. ---
  292. ## 🔍 Tool & Server Discovery
  293. This client offers multiple ways to find and integrate MCP servers:
  294. - **Configured Paths:** Searches directories specified in `config.yaml` (under `discovery_paths`) for local `stdio` server scripts (e.g., `.py`, `.js`). Defaults include:
  295. - `.mcpclient_config/servers` (in project root)
  296. - `~/mcp-servers`
  297. - `~/modelcontextprotocol/servers`
  298. - **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.
  299. - **Intelligent Command Adaptation:**
  300. - Detects `wsl.exe ... <shell> -c "command ..."` patterns.
  301. - Extracts the Linux `<shell>` (e.g., `bash`, `sh`) and the `"command ..."`.
  302. - Remaps the configuration to execute the command directly using the identified Linux shell (e.g., `/bin/bash -c "command ..."`), bypassing `wsl.exe`.
  303. - 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.
  304. - **Remote Registries:** Connects to MCP registry server URLs defined in `config.yaml` (`registry_urls`) to discover publicly available or shared servers (typically SSE).
  305. - **Local Network (mDNS/Zeroconf):**
  306. - Uses the `zeroconf` library to listen for services advertised under `_mcp._tcp.local.` on the local network.
  307. - Provides real-time notifications in the interactive CLI when new servers appear or disappear.
  308. - The `/discover` command suite allows managing these discovered servers:
  309. - `/discover list`: View details of currently visible LAN servers.
  310. - `/discover connect <NAME>`: Add a discovered server to the configuration file and attempt to connect.
  311. - `/discover refresh`: Manually trigger a re-scan of the network.
  312. - `/discover auto [on|off]`: Toggle continuous background mDNS scanning (requires `enable_local_discovery: true` in config).
  313. - **Local Port Scanning:**
  314. - 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.
  315. - Attempts a basic MCP `initialize` handshake on each port to detect responsive MCP servers. Supports automatic detection of `sse` and `streaming-http` transport types based on server responses and HTTP headers.
  316. - Useful for finding servers that don't use mDNS advertisement.
  317. - The range, target IPs, concurrency, and timeout are configurable via `config.yaml` or the `/config port-scan ...` commands.
  318. - Found servers are presented alongside other discovered servers for optional addition to the configuration.
  319. ---
  320. ## 📡 Telemetry + Debugging
  321. - **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).
  322. - **Dashboards:**
  323. - **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.
  324. - **Web UI:** The "Servers" tab provides visual server status (connection, health via icons), and the header shows overall counts.
  325. - **Logging:** Uses Python's standard `logging` configured with `RichHandler` for pretty console output (to `stderr` to avoid `stdio` conflicts).
  326. - Use the `--verbose` or `-v` flag to increase log level to DEBUG for detailed internal information.
  327. - Verbose mode also enables detailed `stdio` session logging (`USE_VERBOSE_SESSION_LOGGING = True`) to see raw JSON-RPC messages (useful for debugging MCP servers).
  328. - **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.
  329. - **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/<server_name>_stderr.log`), crucial for diagnosing server-side problems.
  330. ---
  331. ## 📦 Configuration
  332. - **Primary File:** Configuration is loaded from and saved to `.mcpclient_config/config.yaml` located in the project's root directory.
  333. - **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.
  334. - **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`.
  335. - **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`.
  336. **View Current Config:**
  337. ```bash
  338. mcpclient config --show
  339. # OR in interactive mode:
  340. /config
  341. ```
  342. **Edit Config File Manually:**
  343. ```bash
  344. mcpclient config --edit
  345. # (This will open .mcpclient_config/config.yaml in the editor specified by your $EDITOR environment variable)
  346. ```
  347. ---
  348. ## 🧪 Development Notes
  349. - **Core:** Python 3.13+, `asyncio`
  350. - **CLI:** `Typer`, `Rich`
  351. - **Web:** `FastAPI`, `Uvicorn`, `WebSockets`, `Alpine.js`, `Tailwind CSS`, `DaisyUI`
  352. - **MCP:** `mcp` SDK (`mcp>=1.0.0`), `fastmcp` (for streaming-http transport)
  353. - **AI:** `anthropic` SDK (`anthropic>=0.15.0`)
  354. - **Observability:** `opentelemetry-sdk`, `opentelemetry-api`, `opentelemetry-instrumentation`
  355. - **Utilities:** `httpx`, `PyYAML`, `python-dotenv`, `psutil`, `aiofiles`, `diskcache`, `tiktoken`, `zeroconf`, `colorama`
  356. - **Linting/Formatting:** `ruff` is configured in `pyproject.toml`. Use `uv run lint` or `ruff check . && ruff format .`.
  357. - **Type Checking:** `mypy` is configured in `pyproject.toml`. Use `uv run typecheck` or `mypy mcpclient.py`.
  358. The 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`.
  359. ---
  360. ## 📝 License
  361. MIT License (with OpenAI/Anthropic Rider). See [LICENSE](LICENSE).

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.