# MCP Client

**Auto-invoke:** When user needs to integrate external tools, APIs, or services via the Model Context Protocol.

**Description:**
MCP (Model Context Protocol) client for dynamic tool discovery and integration. Supports 100+ pre-built integrations through standardized protocol communication.

## Core Capabilities

### 1. MCP Server Connection
- Connect to MCP servers via stdio, HTTP, or WebSocket
- Handshake and protocol negotiation
- Tool discovery and listing
- Capability exchange

### 2. Dynamic Tool Invocation
- Call tools on connected MCP servers
- Pass structured arguments
- Receive structured results
- Handle streaming responses

### 3. Tool Management
- Register/unregister servers
- Cache tool definitions
- Monitor server health
- Auto-reconnect on failure

## MCP Servers to Support

### Official MCP Servers
```yaml
@modelcontextprotocol/server-filesystem:
  description: "File system operations"
  tools: [read_file, write_file, list_directory, search_files]

@modelcontextprotocol/server-github:
  description: "GitHub integration"
  tools: [create_issue, list_prs, get_file, search_repos]

@modelcontextprotocol/server-slack:
  description: "Slack messaging"
  tools: [send_message, list_channels, get_history]

@modelcontextprotocol/server-postgres:
  description: "PostgreSQL database"
  tools: [query, list_tables, execute_sql]

@modelcontextprotocol/server-brave-search:
  description: "Web search"
  tools: [search, fetch_page]
```

### Community Servers
```yaml
@agent-protocol/server-memory:
  description: "Persistent memory storage"
  tools: [store, retrieve, search, clear]

@agent-protocol/server-code-analysis:
  description: "Static code analysis"
  tools: [analyze complexity, find patterns, detect smells]
```

## When to Use

Activate when:
- User needs to integrate external services
- User requests API integrations
- User needs database access
- User wants web search/data fetching
- User needs file operations beyond current directory

## Configuration

### MCP Servers Config
```yaml
# ~/.claude/mcp/servers.yaml
servers:
  filesystem:
    command: npx
    args: ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"]
    
  github:
    command: npx
    args: ["-y", "@modelcontextprotocol/server-github"]
    env:
      GITHUB_TOKEN: "${GITHUB_TOKEN}"
      
  postgres:
    command: python
    args: ["-m", "mcp_server_postgres"]
    env:
      POSTGRES_CONNECTION_STRING: "${DATABASE_URL}"
```

### Dynamic Server Discovery
```yaml
# ~/.claude/mcp/registry.yaml
registry:
  - name: filesystem
    npm: "@modelcontextprotocol/server-filesystem"
    auto_install: true
    
  - name: github
    npm: "@modelcontextprotocol/server-github"
    env_required: ["GITHUB_TOKEN"]
```

## Usage Patterns

### Pattern 1: Direct Tool Call
```python
# Call tool on MCP server
result = await mcp_client.call_tool(
    server_name="github",
    tool_name="create_issue",
    arguments={
        "repo": "owner/repo",
        "title": "Bug found",
        "body": "Description"
    }
)
```

### Pattern 2: Tool Discovery
```python
# List available tools
tools = await mcp_client.list_tools("github")
# Returns: [
#   {"name": "create_issue", "description": "..."},
#   {"name": "list_prs", "description": "..."}
# ]
```

### Pattern 3: Server Management
```python
# Connect to server
await mcp_client.connect("filesystem")

# Check health
health = await mcp_client.health_check("filesystem")

# Disconnect
await mcp_client.disconnect("filesystem")
```

## Integration with Claude Code

### Hook Integration
```bash
# ~/.claude/hooks/mcp-loader.sh
# Load MCP servers on session start

python3 << 'PYTHON'
import asyncio
from claude_mcp import Client

async def load_servers():
    client = Client()
    await client.load_from_config("~/.claude/mcp/servers.yaml")
    return client.list_tools()

tools = asyncio.run(load_servers())
print(f"Loaded {len(tools)} MCP tools")
PYTHON
```

