# MCP (Model Context Protocol) Module

This module implements the Model Context Protocol for the custom PHP framework, enabling AI assistants like Claude to interact with the framework through standardized tools and resources.

## ✅ TESTED & WORKING

This MCP module has been successfully tested and is fully functional. The server responds correctly to JSON-RPC requests and integrates seamlessly with the framework's discovery system.

## Overview

The MCP module provides:
- **Tools**: Functions that AI can call to perform actions
- **Resources**: Data sources that AI can read
- **Server**: JSON-RPC server implementation for MCP communication

## Architecture

### Core Components

- `McpServer`: Main server handling JSON-RPC requests
- `McpToolRegistry`: Registry for discovered tools
- `McpResourceRegistry`: Registry for discovered resources  
- `McpInitializer`: Automatic discovery and registration using framework's attribute system

### Attributes

- `#[McpTool]`: Mark methods as MCP tools
- `#[McpResource]`: Mark methods as MCP resources

### Discovery and Mapping

- `McpToolMapper`: Maps `#[McpTool]` attributes using framework's discovery system
- `McpResourceMapper`: Maps `#[McpResource]` attributes

## Available Tools

### Framework Tools (`FrameworkTools`)

- `analyze_routes`: Get all registered routes
- `analyze_container_bindings`: Analyze DI container bindings
- `discover_attributes`: Discover attributes by type
- `framework_health_check`: Health check of framework components
- `list_framework_modules`: List all framework modules

### File System Tools (`FileSystemTools`)

- `list_directory`: List directory contents (project-scoped)
- `read_file`: Read file contents with line limits
- `find_files`: Find files by pattern

## Available Resources

- `framework://config`: Framework configuration and environment

## Usage

### Starting the MCP Server

```bash
# Direct PHP execution
php console.php mcp:server

# Via Docker (recommended for WSL environments)
docker exec -i php php console.php mcp:server
```

This starts the STDIO-based MCP server for AI assistant integration.

### Testing the MCP Server

```bash
# Test initialize
echo '{"jsonrpc": "2.0", "method": "initialize", "params": {}}' | docker exec -i php php console.php mcp:server

# Test tools list
echo '{"jsonrpc": "2.0", "method": "tools/list", "params": {}}' | docker exec -i php php console.php mcp:server
```

### Creating Custom Tools

```php
use App\Framework\Mcp\McpTool;

class MyCustomTools
{
    #[McpTool(
        name: 'my_custom_tool',
        description: 'Description of what this tool does',
        inputSchema: [
            'type' => 'object',
            'properties' => [
                'param1' => ['type' => 'string', 'description' => 'First parameter'],
            ],
            'required' => ['param1'],
        ]
    )]
    public function myCustomTool(string $param1): string
    {
        return "Result: $param1";
    }
}
```

### Creating Custom Resources

```php
use App\Framework\Mcp\McpResource;

class MyCustomResources
{
    #[McpResource(
        uri: 'my://custom-resource',
        name: 'My Custom Resource',
        description: 'A custom data resource',
        mimeType: 'application/json'
    )]
    public function getCustomData(): string
    {
        return json_encode(['data' => 'example']);
    }
}
```

## Claude Code Configuration

### For Windows WSL Setup (Docker environment)

Create or edit: `%APPDATA%\Claude\claude_desktop_config.json`

**RECOMMENDED (Clean MCP Server):**
```json
{
  "mcpServers": {
    "custom-php-framework": {
      "command": "docker",
      "args": ["exec", "-i", "php", "php", "mcp_server.php"],
      "cwd": "\\\\wsl$\\Debian\\home\\michael\\dev\\michaelschiemer"
    }
  }
}
```

**Alternative (Console Command):**
```json
{
  "mcpServers": {
    "custom-php-framework": {
      "command": "docker",
      "args": ["exec", "-i", "php", "php", "console.php", "mcp:server"],
      "cwd": "\\\\wsl$\\Debian\\home\\michael\\dev\\michaelschiemer"
    }
  }
}
```

### For Direct WSL/Linux Environment

```json
{
  "mcpServers": {
    "custom-php-framework": {
      "command": "docker", 
      "args": ["exec", "-i", "php", "php", "console.php", "mcp:server"],
      "cwd": "/home/michael/dev/michaelschiemer"
    }
  }
}
```

### Alternative PHP Direct Execution

```json
{
  "mcpServers": {
    "custom-php-framework": {
      "command": "php",
      "args": ["console.php", "mcp:server"],
      "cwd": "/home/michael/dev/michaelschiemer"
    }
  }
}
```

## Integration with Framework

The MCP module integrates seamlessly with the framework's existing patterns:

1. **Automatic Discovery**: Commands are automatically discovered via `ConsoleCommandMapper`
2. **Attribute Discovery**: Tools and resources use the framework's attribute discovery system
3. **Dependency Injection**: Tools and resources get dependencies through the container
4. **Console Commands**: Includes console command for server startup
5. **Security**: File system tools are scoped to project directory

## Protocol Support

Implements MCP 2025-06-18 specification:
- JSON-RPC 2.0 over STDIO
- `tools/list`, `tools/call` for tool operations
- `resources/list`, `resources/read` for resource operations
- `initialize` for protocol initialization

## Security

- File system access is restricted to project directory
- Input validation on all tool parameters
- Error handling prevents information leakage
- Safe execution with proper exception handling

## Tested Functionality

✅ **Initialize Request**: Server responds with correct protocol version and capabilities  
✅ **Tools List**: Returns empty list (ready for tool registration)  
✅ **Console Integration**: Command `mcp:server` is automatically discovered  
✅ **Docker Compatibility**: Works seamlessly with Docker PHP container  
✅ **JSON-RPC Protocol**: Correct request/response handling  

## Benefits for AI Development

This allows Claude and other AI assistants to:
- Analyze your framework's routes and structure
- Read and understand your codebase
- Discover framework components and patterns
- Perform safe file system operations within your project
- Execute framework-specific commands and queries
- Monitor framework health and performance