# MCP (Model Context Protocol) Integration

## Overview

Grok CLI includes comprehensive support for the Model Context Protocol (MCP), allowing seamless integration with MCP servers to extend functionality with external tools, prompts, and resources.

## Architecture

### Core Components

1. **MCP Client** (`src/core/mcp-client.ts`)
   - JSON-RPC 2.0 communication protocol
   - Server connection management
   - Auto-reconnection capabilities
   - Event-driven architecture

2. **MCP Tool Manager** (`src/tools/mcp.ts`)
   - Dynamic tool registration/unregistration
   - Tool wrapping for integration
   - Permission and validation support

3. **MCP Commands** (`src/core/enhanced-commands.ts`)
   - CLI management interface
   - Server status monitoring
   - Tool discovery and testing

## Usage

### Adding MCP Servers

```bash
# Add a GitHub MCP server
/mcp add github "npx @modelcontextprotocol/server-github" "--token=$GITHUB_TOKEN"

# Add a filesystem MCP server
/mcp add filesystem "npx @modelcontextprotocol/server-filesystem" "/path/to/directory"

# Add a custom MCP server
/mcp add myserver "python" "/path/to/server.py"
```

### Managing MCP Servers

```bash
# List all configured servers
/mcp list

# List with detailed information
/mcp list --verbose

# Show status for specific server
/mcp status github

# Connect to a server
/mcp connect github

# Disconnect from a server
/mcp disconnect github

# Remove a server
/mcp remove github
```

### Working with MCP Tools

```bash
# List all available MCP tools
/mcp tools

# Test a specific tool
/mcp test github list_repositories '{"owner": "microsoft"}'

# Test with simple arguments
/mcp test filesystem read_file '{"path": "README.md"}'
```

### Command Reference

| Command | Description | Example |
|---------|-------------|---------|
| `/mcp add <name> <command> [args...]` | Add new MCP server | `/mcp add github "npx @modelcontextprotocol/server-github"` |
| `/mcp list [-v\|--verbose]` | List configured servers | `/mcp list --verbose` |
| `/mcp status [server-name]` | Show server status | `/mcp status github` |
| `/mcp connect <server-name>` | Connect to server | `/mcp connect github` |
| `/mcp disconnect <server-name>` | Disconnect from server | `/mcp disconnect github` |
| `/mcp remove <server-name>` | Remove server | `/mcp remove github` |
| `/mcp tools` | List available tools | `/mcp tools` |
| `/mcp test <server> <tool> [args]` | Test tool execution | `/mcp test github list_repos '{}'` |
| `/mcp help` | Show help and examples | `/mcp help` |

## Integration Features

### Automatic Tool Registration

When an MCP server connects, its tools are automatically:
- Registered in the main tool registry
- Available for use in conversations
- Subject to the same permission system as built-in tools
- Integrated with the hook system

### Tool Naming Convention

MCP tools are prefixed with `mcp_<server>_<tool>` to avoid naming conflicts:
- `mcp_github_list_repositories`
- `mcp_filesystem_read_file`
- `mcp_myserver_custom_tool`

### Event System

The MCP client emits events for:
- Server connections/disconnections
- Tool registration/unregistration
- Errors and status changes

### Error Handling

- Connection failures are handled gracefully
- Auto-reconnection for temporary network issues
- Clear error messages for configuration problems
- Fallback behavior when servers are unavailable

## Configuration

### Server Configuration

MCP servers are configured with:

```typescript
interface McpServerConfig {
  command: string;           // Executable command
  args?: string[];          // Command line arguments
  env?: Record<string, string>; // Environment variables
  cwd?: string;             // Working directory
}
```

### Connection Status

Servers can be in one of these states:
- `connecting` - Establishing connection
- `connected` - Ready for use
- `disconnected` - Not connected
- `error` - Connection failed

## Common MCP Servers

### GitHub Server

```bash
# Install
npm install -g @modelcontextprotocol/server-github

# Add to Grok
/mcp add github "npx @modelcontextprotocol/server-github" "--token=$GITHUB_TOKEN"

# Available tools: list_repositories, get_repository, create_issue, etc.
```

### Filesystem Server

```bash
# Install
npm install -g @modelcontextprotocol/server-filesystem

# Add to Grok
/mcp add filesystem "npx @modelcontextprotocol/server-filesystem" "/allowed/path"

# Available tools: read_file, write_file, list_directory, etc.
```

### SQLite Server