### Skill Integration
```python
# Auto-inject MCP tools into available tools
mcp_tools = mcp_client.get_all_tools()
available_tools.extend(mcp_tools)
```

## Commands to Create

```bash
# List MCP servers
~/.claude/mcp/list-servers.sh

# Connect to server
~/.claude/mcp/connect.sh <server-name>

# Call tool
~/.claude/mcp/call.sh <server> <tool> <args-json>

# Disconnect server
~/.claude/mcp/disconnect.sh <server-name>

# Show server logs
~/.claude/mcp/logs.sh <server-name>
```

## Tool Schema

Each MCP tool provides:
```json
{
  "name": "tool_name",
  "description": "What this tool does",
  "inputSchema": {
    "type": "object",
    "properties": {
      "param1": {"type": "string", "description": "..."}
    },
    "required": ["param1"]
  }
}
```

## Error Handling

### Connection Failures
- Retry with exponential backoff
- Fall back to cached tool definitions
- Notify user of unavailable tools

### Tool Execution Errors
- Parse error messages from server
- Suggest fixes based on error type
- Offer retry with corrected arguments

### Protocol Mismatches
- Log protocol version mismatches
- Attempt to negotiate compatible version
- Warn user of degraded functionality

## Security

### Sandboxing
- Run servers in separate processes
- Restrict file system access
- Isolate environment variables

### Credential Management
- Load credentials from env vars
- Never log sensitive data
- Rotate tokens automatically

### Permission Checks
- Verify tool permissions before call
- Require user approval for dangerous ops
- Audit all tool invocations

## Performance

### Connection Pooling
- Reuse server connections
- Keep idle connections alive
- Limit concurrent connections

### Caching
- Cache tool definitions
- Cache server capabilities
- Invalidate on server restart

### Monitoring
- Track tool call latency
- Monitor server health
- Alert on degradation

## Example Interactions

### Example 1: GitHub Integration
```
User: "Create a GitHub issue for this bug"

[Connect to github MCP server]
[Tool: create_issue]
Arguments: {
  repo: "owner/repo",
  title: "Bug in authentication",
  body: "Steps to reproduce..."
}

Result: Issue #123 created
URL: https://github.com/owner/repo/issues/123
```

### Example 2: Database Query
```
User: "Show me all users created today"

[Connect to postgres MCP server]
[Tool: execute_sql]
Arguments: {
  query: "SELECT * FROM users WHERE created_at > CURRENT_DATE"
}

Result: [
  {id: 1, name: "Alice", email: "alice@example.com"},
  {id: 2, name: "Bob", email: "bob@example.com"}
]
```

### Example 3: Web Search
```
User: "Search for recent Claude Code updates"

[Connect to brave-search MCP server]
[Tool: search]
Arguments: {
  query: "Claude Code CLI latest features"
}

Result: [
  {
    title: "Claude Code 2.0 Released",
    url: "https://...",
    snippet: "..."
  }
]
```

## Troubleshooting

### Server Won't Start
```bash
# Check server logs
~/.claude/mcp/logs.sh <server-name>

# Verify installation
which <server-command>

# Test manually
<server-command> --version
```

### Tool Not Found
```bash
# List available tools
~/.claude/mcp/list-tools.sh <server-name>

# Refresh tool cache
~/.claude/mcp/refresh.sh
```

### Connection Timeout
```bash
# Increase timeout
export MCP_TIMEOUT=30

# Check network
ping <server-host>

# Verify credentials
echo $GITHUB_TOKEN
```

## Dependencies

```bash
# Core MCP client
pip install mcp

# Common servers
npm install -g @modelcontextprotocol/server-filesystem
npm install -g @modelcontextprotocol/server-github
npm install -g @modelcontextprotocol/server-postgres
```

---

**Remember:** MCP unlocks a universe of external tools and integrations while maintaining a clean, standardized interface.
