chuk-mcp


Namechuk-mcp JSON
Version 0.5 PyPI version JSON
download
home_pageNone
SummaryModel Context Protocol Client with Optional Pydantic Support
upload_time2025-07-10 00:24:50
maintainerNone
docs_urlNone
authorNone
requires_python>=3.11
licenseMIT
keywords llm openai claude mcp client protocol
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # chuk-mcp

A comprehensive Python client implementation for the **Model Context Protocol (MCP)** - the open standard for connecting AI assistants to external data and tools.

[![PyPI version](https://badge.fury.io/py/chuk-mcp.svg)](https://badge.fury.io/py/chuk-mcp)
[![Python Version](https://img.shields.io/pypi/pyversions/chuk-mcp)](https://pypi.org/project/chuk-mcp/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![uv](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json)](https://github.com/astral-sh/uv)

## What is the Model Context Protocol?

The **Model Context Protocol (MCP)** is an open standard that enables AI applications to securely access external data and tools. Instead of every AI app building custom integrations, MCP provides a universal interface for:

- **๐Ÿ”ง Tools**: Functions AI can call (APIs, file operations, calculations)
- **๐Ÿ“„ Resources**: Data sources AI can read (files, databases, web content)  
- **๐Ÿ’ฌ Prompts**: Reusable prompt templates with parameters
- **๐ŸŽฏ Real-time Data**: Live information that changes frequently

**Key Benefits:**
- **Standardized**: One protocol for all integrations
- **Secure**: User-controlled access to sensitive data
- **Extensible**: Easy to add new capabilities
- **Language-Agnostic**: Works across different programming languages

## Why Use This Client?

`chuk-mcp` is a production-ready Python implementation that provides:

โœ… **Complete MCP Protocol Support** - All standard features including tools, resources, prompts, sampling, and completion  
โœ… **Type Safety** - Full type annotations with optional Pydantic integration or graceful fallback  
โœ… **Robust Error Handling** - Automatic retries, connection recovery, and detailed error reporting  
โœ… **Multi-Server Support** - Connect to multiple MCP servers simultaneously  
โœ… **Modern Architecture** - Clean separation of protocol, transport, and client layers  
โœ… **Developer Experience** - Rich CLI tools, comprehensive docs, and intuitive APIs  
โœ… **Production Ready** - Battle-tested with proper logging, monitoring, and performance optimization  
โœ… **UV Optimized** - First-class support for modern Python packaging with UV

## Installation

### Quick Start with UV (Recommended)

[UV](https://github.com/astral-sh/uv) is the fastest Python package manager. Choose your installation based on your needs:

```bash
# ๐Ÿš€ Minimal installation (uses lightweight fallback validation)
uv add chuk-mcp

# ๐Ÿ”ง With Pydantic validation (recommended for production)
uv add chuk-mcp[pydantic]

# ๐ŸŒŸ Full features (Pydantic + HTTP transport + all extras)
uv add chuk-mcp[full]

# ๐Ÿ› ๏ธ Development installation (includes testing and examples)
uv add chuk-mcp[dev]
```

### Traditional Installation

```bash
# Using pip (if UV not available)
pip install chuk-mcp

# With Pydantic support
pip install chuk-mcp[pydantic]

# Full features
pip install chuk-mcp[full]
```

### Installation Options Explained

| Option | Dependencies | Use Case | Performance |
|--------|-------------|----------|-------------|
| `chuk-mcp` | Core only | Minimal deployments, testing | Fast startup, lightweight validation |
| `chuk-mcp[pydantic]` | + Pydantic | Production use, type safety | Enhanced validation, better errors |
| `chuk-mcp[full]` | + All features | Maximum functionality | Full feature set |
| `chuk-mcp[dev]` | + Dev tools | Development, testing | All tools included |

> **๐Ÿ’ก Performance Note:** The lightweight fallback validation is ~20x slower than Pydantic (0.010ms vs 0.000ms per operation) but still excellent for most use cases. Use `[pydantic]` for high-throughput applications.

### Verify Installation

```bash
# Quick test with UV
uv run python -c "import chuk_mcp; print('โœ… chuk-mcp installed successfully')"

# Or test full functionality
uv run --with chuk-mcp[pydantic] python -c "
from chuk_mcp.protocol.mcp_pydantic_base import PYDANTIC_AVAILABLE
print(f'โœ… Pydantic available: {PYDANTIC_AVAILABLE}')
"
```

## Protocol Compliance

`chuk-mcp` provides comprehensive compliance with the MCP specification across multiple protocol versions:

### ๐Ÿ“‹ Supported Protocol Versions
- **Latest**: `2025-06-18` (primary support)
- **Stable**: `2025-03-26` (full compatibility)
- **Legacy**: `2024-11-05` (backward compatibility)

### ๐ŸŽฏ Core Protocol Features

#### โœ… **JSON-RPC 2.0 Compliance**
- Complete request/response/notification handling
- Proper error code classification
- Version-aware message routing
- Batching support (version-dependent)

#### โœ… **Transport Layer Support**
- **Stdio Transport**: Primary subprocess-based communication
- **HTTP Transport**: Modern streamable HTTP transport (spec 2025-03-26)
- **SSE Transport**: Deprecated Server-Sent Events (backward compatibility)
- **Pluggable Architecture**: Easy to add new transport types

#### โœ… **MCP Operations**
- **๐Ÿ”ง Tools**: List and call server tools with full argument validation
- **๐Ÿ“„ Resources**: Discover and read server resources with URI support
- **๐Ÿ’ฌ Prompts**: Get parameterized prompt templates with argument substitution
- **๐ŸŽฏ Sampling**: Client-side LLM sampling (advanced feature)
- **๐Ÿ“ Completion**: Argument autocompletion for enhanced UX
- **๐ŸŒณ Roots**: File system access control and security
- **โ“ Elicitation**: User input requests (new in 2025-06-18)

### ๐Ÿš€ Advanced Protocol Features

#### โœ… **Session Management**
- Automatic initialization and capability exchange
- Version negotiation with fallback support
- Multi-client session handling (server-side)
- Connection lifecycle management

#### โœ… **Real-time Operations**
- **Progress Tracking**: Long-running operation progress reporting
- **Cancellation**: Request cancellation support with proper cleanup
- **Notifications**: Real-time event notifications (resource changes, logs)
- **Subscriptions**: Resource change monitoring

#### โœ… **Error Handling & Resilience**
- Comprehensive error classification (retryable vs non-retryable)
- Automatic retry logic with exponential backoff
- Connection recovery and reconnection
- Structured error reporting with context

#### โœ… **Version-Aware Features**
- **Feature Detection**: Automatic capability discovery
- **Batching**: JSON-RPC batch support where available
- **Protocol Upgrades**: Seamless version transitions
- **Backward Compatibility**: Graceful degradation for older servers

### ๐Ÿ“Š Protocol Compliance Matrix

| Feature Category | 2024-11-05 | 2025-03-26 | 2025-06-18 | Implementation Status |
|-----------------|------------|------------|------------|---------------------|
| **Core Operations** | | | | |
| Tools (list/call) | โœ… | โœ… | โœ… | โœ… Complete |
| Resources (list/read/subscribe) | โœ… | โœ… | โœ… | โœ… Complete |
| Prompts (list/get) | โœ… | โœ… | โœ… | โœ… Complete |
| **Transport** | | | | |
| Stdio | โœ… | โœ… | โœ… | โœ… Complete |
| SSE | โœ… | โš ๏ธ Deprecated | โŒ Removed | โœ… Legacy Support |
| HTTP Streaming | โŒ | โœ… | โœ… | โœ… Complete |
| **Advanced Features** | | | | |
| Sampling | โŒ | โœ… | โœ… | โœ… Complete |
| Completion | โŒ | โœ… | โœ… | โœ… Complete |
| Roots | โŒ | โœ… | โœ… | โœ… Complete |
| Elicitation | โŒ | โŒ | โœ… | โœ… Complete |
| **Quality Features** | | | | |
| Progress Tracking | โœ… | โœ… | โœ… | โœ… Complete |
| Cancellation | โœ… | โœ… | โœ… | โœ… Complete |
| Notifications | โœ… | โœ… | โœ… | โœ… Complete |
| Batching | โŒ | โœ… | โœ… | โœ… Complete |

## Quick Start

### 5-Minute Demo

```bash
# Get started instantly with UV
uv run --with chuk-mcp[pydantic] python - << 'EOF'
import anyio
from chuk_mcp import stdio_client, StdioServerParameters
from chuk_mcp.protocol.messages import send_initialize

async def main():
    # Demo with echo server (no external dependencies)
    server_params = StdioServerParameters(
        command="python",
        args=["-c", """
import json, sys
init = json.loads(input())
print(json.dumps({"id": init["id"], "result": {"serverInfo": {"name": "Demo", "version": "1.0"}, "protocolVersion": "2025-06-18", "capabilities": {}}}))
        """]
    )
    
    async with stdio_client(server_params) as (read, write):
        result = await send_initialize(read, write)
        print(f"โœ… Connected to {result.serverInfo.name}")

anyio.run(main)
EOF
```

### Basic Usage with Real Server

```python
import anyio
from chuk_mcp import stdio_client, StdioServerParameters
from chuk_mcp.protocol.messages import send_initialize

async def main():
    # Configure connection to an MCP server
    server_params = StdioServerParameters(
        command="uvx",  # Use uvx to run Python tools
        args=["mcp-server-sqlite", "--db-path", "example.db"]
    )
    
    # Connect and initialize
    async with stdio_client(server_params) as (read_stream, write_stream):
        # Initialize the MCP session
        init_result = await send_initialize(read_stream, write_stream)
        
        if init_result:
            print(f"โœ… Connected to {init_result.serverInfo.name}")
            print(f"๐Ÿ“‹ Protocol version: {init_result.protocolVersion}")
        else:
            print("โŒ Failed to initialize connection")

anyio.run(main)
```

### Using the CLI

Test server connectivity instantly:

```bash
# Test with quickstart demo
uv run examples/quickstart.py

# Run comprehensive demos
uv run examples/e2e_smoke_test_example.py --demo all

# Test specific server configurations
uv run examples/e2e_smoke_test_example.py --smoke
```

## Core Concepts

### ๐Ÿ”ง Tools - Functions AI Can Call

Tools are functions that AI can execute on your behalf. Examples include file operations, API calls, calculations, or any custom logic.

```python
from chuk_mcp.protocol.messages import send_tools_list, send_tools_call

async def explore_tools(read_stream, write_stream):
    # List available tools
    tools_response = await send_tools_list(read_stream, write_stream)
    
    for tool in tools_response.get("tools", []):
        print(f"๐Ÿ”ง {tool['name']}: {tool['description']}")
    
    # Call a specific tool
    result = await send_tools_call(
        read_stream, write_stream,
        name="execute_sql",
        arguments={"query": "SELECT COUNT(*) FROM users"}
    )
    
    print(f"๐Ÿ“Š Query result: {result}")
```

### ๐Ÿ“„ Resources - Data AI Can Access

Resources are data sources like files, database records, API responses, or any URI-addressable content.

```python
from chuk_mcp.protocol.messages import send_resources_list, send_resources_read

async def explore_resources(read_stream, write_stream):
    # Discover available resources
    resources_response = await send_resources_list(read_stream, write_stream)
    
    for resource in resources_response.get("resources", []):
        print(f"๐Ÿ“„ {resource['name']} ({resource.get('mimeType', 'unknown')})")
        print(f"   URI: {resource['uri']}")
    
    # Read specific resource content
    if resources_response.get("resources"):
        first_resource = resources_response["resources"][0]
        content = await send_resources_read(read_stream, write_stream, first_resource["uri"])
        
        for item in content.get("contents", []):
            if "text" in item:
                print(f"๐Ÿ“– Content preview: {item['text'][:200]}...")
```

### ๐Ÿ’ฌ Prompts - Reusable Templates

Prompts are parameterized templates that help generate consistent, high-quality AI interactions.

```python
from chuk_mcp.protocol.messages import send_prompts_list, send_prompts_get

async def use_prompts(read_stream, write_stream):
    # List available prompt templates
    prompts_response = await send_prompts_list(read_stream, write_stream)
    
    for prompt in prompts_response.get("prompts", []):
        print(f"๐Ÿ’ฌ {prompt['name']}: {prompt['description']}")
    
    # Get a prompt with custom arguments
    prompt_result = await send_prompts_get(
        read_stream, write_stream,
        name="analyze_data",
        arguments={"dataset": "sales_2024", "metric": "revenue"}
    )
    
    # The result contains formatted messages ready for AI
    for message in prompt_result.get("messages", []):
        print(f"๐Ÿค– {message['role']}: {message['content']}")
```

## Architecture

`chuk-mcp` features a clean, layered architecture that separates concerns and enables extensibility:

```
chuk_mcp/
โ”œโ”€โ”€ protocol/           # ๐Ÿ—๏ธ Shared protocol layer
โ”‚   โ”œโ”€โ”€ types/         #    Type definitions and validation
โ”‚   โ”œโ”€โ”€ messages/      #    Feature-organized messaging
โ”‚   โ””โ”€โ”€ mcp_pydantic_base.py  # Type system foundation with fallback
โ””โ”€โ”€ mcp_client/        # ๐Ÿš€ Client implementation  
    โ”œโ”€โ”€ transport/     #    Communication layer (stdio, future: HTTP/WS)
    โ”œโ”€โ”€ host/          #    High-level management
    โ””โ”€โ”€ __init__.py    #    Convenient unified API
```

**Benefits of This Architecture:**
- **๐Ÿ”Œ Pluggable Transports**: Easy to add HTTP, WebSocket, or other transports
- **โ™ป๏ธ Reusable Protocol Layer**: Can be used by servers, proxies, or other tools
- **๐Ÿงช Testable Components**: Each layer can be tested independently
- **๐Ÿ“ฆ Clean Dependencies**: Minimal coupling between layers
- **โšก Smart Validation**: Optional Pydantic with intelligent fallback

## Configuration

### Server Configuration

Create a `server_config.json` file to define your MCP servers:

```json
{
  "mcpServers": {
    "sqlite": {
      "command": "uvx",
      "args": ["mcp-server-sqlite", "--db-path", "database.db"]
    },
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/files"]
    },
    "github": {
      "command": "uvx",
      "args": ["mcp-server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
      }
    },
    "python": {
      "command": "uv",
      "args": ["run", "--with", "mcp-server-python", "mcp-server-python"],
      "env": {
        "PYTHONPATH": "/custom/python/path"
      }
    }
  }
}
```

### Configuration Loading

```python
from chuk_mcp.mcp_client.host import load_config
from chuk_mcp import stdio_client
from chuk_mcp.protocol.messages import send_initialize

async def connect_configured_server():
    # Load server configuration
    server_params = await load_config("server_config.json", "sqlite")
    
    async with stdio_client(server_params) as (read_stream, write_stream):
        init_result = await send_initialize(read_stream, write_stream)
        print(f"Connected to configured server: {init_result.serverInfo.name}")
```

## Advanced Features

### ๐ŸŽฏ Intelligent Sampling

Let servers request AI to generate content on their behalf (with user approval):

```python
from chuk_mcp.protocol.messages.sampling import (
    send_sampling_create_message, 
    create_sampling_message
)

async def ai_content_generation(read_stream, write_stream):
    # Server can request AI to generate content
    messages = [
        create_sampling_message("user", "Explain quantum computing in simple terms")
    ]
    
    result = await send_sampling_create_message(
        read_stream, write_stream,
        messages=messages,
        max_tokens=1000,
        temperature=0.7
    )
    
    print(f"๐Ÿค– AI Generated: {result['content']['text']}")
```

### ๐ŸŽฏ Argument Completion

Provide intelligent autocompletion for tool arguments:

```python
from chuk_mcp.protocol.messages.completion import (
    send_completion_complete, 
    create_resource_reference, 
    create_argument_info
)

async def smart_completion(read_stream, write_stream):
    # Get completion suggestions for a resource argument
    response = await send_completion_complete(
        read_stream, write_stream,
        ref=create_resource_reference("file:///project/data/"),
        argument=create_argument_info("filename", "sales_202")
    )
    
    completions = response.get("completion", {}).get("values", [])
    print(f"๐Ÿ’ก Suggestions: {completions}")
```

### ๐Ÿ”„ Multi-Server Orchestration

Connect to multiple servers simultaneously:

```python
from chuk_mcp.mcp_client.host import run_command
from chuk_mcp.protocol.messages import send_tools_list

async def multi_server_task(server_streams):
    """Process data using multiple MCP servers."""
    
    # server_streams contains connections to all configured servers
    for i, (read_stream, write_stream) in enumerate(server_streams):
        print(f"Processing with server {i+1}")
        
        # Each server can have different capabilities
        tools = await send_tools_list(read_stream, write_stream)
        print(f"  Available tools: {len(tools.get('tools', []))}")

# Run across multiple servers defined in config
run_command(multi_server_task, "server_config.json", ["sqlite", "filesystem", "github"])
```

### ๐Ÿ“ก Real-time Subscriptions

Subscribe to resource changes for live updates:

```python
from chuk_mcp.protocol.messages.resources import send_resources_subscribe

async def live_monitoring(read_stream, write_stream):
    # Subscribe to file changes
    success = await send_resources_subscribe(
        read_stream, write_stream,
        uri="file:///project/logs/app.log"
    )
    
    if success:
        print("๐Ÿ“ก Subscribed to log file changes")
        
        # Handle notifications in your message loop
        # (implementation depends on your notification handling)
```

## Error Handling & Resilience

`chuk-mcp` provides robust error handling with automatic retries:

```python
from chuk_mcp.protocol.messages import RetryableError, NonRetryableError
from chuk_mcp.protocol.messages import send_tools_call

async def resilient_operations(read_stream, write_stream):
    try:
        # Operations automatically retry on transient failures
        result = await send_tools_call(
            read_stream, write_stream,
            name="network_operation",
            arguments={"url": "https://api.example.com/data"},
            timeout=30.0,  # Extended timeout for slow operations
            retries=5      # More retries for critical operations
        )
        
    except RetryableError as e:
        print(f"โš ๏ธ Transient error after retries: {e}")
        # Handle gracefully - maybe try alternative approach
        
    except NonRetryableError as e:
        print(f"โŒ Permanent error: {e}")
        # Handle definitively - operation cannot succeed
        
    except Exception as e:
        print(f"๐Ÿšจ Unexpected error: {e}")
        # Handle unknown errors
```

## Available MCP Servers

The MCP ecosystem includes servers for popular services:

### ๐Ÿš€ Install with UV (Recommended)

```bash
# Popular Python servers
uv tool install mcp-server-sqlite
uv tool install mcp-server-github
uv tool install mcp-server-postgres

# Or run directly without installation
uv run --with mcp-server-sqlite mcp-server-sqlite --db-path data.db
```

### ๐ŸŸข Node.js Servers

```bash
# Use npx for Node.js servers
npx -y @modelcontextprotocol/server-filesystem /path/to/files
npx -y @modelcontextprotocol/server-brave-search
```

### ๐Ÿ“ Available Servers

- **๐Ÿ“ Filesystem**: `@modelcontextprotocol/server-filesystem` 
- **๐Ÿ—„๏ธ SQLite**: `mcp-server-sqlite` 
- **๐Ÿ™ GitHub**: `mcp-server-github`
- **โ˜๏ธ Google Drive**: `mcp-server-gdrive`
- **๐Ÿ” Web Search**: `mcp-server-brave-search`
- **๐Ÿ“Š PostgreSQL**: `mcp-server-postgres`
- **๐Ÿ“ˆ Analytics**: Various data analytics servers
- **๐Ÿ”ง Custom**: Build your own with the MCP SDK

Find more at: [MCP Servers Directory](https://github.com/modelcontextprotocol/servers)

## Building MCP Servers

Want to create your own MCP server? Check out:

- **Python**: [`mcp` package](https://pypi.org/project/mcp/)
- **TypeScript**: [`@modelcontextprotocol/sdk`](https://www.npmjs.com/package/@modelcontextprotocol/sdk)
- **Specification**: [MCP Protocol Documentation](https://spec.modelcontextprotocol.io/)

## Development

### Setup with UV

```bash
git clone https://github.com/chrishayuk/chuk-mcp
cd chuk-mcp

# Install with development dependencies
uv sync

# Activate the virtual environment
source .venv/bin/activate  # Linux/Mac
# or .venv\Scripts\activate  # Windows
```

### Traditional Setup

```bash
# Alternative setup with pip
pip install -e ".[dev]"
```

### Testing & Validation

```bash
# Quick validation
uv run examples/quickstart.py

# Run comprehensive tests
uv run examples/e2e_smoke_test_example.py --demo all

# Validate installation scenarios
uv run diagnostics/installation_scenarios_diagnostic.py

# Test specific functionality
uv run examples/e2e_smoke_test_example.py --smoke

# Performance benchmarks
uv run examples/e2e_smoke_test_example.py --performance
```

### Development Features

```bash
# Test with fallback validation
UV_MCP_FORCE_FALLBACK=1 uv run examples/quickstart.py

# Test with different Python versions
uv run --python 3.11 examples/quickstart.py
uv run --python 3.12 examples/quickstart.py
```

### Contributing

1. Fork the repository
2. Create a feature branch
3. Add tests for your changes
4. Ensure all tests pass with `uv run diagnostics/installation_scenarios_diagnostic.py`
5. Submit a pull request

## Performance & Monitoring

`chuk-mcp` includes built-in performance monitoring:

```python
import logging

# Enable detailed logging for debugging
logging.basicConfig(level=logging.DEBUG)

# Performance is optimized for:
# - Concurrent server connections
# - Efficient message routing  
# - Minimal memory allocation
# - Fast JSON serialization
```

**Performance Highlights:**
- **๐Ÿš€ Fast Startup**: < 1 second connection time
- **โšก High Throughput**: 50+ requests/second per connection
- **๐Ÿ”„ Concurrent Operations**: Full async/await support
- **๐Ÿ’พ Memory Efficient**: Minimal overhead per connection

## Intelligent Dependency Management

`chuk-mcp` includes intelligent dependency handling with graceful fallbacks:

```python
# Check validation backend
from chuk_mcp.protocol.mcp_pydantic_base import PYDANTIC_AVAILABLE

if PYDANTIC_AVAILABLE:
    print("โœ… Using Pydantic for enhanced validation")
    print("   โ€ข Better error messages")
    print("   โ€ข Faster validation (Rust-based)")
    print("   โ€ข Advanced type coercion")
else:
    print("๐Ÿ“ฆ Using lightweight fallback validation")
    print("   โ€ข Pure Python implementation")
    print("   โ€ข No external dependencies")
    print("   โ€ข ~20x slower but still fast")

# Force fallback mode for testing
import os
os.environ["MCP_FORCE_FALLBACK"] = "1"
```

### Installation Performance Matrix

| Installation | Startup Time | Validation Speed | Memory Usage | Dependencies |
|-------------|-------------|------------------|--------------|--------------|
| `chuk-mcp` | < 0.5s | 0.010ms/op | 15MB | Core only |
| `chuk-mcp[pydantic]` | < 1.0s | 0.000ms/op | 25MB | + Pydantic |
| `chuk-mcp[full]` | < 1.5s | 0.000ms/op | 35MB | All features |

## UV Integration Features

### Project Templates

```bash
# Start a new MCP client project
uv init my-mcp-client
cd my-mcp-client

# Add chuk-mcp with dependencies
uv add chuk-mcp[pydantic]

# Add development tools
uv add --dev pytest black isort

# Create example
cat > main.py << 'EOF'
import anyio
from chuk_mcp import stdio_client, StdioServerParameters

async def main():
    # Your MCP client code here
    pass

if __name__ == "__main__":
    anyio.run(main)
EOF
```

### UV Scripts

Add to your `pyproject.toml`:

```toml
[tool.uv]
dev-dependencies = [
    "chuk-mcp[dev]",
]

[project.scripts]
mcp-client = "my_mcp_client:main"

[tool.uv.scripts]
test-mcp = "uv run examples/quickstart.py"
validate = "uv run diagnostics/installation_scenarios_diagnostic.py"
```

## Support & Community

- **๐Ÿ“– Documentation**: [Full API Documentation](https://docs.example.com)
- **๐Ÿ› Issues**: [GitHub Issues](https://github.com/chrishayuk/chuk-mcp/issues)
- **๐Ÿ’ฌ Discussions**: [GitHub Discussions](https://github.com/chrishayuk/chuk-mcp/discussions)
- **๐Ÿ“ง Email**: For private inquiries
- **๐Ÿš€ UV**: [UV Package Manager](https://github.com/astral-sh/uv)

## License

MIT License - see [LICENSE](LICENSE) file for details.

## Acknowledgments

- Built on the [Model Context Protocol](https://modelcontextprotocol.io/) specification
- Inspired by the official [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk)
- Thanks to the MCP community for feedback and contributions
- Special thanks to the [UV](https://github.com/astral-sh/uv) team for making Python package management fast and reliable

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "chuk-mcp",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.11",
    "maintainer_email": null,
    "keywords": "llm, openai, claude, mcp, client, protocol",
    "author": null,
    "author_email": "Chris Hay <chrishayuk@somejunkmailbox.com>",
    "download_url": "https://files.pythonhosted.org/packages/07/ad/75c7c980a6a409a95ee179d0e83f0a74b5501e94f861bc5f8e97ef8c9d86/chuk_mcp-0.5.tar.gz",
    "platform": null,
    "description": "# chuk-mcp\n\nA comprehensive Python client implementation for the **Model Context Protocol (MCP)** - the open standard for connecting AI assistants to external data and tools.\n\n[![PyPI version](https://badge.fury.io/py/chuk-mcp.svg)](https://badge.fury.io/py/chuk-mcp)\n[![Python Version](https://img.shields.io/pypi/pyversions/chuk-mcp)](https://pypi.org/project/chuk-mcp/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![uv](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json)](https://github.com/astral-sh/uv)\n\n## What is the Model Context Protocol?\n\nThe **Model Context Protocol (MCP)** is an open standard that enables AI applications to securely access external data and tools. Instead of every AI app building custom integrations, MCP provides a universal interface for:\n\n- **\ud83d\udd27 Tools**: Functions AI can call (APIs, file operations, calculations)\n- **\ud83d\udcc4 Resources**: Data sources AI can read (files, databases, web content)  \n- **\ud83d\udcac Prompts**: Reusable prompt templates with parameters\n- **\ud83c\udfaf Real-time Data**: Live information that changes frequently\n\n**Key Benefits:**\n- **Standardized**: One protocol for all integrations\n- **Secure**: User-controlled access to sensitive data\n- **Extensible**: Easy to add new capabilities\n- **Language-Agnostic**: Works across different programming languages\n\n## Why Use This Client?\n\n`chuk-mcp` is a production-ready Python implementation that provides:\n\n\u2705 **Complete MCP Protocol Support** - All standard features including tools, resources, prompts, sampling, and completion  \n\u2705 **Type Safety** - Full type annotations with optional Pydantic integration or graceful fallback  \n\u2705 **Robust Error Handling** - Automatic retries, connection recovery, and detailed error reporting  \n\u2705 **Multi-Server Support** - Connect to multiple MCP servers simultaneously  \n\u2705 **Modern Architecture** - Clean separation of protocol, transport, and client layers  \n\u2705 **Developer Experience** - Rich CLI tools, comprehensive docs, and intuitive APIs  \n\u2705 **Production Ready** - Battle-tested with proper logging, monitoring, and performance optimization  \n\u2705 **UV Optimized** - First-class support for modern Python packaging with UV\n\n## Installation\n\n### Quick Start with UV (Recommended)\n\n[UV](https://github.com/astral-sh/uv) is the fastest Python package manager. Choose your installation based on your needs:\n\n```bash\n# \ud83d\ude80 Minimal installation (uses lightweight fallback validation)\nuv add chuk-mcp\n\n# \ud83d\udd27 With Pydantic validation (recommended for production)\nuv add chuk-mcp[pydantic]\n\n# \ud83c\udf1f Full features (Pydantic + HTTP transport + all extras)\nuv add chuk-mcp[full]\n\n# \ud83d\udee0\ufe0f Development installation (includes testing and examples)\nuv add chuk-mcp[dev]\n```\n\n### Traditional Installation\n\n```bash\n# Using pip (if UV not available)\npip install chuk-mcp\n\n# With Pydantic support\npip install chuk-mcp[pydantic]\n\n# Full features\npip install chuk-mcp[full]\n```\n\n### Installation Options Explained\n\n| Option | Dependencies | Use Case | Performance |\n|--------|-------------|----------|-------------|\n| `chuk-mcp` | Core only | Minimal deployments, testing | Fast startup, lightweight validation |\n| `chuk-mcp[pydantic]` | + Pydantic | Production use, type safety | Enhanced validation, better errors |\n| `chuk-mcp[full]` | + All features | Maximum functionality | Full feature set |\n| `chuk-mcp[dev]` | + Dev tools | Development, testing | All tools included |\n\n> **\ud83d\udca1 Performance Note:** The lightweight fallback validation is ~20x slower than Pydantic (0.010ms vs 0.000ms per operation) but still excellent for most use cases. Use `[pydantic]` for high-throughput applications.\n\n### Verify Installation\n\n```bash\n# Quick test with UV\nuv run python -c \"import chuk_mcp; print('\u2705 chuk-mcp installed successfully')\"\n\n# Or test full functionality\nuv run --with chuk-mcp[pydantic] python -c \"\nfrom chuk_mcp.protocol.mcp_pydantic_base import PYDANTIC_AVAILABLE\nprint(f'\u2705 Pydantic available: {PYDANTIC_AVAILABLE}')\n\"\n```\n\n## Protocol Compliance\n\n`chuk-mcp` provides comprehensive compliance with the MCP specification across multiple protocol versions:\n\n### \ud83d\udccb Supported Protocol Versions\n- **Latest**: `2025-06-18` (primary support)\n- **Stable**: `2025-03-26` (full compatibility)\n- **Legacy**: `2024-11-05` (backward compatibility)\n\n### \ud83c\udfaf Core Protocol Features\n\n#### \u2705 **JSON-RPC 2.0 Compliance**\n- Complete request/response/notification handling\n- Proper error code classification\n- Version-aware message routing\n- Batching support (version-dependent)\n\n#### \u2705 **Transport Layer Support**\n- **Stdio Transport**: Primary subprocess-based communication\n- **HTTP Transport**: Modern streamable HTTP transport (spec 2025-03-26)\n- **SSE Transport**: Deprecated Server-Sent Events (backward compatibility)\n- **Pluggable Architecture**: Easy to add new transport types\n\n#### \u2705 **MCP Operations**\n- **\ud83d\udd27 Tools**: List and call server tools with full argument validation\n- **\ud83d\udcc4 Resources**: Discover and read server resources with URI support\n- **\ud83d\udcac Prompts**: Get parameterized prompt templates with argument substitution\n- **\ud83c\udfaf Sampling**: Client-side LLM sampling (advanced feature)\n- **\ud83d\udcdd Completion**: Argument autocompletion for enhanced UX\n- **\ud83c\udf33 Roots**: File system access control and security\n- **\u2753 Elicitation**: User input requests (new in 2025-06-18)\n\n### \ud83d\ude80 Advanced Protocol Features\n\n#### \u2705 **Session Management**\n- Automatic initialization and capability exchange\n- Version negotiation with fallback support\n- Multi-client session handling (server-side)\n- Connection lifecycle management\n\n#### \u2705 **Real-time Operations**\n- **Progress Tracking**: Long-running operation progress reporting\n- **Cancellation**: Request cancellation support with proper cleanup\n- **Notifications**: Real-time event notifications (resource changes, logs)\n- **Subscriptions**: Resource change monitoring\n\n#### \u2705 **Error Handling & Resilience**\n- Comprehensive error classification (retryable vs non-retryable)\n- Automatic retry logic with exponential backoff\n- Connection recovery and reconnection\n- Structured error reporting with context\n\n#### \u2705 **Version-Aware Features**\n- **Feature Detection**: Automatic capability discovery\n- **Batching**: JSON-RPC batch support where available\n- **Protocol Upgrades**: Seamless version transitions\n- **Backward Compatibility**: Graceful degradation for older servers\n\n### \ud83d\udcca Protocol Compliance Matrix\n\n| Feature Category | 2024-11-05 | 2025-03-26 | 2025-06-18 | Implementation Status |\n|-----------------|------------|------------|------------|---------------------|\n| **Core Operations** | | | | |\n| Tools (list/call) | \u2705 | \u2705 | \u2705 | \u2705 Complete |\n| Resources (list/read/subscribe) | \u2705 | \u2705 | \u2705 | \u2705 Complete |\n| Prompts (list/get) | \u2705 | \u2705 | \u2705 | \u2705 Complete |\n| **Transport** | | | | |\n| Stdio | \u2705 | \u2705 | \u2705 | \u2705 Complete |\n| SSE | \u2705 | \u26a0\ufe0f Deprecated | \u274c Removed | \u2705 Legacy Support |\n| HTTP Streaming | \u274c | \u2705 | \u2705 | \u2705 Complete |\n| **Advanced Features** | | | | |\n| Sampling | \u274c | \u2705 | \u2705 | \u2705 Complete |\n| Completion | \u274c | \u2705 | \u2705 | \u2705 Complete |\n| Roots | \u274c | \u2705 | \u2705 | \u2705 Complete |\n| Elicitation | \u274c | \u274c | \u2705 | \u2705 Complete |\n| **Quality Features** | | | | |\n| Progress Tracking | \u2705 | \u2705 | \u2705 | \u2705 Complete |\n| Cancellation | \u2705 | \u2705 | \u2705 | \u2705 Complete |\n| Notifications | \u2705 | \u2705 | \u2705 | \u2705 Complete |\n| Batching | \u274c | \u2705 | \u2705 | \u2705 Complete |\n\n## Quick Start\n\n### 5-Minute Demo\n\n```bash\n# Get started instantly with UV\nuv run --with chuk-mcp[pydantic] python - << 'EOF'\nimport anyio\nfrom chuk_mcp import stdio_client, StdioServerParameters\nfrom chuk_mcp.protocol.messages import send_initialize\n\nasync def main():\n    # Demo with echo server (no external dependencies)\n    server_params = StdioServerParameters(\n        command=\"python\",\n        args=[\"-c\", \"\"\"\nimport json, sys\ninit = json.loads(input())\nprint(json.dumps({\"id\": init[\"id\"], \"result\": {\"serverInfo\": {\"name\": \"Demo\", \"version\": \"1.0\"}, \"protocolVersion\": \"2025-06-18\", \"capabilities\": {}}}))\n        \"\"\"]\n    )\n    \n    async with stdio_client(server_params) as (read, write):\n        result = await send_initialize(read, write)\n        print(f\"\u2705 Connected to {result.serverInfo.name}\")\n\nanyio.run(main)\nEOF\n```\n\n### Basic Usage with Real Server\n\n```python\nimport anyio\nfrom chuk_mcp import stdio_client, StdioServerParameters\nfrom chuk_mcp.protocol.messages import send_initialize\n\nasync def main():\n    # Configure connection to an MCP server\n    server_params = StdioServerParameters(\n        command=\"uvx\",  # Use uvx to run Python tools\n        args=[\"mcp-server-sqlite\", \"--db-path\", \"example.db\"]\n    )\n    \n    # Connect and initialize\n    async with stdio_client(server_params) as (read_stream, write_stream):\n        # Initialize the MCP session\n        init_result = await send_initialize(read_stream, write_stream)\n        \n        if init_result:\n            print(f\"\u2705 Connected to {init_result.serverInfo.name}\")\n            print(f\"\ud83d\udccb Protocol version: {init_result.protocolVersion}\")\n        else:\n            print(\"\u274c Failed to initialize connection\")\n\nanyio.run(main)\n```\n\n### Using the CLI\n\nTest server connectivity instantly:\n\n```bash\n# Test with quickstart demo\nuv run examples/quickstart.py\n\n# Run comprehensive demos\nuv run examples/e2e_smoke_test_example.py --demo all\n\n# Test specific server configurations\nuv run examples/e2e_smoke_test_example.py --smoke\n```\n\n## Core Concepts\n\n### \ud83d\udd27 Tools - Functions AI Can Call\n\nTools are functions that AI can execute on your behalf. Examples include file operations, API calls, calculations, or any custom logic.\n\n```python\nfrom chuk_mcp.protocol.messages import send_tools_list, send_tools_call\n\nasync def explore_tools(read_stream, write_stream):\n    # List available tools\n    tools_response = await send_tools_list(read_stream, write_stream)\n    \n    for tool in tools_response.get(\"tools\", []):\n        print(f\"\ud83d\udd27 {tool['name']}: {tool['description']}\")\n    \n    # Call a specific tool\n    result = await send_tools_call(\n        read_stream, write_stream,\n        name=\"execute_sql\",\n        arguments={\"query\": \"SELECT COUNT(*) FROM users\"}\n    )\n    \n    print(f\"\ud83d\udcca Query result: {result}\")\n```\n\n### \ud83d\udcc4 Resources - Data AI Can Access\n\nResources are data sources like files, database records, API responses, or any URI-addressable content.\n\n```python\nfrom chuk_mcp.protocol.messages import send_resources_list, send_resources_read\n\nasync def explore_resources(read_stream, write_stream):\n    # Discover available resources\n    resources_response = await send_resources_list(read_stream, write_stream)\n    \n    for resource in resources_response.get(\"resources\", []):\n        print(f\"\ud83d\udcc4 {resource['name']} ({resource.get('mimeType', 'unknown')})\")\n        print(f\"   URI: {resource['uri']}\")\n    \n    # Read specific resource content\n    if resources_response.get(\"resources\"):\n        first_resource = resources_response[\"resources\"][0]\n        content = await send_resources_read(read_stream, write_stream, first_resource[\"uri\"])\n        \n        for item in content.get(\"contents\", []):\n            if \"text\" in item:\n                print(f\"\ud83d\udcd6 Content preview: {item['text'][:200]}...\")\n```\n\n### \ud83d\udcac Prompts - Reusable Templates\n\nPrompts are parameterized templates that help generate consistent, high-quality AI interactions.\n\n```python\nfrom chuk_mcp.protocol.messages import send_prompts_list, send_prompts_get\n\nasync def use_prompts(read_stream, write_stream):\n    # List available prompt templates\n    prompts_response = await send_prompts_list(read_stream, write_stream)\n    \n    for prompt in prompts_response.get(\"prompts\", []):\n        print(f\"\ud83d\udcac {prompt['name']}: {prompt['description']}\")\n    \n    # Get a prompt with custom arguments\n    prompt_result = await send_prompts_get(\n        read_stream, write_stream,\n        name=\"analyze_data\",\n        arguments={\"dataset\": \"sales_2024\", \"metric\": \"revenue\"}\n    )\n    \n    # The result contains formatted messages ready for AI\n    for message in prompt_result.get(\"messages\", []):\n        print(f\"\ud83e\udd16 {message['role']}: {message['content']}\")\n```\n\n## Architecture\n\n`chuk-mcp` features a clean, layered architecture that separates concerns and enables extensibility:\n\n```\nchuk_mcp/\n\u251c\u2500\u2500 protocol/           # \ud83c\udfd7\ufe0f Shared protocol layer\n\u2502   \u251c\u2500\u2500 types/         #    Type definitions and validation\n\u2502   \u251c\u2500\u2500 messages/      #    Feature-organized messaging\n\u2502   \u2514\u2500\u2500 mcp_pydantic_base.py  # Type system foundation with fallback\n\u2514\u2500\u2500 mcp_client/        # \ud83d\ude80 Client implementation  \n    \u251c\u2500\u2500 transport/     #    Communication layer (stdio, future: HTTP/WS)\n    \u251c\u2500\u2500 host/          #    High-level management\n    \u2514\u2500\u2500 __init__.py    #    Convenient unified API\n```\n\n**Benefits of This Architecture:**\n- **\ud83d\udd0c Pluggable Transports**: Easy to add HTTP, WebSocket, or other transports\n- **\u267b\ufe0f Reusable Protocol Layer**: Can be used by servers, proxies, or other tools\n- **\ud83e\uddea Testable Components**: Each layer can be tested independently\n- **\ud83d\udce6 Clean Dependencies**: Minimal coupling between layers\n- **\u26a1 Smart Validation**: Optional Pydantic with intelligent fallback\n\n## Configuration\n\n### Server Configuration\n\nCreate a `server_config.json` file to define your MCP servers:\n\n```json\n{\n  \"mcpServers\": {\n    \"sqlite\": {\n      \"command\": \"uvx\",\n      \"args\": [\"mcp-server-sqlite\", \"--db-path\", \"database.db\"]\n    },\n    \"filesystem\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-filesystem\", \"/path/to/files\"]\n    },\n    \"github\": {\n      \"command\": \"uvx\",\n      \"args\": [\"mcp-server-github\"],\n      \"env\": {\n        \"GITHUB_PERSONAL_ACCESS_TOKEN\": \"${GITHUB_TOKEN}\"\n      }\n    },\n    \"python\": {\n      \"command\": \"uv\",\n      \"args\": [\"run\", \"--with\", \"mcp-server-python\", \"mcp-server-python\"],\n      \"env\": {\n        \"PYTHONPATH\": \"/custom/python/path\"\n      }\n    }\n  }\n}\n```\n\n### Configuration Loading\n\n```python\nfrom chuk_mcp.mcp_client.host import load_config\nfrom chuk_mcp import stdio_client\nfrom chuk_mcp.protocol.messages import send_initialize\n\nasync def connect_configured_server():\n    # Load server configuration\n    server_params = await load_config(\"server_config.json\", \"sqlite\")\n    \n    async with stdio_client(server_params) as (read_stream, write_stream):\n        init_result = await send_initialize(read_stream, write_stream)\n        print(f\"Connected to configured server: {init_result.serverInfo.name}\")\n```\n\n## Advanced Features\n\n### \ud83c\udfaf Intelligent Sampling\n\nLet servers request AI to generate content on their behalf (with user approval):\n\n```python\nfrom chuk_mcp.protocol.messages.sampling import (\n    send_sampling_create_message, \n    create_sampling_message\n)\n\nasync def ai_content_generation(read_stream, write_stream):\n    # Server can request AI to generate content\n    messages = [\n        create_sampling_message(\"user\", \"Explain quantum computing in simple terms\")\n    ]\n    \n    result = await send_sampling_create_message(\n        read_stream, write_stream,\n        messages=messages,\n        max_tokens=1000,\n        temperature=0.7\n    )\n    \n    print(f\"\ud83e\udd16 AI Generated: {result['content']['text']}\")\n```\n\n### \ud83c\udfaf Argument Completion\n\nProvide intelligent autocompletion for tool arguments:\n\n```python\nfrom chuk_mcp.protocol.messages.completion import (\n    send_completion_complete, \n    create_resource_reference, \n    create_argument_info\n)\n\nasync def smart_completion(read_stream, write_stream):\n    # Get completion suggestions for a resource argument\n    response = await send_completion_complete(\n        read_stream, write_stream,\n        ref=create_resource_reference(\"file:///project/data/\"),\n        argument=create_argument_info(\"filename\", \"sales_202\")\n    )\n    \n    completions = response.get(\"completion\", {}).get(\"values\", [])\n    print(f\"\ud83d\udca1 Suggestions: {completions}\")\n```\n\n### \ud83d\udd04 Multi-Server Orchestration\n\nConnect to multiple servers simultaneously:\n\n```python\nfrom chuk_mcp.mcp_client.host import run_command\nfrom chuk_mcp.protocol.messages import send_tools_list\n\nasync def multi_server_task(server_streams):\n    \"\"\"Process data using multiple MCP servers.\"\"\"\n    \n    # server_streams contains connections to all configured servers\n    for i, (read_stream, write_stream) in enumerate(server_streams):\n        print(f\"Processing with server {i+1}\")\n        \n        # Each server can have different capabilities\n        tools = await send_tools_list(read_stream, write_stream)\n        print(f\"  Available tools: {len(tools.get('tools', []))}\")\n\n# Run across multiple servers defined in config\nrun_command(multi_server_task, \"server_config.json\", [\"sqlite\", \"filesystem\", \"github\"])\n```\n\n### \ud83d\udce1 Real-time Subscriptions\n\nSubscribe to resource changes for live updates:\n\n```python\nfrom chuk_mcp.protocol.messages.resources import send_resources_subscribe\n\nasync def live_monitoring(read_stream, write_stream):\n    # Subscribe to file changes\n    success = await send_resources_subscribe(\n        read_stream, write_stream,\n        uri=\"file:///project/logs/app.log\"\n    )\n    \n    if success:\n        print(\"\ud83d\udce1 Subscribed to log file changes\")\n        \n        # Handle notifications in your message loop\n        # (implementation depends on your notification handling)\n```\n\n## Error Handling & Resilience\n\n`chuk-mcp` provides robust error handling with automatic retries:\n\n```python\nfrom chuk_mcp.protocol.messages import RetryableError, NonRetryableError\nfrom chuk_mcp.protocol.messages import send_tools_call\n\nasync def resilient_operations(read_stream, write_stream):\n    try:\n        # Operations automatically retry on transient failures\n        result = await send_tools_call(\n            read_stream, write_stream,\n            name=\"network_operation\",\n            arguments={\"url\": \"https://api.example.com/data\"},\n            timeout=30.0,  # Extended timeout for slow operations\n            retries=5      # More retries for critical operations\n        )\n        \n    except RetryableError as e:\n        print(f\"\u26a0\ufe0f Transient error after retries: {e}\")\n        # Handle gracefully - maybe try alternative approach\n        \n    except NonRetryableError as e:\n        print(f\"\u274c Permanent error: {e}\")\n        # Handle definitively - operation cannot succeed\n        \n    except Exception as e:\n        print(f\"\ud83d\udea8 Unexpected error: {e}\")\n        # Handle unknown errors\n```\n\n## Available MCP Servers\n\nThe MCP ecosystem includes servers for popular services:\n\n### \ud83d\ude80 Install with UV (Recommended)\n\n```bash\n# Popular Python servers\nuv tool install mcp-server-sqlite\nuv tool install mcp-server-github\nuv tool install mcp-server-postgres\n\n# Or run directly without installation\nuv run --with mcp-server-sqlite mcp-server-sqlite --db-path data.db\n```\n\n### \ud83d\udfe2 Node.js Servers\n\n```bash\n# Use npx for Node.js servers\nnpx -y @modelcontextprotocol/server-filesystem /path/to/files\nnpx -y @modelcontextprotocol/server-brave-search\n```\n\n### \ud83d\udcc1 Available Servers\n\n- **\ud83d\udcc1 Filesystem**: `@modelcontextprotocol/server-filesystem` \n- **\ud83d\uddc4\ufe0f SQLite**: `mcp-server-sqlite` \n- **\ud83d\udc19 GitHub**: `mcp-server-github`\n- **\u2601\ufe0f Google Drive**: `mcp-server-gdrive`\n- **\ud83d\udd0d Web Search**: `mcp-server-brave-search`\n- **\ud83d\udcca PostgreSQL**: `mcp-server-postgres`\n- **\ud83d\udcc8 Analytics**: Various data analytics servers\n- **\ud83d\udd27 Custom**: Build your own with the MCP SDK\n\nFind more at: [MCP Servers Directory](https://github.com/modelcontextprotocol/servers)\n\n## Building MCP Servers\n\nWant to create your own MCP server? Check out:\n\n- **Python**: [`mcp` package](https://pypi.org/project/mcp/)\n- **TypeScript**: [`@modelcontextprotocol/sdk`](https://www.npmjs.com/package/@modelcontextprotocol/sdk)\n- **Specification**: [MCP Protocol Documentation](https://spec.modelcontextprotocol.io/)\n\n## Development\n\n### Setup with UV\n\n```bash\ngit clone https://github.com/chrishayuk/chuk-mcp\ncd chuk-mcp\n\n# Install with development dependencies\nuv sync\n\n# Activate the virtual environment\nsource .venv/bin/activate  # Linux/Mac\n# or .venv\\Scripts\\activate  # Windows\n```\n\n### Traditional Setup\n\n```bash\n# Alternative setup with pip\npip install -e \".[dev]\"\n```\n\n### Testing & Validation\n\n```bash\n# Quick validation\nuv run examples/quickstart.py\n\n# Run comprehensive tests\nuv run examples/e2e_smoke_test_example.py --demo all\n\n# Validate installation scenarios\nuv run diagnostics/installation_scenarios_diagnostic.py\n\n# Test specific functionality\nuv run examples/e2e_smoke_test_example.py --smoke\n\n# Performance benchmarks\nuv run examples/e2e_smoke_test_example.py --performance\n```\n\n### Development Features\n\n```bash\n# Test with fallback validation\nUV_MCP_FORCE_FALLBACK=1 uv run examples/quickstart.py\n\n# Test with different Python versions\nuv run --python 3.11 examples/quickstart.py\nuv run --python 3.12 examples/quickstart.py\n```\n\n### Contributing\n\n1. Fork the repository\n2. Create a feature branch\n3. Add tests for your changes\n4. Ensure all tests pass with `uv run diagnostics/installation_scenarios_diagnostic.py`\n5. Submit a pull request\n\n## Performance & Monitoring\n\n`chuk-mcp` includes built-in performance monitoring:\n\n```python\nimport logging\n\n# Enable detailed logging for debugging\nlogging.basicConfig(level=logging.DEBUG)\n\n# Performance is optimized for:\n# - Concurrent server connections\n# - Efficient message routing  \n# - Minimal memory allocation\n# - Fast JSON serialization\n```\n\n**Performance Highlights:**\n- **\ud83d\ude80 Fast Startup**: < 1 second connection time\n- **\u26a1 High Throughput**: 50+ requests/second per connection\n- **\ud83d\udd04 Concurrent Operations**: Full async/await support\n- **\ud83d\udcbe Memory Efficient**: Minimal overhead per connection\n\n## Intelligent Dependency Management\n\n`chuk-mcp` includes intelligent dependency handling with graceful fallbacks:\n\n```python\n# Check validation backend\nfrom chuk_mcp.protocol.mcp_pydantic_base import PYDANTIC_AVAILABLE\n\nif PYDANTIC_AVAILABLE:\n    print(\"\u2705 Using Pydantic for enhanced validation\")\n    print(\"   \u2022 Better error messages\")\n    print(\"   \u2022 Faster validation (Rust-based)\")\n    print(\"   \u2022 Advanced type coercion\")\nelse:\n    print(\"\ud83d\udce6 Using lightweight fallback validation\")\n    print(\"   \u2022 Pure Python implementation\")\n    print(\"   \u2022 No external dependencies\")\n    print(\"   \u2022 ~20x slower but still fast\")\n\n# Force fallback mode for testing\nimport os\nos.environ[\"MCP_FORCE_FALLBACK\"] = \"1\"\n```\n\n### Installation Performance Matrix\n\n| Installation | Startup Time | Validation Speed | Memory Usage | Dependencies |\n|-------------|-------------|------------------|--------------|--------------|\n| `chuk-mcp` | < 0.5s | 0.010ms/op | 15MB | Core only |\n| `chuk-mcp[pydantic]` | < 1.0s | 0.000ms/op | 25MB | + Pydantic |\n| `chuk-mcp[full]` | < 1.5s | 0.000ms/op | 35MB | All features |\n\n## UV Integration Features\n\n### Project Templates\n\n```bash\n# Start a new MCP client project\nuv init my-mcp-client\ncd my-mcp-client\n\n# Add chuk-mcp with dependencies\nuv add chuk-mcp[pydantic]\n\n# Add development tools\nuv add --dev pytest black isort\n\n# Create example\ncat > main.py << 'EOF'\nimport anyio\nfrom chuk_mcp import stdio_client, StdioServerParameters\n\nasync def main():\n    # Your MCP client code here\n    pass\n\nif __name__ == \"__main__\":\n    anyio.run(main)\nEOF\n```\n\n### UV Scripts\n\nAdd to your `pyproject.toml`:\n\n```toml\n[tool.uv]\ndev-dependencies = [\n    \"chuk-mcp[dev]\",\n]\n\n[project.scripts]\nmcp-client = \"my_mcp_client:main\"\n\n[tool.uv.scripts]\ntest-mcp = \"uv run examples/quickstart.py\"\nvalidate = \"uv run diagnostics/installation_scenarios_diagnostic.py\"\n```\n\n## Support & Community\n\n- **\ud83d\udcd6 Documentation**: [Full API Documentation](https://docs.example.com)\n- **\ud83d\udc1b Issues**: [GitHub Issues](https://github.com/chrishayuk/chuk-mcp/issues)\n- **\ud83d\udcac Discussions**: [GitHub Discussions](https://github.com/chrishayuk/chuk-mcp/discussions)\n- **\ud83d\udce7 Email**: For private inquiries\n- **\ud83d\ude80 UV**: [UV Package Manager](https://github.com/astral-sh/uv)\n\n## License\n\nMIT License - see [LICENSE](LICENSE) file for details.\n\n## Acknowledgments\n\n- Built on the [Model Context Protocol](https://modelcontextprotocol.io/) specification\n- Inspired by the official [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk)\n- Thanks to the MCP community for feedback and contributions\n- Special thanks to the [UV](https://github.com/astral-sh/uv) team for making Python package management fast and reliable\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Model Context Protocol Client with Optional Pydantic Support",
    "version": "0.5",
    "project_urls": {
        "Bug Tracker": "https://github.com/chrishayuk/chuk-mcp/issues",
        "Homepage": "https://github.com/chrishayuk/chuk-mcp",
        "Repository": "https://github.com/chrishayuk/chuk-mcp"
    },
    "split_keywords": [
        "llm",
        " openai",
        " claude",
        " mcp",
        " client",
        " protocol"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "a4cde4028df4beed868969e63009fa0496b28ecbf89e206446755abf9a6ef549",
                "md5": "aa0c047522ec4e11f6f663e12c0e1639",
                "sha256": "466f1c6f6710127ca165472eea3176fc8cdfd9d020058fddedbdbff5b7cc28c1"
            },
            "downloads": -1,
            "filename": "chuk_mcp-0.5-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "aa0c047522ec4e11f6f663e12c0e1639",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.11",
            "size": 126388,
            "upload_time": "2025-07-10T00:24:48",
            "upload_time_iso_8601": "2025-07-10T00:24:48.830727Z",
            "url": "https://files.pythonhosted.org/packages/a4/cd/e4028df4beed868969e63009fa0496b28ecbf89e206446755abf9a6ef549/chuk_mcp-0.5-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "07ad75c7c980a6a409a95ee179d0e83f0a74b5501e94f861bc5f8e97ef8c9d86",
                "md5": "f012e1fb500401d566aba5c979d51834",
                "sha256": "783f185a5ba43e037c56987ce6b6f852042f8426d1b19adba8e82fb12881cc57"
            },
            "downloads": -1,
            "filename": "chuk_mcp-0.5.tar.gz",
            "has_sig": false,
            "md5_digest": "f012e1fb500401d566aba5c979d51834",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.11",
            "size": 101832,
            "upload_time": "2025-07-10T00:24:50",
            "upload_time_iso_8601": "2025-07-10T00:24:50.162486Z",
            "url": "https://files.pythonhosted.org/packages/07/ad/75c7c980a6a409a95ee179d0e83f0a74b5501e94f861bc5f8e97ef8c9d86/chuk_mcp-0.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-10 00:24:50",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "chrishayuk",
    "github_project": "chuk-mcp",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "chuk-mcp"
}
        
Elapsed time: 0.42918s