```bash
# Install
npm install -g @modelcontextprotocol/server-sqlite

# Add to Grok
/mcp add sqlite "npx @modelcontextprotocol/server-sqlite" "--db-path=/path/to/database.db"

# Available tools: query, schema, tables, etc.
```

## Development

### Creating Custom MCP Servers

1. **Python Example**:
```python
from mcp.server import Server
from mcp.types import Tool

server = Server("my-server")

@server.tool()
async def my_tool(text: str) -> str:
    return f"Processed: {text}"

if __name__ == "__main__":
    server.run()
```

2. **Add to Grok**:
```bash
/mcp add myserver "python" "/path/to/server.py"
```

### MCP Tool Wrapper

The `McpTool` class wraps MCP server tools:

```typescript
export class McpTool extends BaseTool {
  constructor(
    serverName: string,
    toolName: string, 
    description: string,
    inputSchema: any,
    mcpClient: McpClient
  ) {
    // Tool implementation
  }
  
  async execute(params: Record<string, unknown>): Promise<ToolResult> {
    // Execute tool via MCP client
  }
}
```

## Best Practices

### Security

1. **Token Management**: Store sensitive tokens in environment variables
2. **Path Restrictions**: Limit filesystem access to specific directories
3. **Permission System**: Use Grok's permission modes for MCP tools
4. **Input Validation**: Validate all parameters before sending to MCP servers

### Performance

1. **Connection Pooling**: Reuse existing connections when possible
2. **Timeout Handling**: Set appropriate timeouts for MCP operations
3. **Error Recovery**: Implement graceful fallbacks for server failures
4. **Resource Cleanup**: Properly disconnect when shutting down

### Debugging

1. **Verbose Logging**: Use `/mcp list --verbose` for detailed status
2. **Tool Testing**: Test tools with `/mcp test` before use
3. **Status Monitoring**: Check `/mcp status` for connection issues
4. **Error Messages**: Review detailed error messages for troubleshooting

## Troubleshooting

### Common Issues

1. **Connection Failures**:
   - Check if the MCP server executable is installed
   - Verify command path and arguments
   - Check environment variables and permissions

2. **Tool Not Available**:
   - Ensure server is connected: `/mcp status <server>`
   - Check if tools are listed: `/mcp tools`
   - Try reconnecting: `/mcp disconnect <server>` then `/mcp connect <server>`

3. **Permission Errors**:
   - Verify API tokens and credentials
   - Check file system permissions for filesystem servers
   - Review Grok's permission mode settings

### Debug Commands

```bash
# Check server status
/mcp status

# List all tools with server info
/mcp tools

# Test basic connectivity
/mcp test <server> <simple-tool> '{}'

# View detailed logs
grok --verbose
```

## Integration with Grok Features

### Hook System

MCP tools integrate with Grok's hook system:
- `PreToolUse` - Called before MCP tool execution
- `PostToolUse` - Called after MCP tool execution
- Same JSON I/O interface as built-in tools

### Permission System

MCP tools respect Grok's permission modes:
- `ask` - Prompt user before executing MCP tools
- `plan` - Show what would be executed without running
- `auto` - Auto-approve MCP tool execution
- `full` - No restrictions on MCP tools

### File Reference System

MCP tools can be used with file references:
```bash
# Use filesystem MCP tool with file reference
@package.json # References file, then can use mcp_filesystem_read_file
```

### History and Continuation

MCP tool executions are:
- Logged in conversation history
- Available when continuing sessions
- Tracked with timestamps and results

## Future Enhancements

### Planned Features

1. **MCP Server Discovery**: Automatic discovery of available MCP servers
2. **Configuration Persistence**: Save MCP server configurations across sessions
3. **Tool Categorization**: Group MCP tools by functionality
4. **Performance Metrics**: Track MCP tool execution times and success rates
5. **Batch Operations**: Execute multiple MCP tools in sequence

### Extension Points

1. **Custom Protocols**: Support for protocol extensions
2. **Middleware**: Add custom middleware for MCP communication
3. **Caching**: Cache MCP tool results for performance
4. **Load Balancing**: Distribute requests across multiple server instances

## See Also

- [Model Context Protocol Specification](https://modelcontextprotocol.io)
- [MCP Server Registry](https://github.com/modelcontextprotocol/servers)
- [Grok CLI Hook System](./hooks-system.md)
- [Grok CLI Tool System](./tool-system.md)
- [Grok CLI Permission System](./permission-system.md)