# MCP Proxy Adapter

**Author:** Vasiliy Zdanovskiy  
**Email:** vasilyvz@gmail.com

## Overview

MCP Proxy Adapter is a comprehensive framework for building JSON-RPC API servers with built-in security, SSL/TLS support, and proxy registration capabilities. It provides a unified interface for command execution, protocol management, and security enforcement.

## Features

- **JSON-RPC API**: Full JSON-RPC 2.0 support with built-in commands
- **Security Framework**: Integrated authentication, authorization, and SSL/TLS
- **Protocol Management**: HTTP, HTTPS, and mTLS protocol support
- **Proxy Registration**: Automatic registration with proxy servers
- **Command System**: Extensible command registry with built-in commands
- **Configuration Management**: Comprehensive configuration with environment variable overrides

## Quick Start

1. **Installation**:
   ```bash
   pip install mcp-proxy-adapter
   ```

2. **Generate Configuration**:
   ```bash
   # Generate a simple HTTP configuration
   adapter-cfg-gen --protocol http --out config.json
   
   # Generate HTTPS configuration with proxy registration
   adapter-cfg-gen --protocol https --with-proxy --out config.json
   
   # Generate mTLS configuration with custom certificates
   adapter-cfg-gen --protocol mtls \
     --server-cert-file ./certs/server.crt \
     --server-key-file ./certs/server.key \
     --server-ca-cert-file ./certs/ca.crt \
     --out config.json
   ```

3. **Validate Configuration**:
   ```bash
   # Validate configuration file
   adapter-cfg-val --file config.json
   ```

4. **Start Server**:
   ```bash
   # Use the generated configuration
   python -m mcp_proxy_adapter --config config.json
   # Or use the main CLI
   mcp-proxy-adapter config validate --file config.json
   mcp-proxy-adapter server --config config.json
   ```

5. **Access the API**:
   - Health check: `GET http://localhost:8000/health`
   - JSON-RPC: `POST http://localhost:8000/api/jsonrpc`
   - REST API: `POST http://localhost:8000/cmd`
   - Documentation: `http://localhost:8000/docs`

## Configuration

The adapter uses a comprehensive JSON configuration file (`config.json`) that includes all available options. **All features are disabled by default** and must be explicitly enabled. The configuration system has **NO default values** - all configuration must be explicitly specified.

### Configuration Sections

#### 1. `uuid` (Root Level)
**Type**: `string` (UUID4 format)  
**Required**: YES  
**Description**: Unique identifier for the server instance  
**Format**: `xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx`

```json
{
  "uuid": "123e4567-e89b-42d3-a456-426614174000"
}
```

#### 2. `server` Section
**Required**: YES  
**Description**: Core server configuration settings

| Field | Type | Required | Description | Allowed Values |
|-------|------|----------|-------------|----------------|
| `host` | string | YES | Server host address | Any valid IP or hostname |
| `port` | integer | YES | Server port number | 1-65535 |
| `protocol` | string | YES | Server protocol | `"http"`, `"https"`, `"mtls"` |
| `debug` | boolean | YES | Enable debug mode | `true`, `false` |
| `log_level` | string | YES | Logging level | `"DEBUG"`, `"INFO"`, `"WARNING"`, `"ERROR"` |

```json
{
  "server": {
    "host": "0.0.0.0",
    "port": 8080,
    "protocol": "http",
    "debug": false,
    "log_level": "INFO"
  }
}
```

#### 3. `logging` Section
**Required**: YES  
**Description**: Logging configuration settings

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `level` | string | YES | Log level (`"INFO"`, `"DEBUG"`, `"WARNING"`, `"ERROR"`) |
| `log_dir` | string | YES | Directory for log files |
| `log_file` | string | YES | Main log file name |
| `error_log_file` | string | YES | Error log file name |
| `access_log_file` | string | YES | Access log file name |
| `max_file_size` | string/integer | YES | Maximum log file size (`"10MB"` or `10485760`) |
| `backup_count` | integer | YES | Number of backup log files |
| `format` | string | YES | Log message format (Python logging format string) |
| `date_format` | string | YES | Date format for logs |
| `console_output` | boolean | YES | Enable console logging |
| `file_output` | boolean | YES | Enable file logging |

```json
{
  "logging": {
    "level": "INFO",
    "log_dir": "./logs",
    "log_file": "mcp_proxy_adapter.log",
    "error_log_file": "mcp_proxy_adapter_error.log",
    "access_log_file": "mcp_proxy_adapter_access.log",
    "max_file_size": "10MB",
    "backup_count": 5,
    "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    "date_format": "%Y-%m-%d %H:%M:%S",
    "console_output": true,
    "file_output": true
  }
}
```

#### 4. `commands` Section
**Required**: YES  
**Description**: Command management configuration

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `auto_discovery` | boolean | YES | Enable automatic command discovery |
| `commands_directory` | string | YES | Directory for command files |
| `catalog_directory` | string | YES | Directory for command catalog |
| `plugin_servers` | array | YES | List of plugin server URLs |
| `auto_install_dependencies` | boolean | YES | Auto-install command dependencies |
| `enabled_commands` | array | YES | List of enabled commands |
| `disabled_commands` | array | YES | List of disabled commands |
| `custom_commands_path` | string | YES | Path to custom commands |

```json
{
  "commands": {
    "auto_discovery": true,
    "commands_directory": "./commands",
    "catalog_directory": "./catalog",
    "plugin_servers": [],
    "auto_install_dependencies": true,
    "enabled_commands": ["health", "echo", "help"],
    "disabled_commands": [],
    "custom_commands_path": "./commands"
  }
}
```

#### 5. `transport` Section
**Required**: YES  
**Description**: Transport layer configuration

| Field | Type | Required | Description | Allowed Values |
|-------|------|----------|-------------|----------------|
| `type` | string | YES | Transport type | `"http"`, `"https"`, `"mtls"` |
| `port` | integer/null | YES | Transport port (can be null) | 1-65535 or `null` |
| `verify_client` | boolean | YES | Enable client certificate verification | `true`, `false` |
| `chk_hostname` | boolean | YES | Enable hostname checking | `true`, `false` |

**Nested Section**: `transport.ssl` (when SSL/TLS is enabled)

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `enabled` | boolean | Conditional | Enable SSL/TLS |
| `cert_file` | string | Conditional | Path to SSL certificate file |
| `key_file` | string | Conditional | Path to SSL private key file |
| `ca_cert` | string | Optional | Path to CA certificate file |
| `verify_client` | boolean | Optional | Verify client certificates |
| `verify_ssl` | boolean | Optional | Verify SSL certificates |
| `verify_hostname` | boolean | Optional | Verify hostname in certificate |
| `verify_mode` | string | Optional | SSL verification mode: `"CERT_NONE"`, `"CERT_OPTIONAL"`, `"CERT_REQUIRED"` |

```json
{
  "transport": {
    "type": "https",
    "port": 8443,
    "verify_client": false,
    "chk_hostname": true,
    "ssl": {
      "enabled": true,
      "cert_file": "./certs/server.crt",
      "key_file": "./certs/server.key",
      "ca_cert": "./certs/ca.crt",
      "verify_ssl": true,
      "verify_hostname": true,
      "verify_mode": "CERT_REQUIRED"
    }
  }
}
```

#### 6. `ssl` Section (Root Level)
**Required**: Conditional (required for HTTPS/mTLS protocols)  
**Description**: SSL/TLS configuration for server

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `enabled` | boolean | YES | Enable SSL/TLS |
| `cert_file` | string | YES | Path to SSL certificate file |
| `key_file` | string | YES | Path to SSL private key file |
| `ca_cert` | string | Optional | Path to CA certificate file (required for mTLS) |

```json
{
  "ssl": {
    "enabled": true,
    "cert_file": "./certs/server.crt",
    "key_file": "./certs/server.key",
    "ca_cert": "./certs/ca.crt"
  }
}
```

#### 7. `proxy_registration` Section
**Required**: YES  
**Description**: Proxy server registration configuration

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `enabled` | boolean | YES | Enable proxy registration |
| `proxy_url` | string | YES | Proxy server URL |
| `server_id` | string | YES | Unique server identifier |
| `server_name` | string | YES | Human-readable server name |
| `description` | string | YES | Server description |
| `version` | string | YES | Server version |
| `protocol` | string | Conditional | Registration protocol: `"http"`, `"https"`, `"mtls"` |
| `registration_timeout` | integer | YES | Registration timeout in seconds |
| `retry_attempts` | integer | YES | Number of retry attempts |
| `retry_delay` | integer | YES | Delay between retries in seconds |
| `auto_register_on_startup` | boolean | YES | Auto-register on startup |
| `auto_unregister_on_shutdown` | boolean | YES | Auto-unregister on shutdown |
| `uuid` | string | Optional | UUID for registration (UUID4 format) |

**Nested Section**: `proxy_registration.ssl` (when using HTTPS/mTLS)

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `enabled` | boolean | Conditional | Enable SSL for registration |
| `verify_ssl` | boolean | Conditional | Verify proxy SSL certificate |
| `verify_hostname` | boolean | Conditional | Verify proxy hostname |
| `verify_mode` | string | Conditional | SSL verification mode |
| `ca_cert` | string | Conditional | Path to CA certificate |
| `cert_file` | string | Conditional | Path to client certificate (for mTLS) |
| `key_file` | string | Conditional | Path to client key (for mTLS) |

**Nested Section**: `proxy_registration.heartbeat`

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `enabled` | boolean | Optional | Enable heartbeat |
| `interval` | integer | Optional | Heartbeat interval in seconds |
| `timeout` | integer | Optional | Heartbeat timeout in seconds |
| `retry_attempts` | integer | Optional | Number of retry attempts |
| `retry_delay` | integer | Optional | Delay between retries |
| `url` | string | Optional | Heartbeat endpoint URL |

```json
{
  "proxy_registration": {
    "enabled": true,
    "proxy_url": "https://proxy.example.com:3005",
    "server_id": "my-server-001",
    "server_name": "My MCP Server",
    "description": "Production MCP server",
    "version": "1.0.0",
    "protocol": "mtls",
    "registration_timeout": 30,
    "retry_attempts": 3,
    "retry_delay": 5,
    "auto_register_on_startup": true,
    "auto_unregister_on_shutdown": true,
    "ssl": {
      "enabled": true,
      "verify_ssl": true,
      "verify_hostname": false,
      "verify_mode": "CERT_REQUIRED",
      "ca_cert": "./certs/ca.crt",
      "cert_file": "./certs/client.crt",
      "key_file": "./certs/client.key"
    },
    "heartbeat": {
      "enabled": true,
      "interval": 30,
      "timeout": 10,
      "retry_attempts": 3,
      "retry_delay": 5,
      "url": "/heartbeat"
    }
  }
}
```

#### 8. `security` Section
**Required**: YES  
**Description**: Security framework configuration

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `enabled` | boolean | YES | Enable security framework |
| `tokens` | object | YES | Token-based authentication configuration |
| `roles` | object | YES | Role-based access control configuration |
| `roles_file` | string/null | YES | Path to roles configuration file |

**Nested Section**: `security.tokens`

| Field | Type | Description |
|-------|------|-------------|
| `admin` | string | Administrator token |
| `user` | string | User token |
| `readonly` | string | Read-only token |
| *(custom)* | string | Custom token names |

**Nested Section**: `security.roles`

| Field | Type | Description |
|-------|------|-------------|
| `admin` | array | Administrator role permissions |
| `user` | array | User role permissions |
| `readonly` | array | Read-only role permissions |
| *(custom)* | array | Custom role names |

```json
{
  "security": {
    "enabled": true,
    "tokens": {
      "admin": "admin-secret-key",
      "user": "user-secret-key",
      "readonly": "readonly-secret-key"
    },
    "roles": {
      "admin": ["*"],
      "user": ["health", "echo"],
      "readonly": ["health"]
    },
    "roles_file": null
  }
}
```

#### 9. `roles` Section
**Required**: YES  
**Description**: Role-based access control configuration

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `enabled` | boolean | YES | Enable RBAC |
| `config_file` | string/null | YES | Path to roles configuration file |
| `default_policy` | object | YES | Default policy settings |
| `auto_load` | boolean | YES | Auto-load roles on startup |
| `validation_enabled` | boolean | YES | Enable role validation |

**Nested Section**: `roles.default_policy`

| Field | Type | Description |
|-------|------|-------------|
| `deny_by_default` | boolean | Deny access by default |
| `require_role_match` | boolean | Require exact role match |
| `case_sensitive` | boolean | Case-sensitive role matching |
| `allow_wildcard` | boolean | Allow wildcard permissions |

```json
{
  "roles": {
    "enabled": false,
    "config_file": null,
    "default_policy": {
      "deny_by_default": true,
      "require_role_match": true,
      "case_sensitive": false,
      "allow_wildcard": true
    },
    "auto_load": true,
    "validation_enabled": true
  }
}
```

#### 10. `debug` Section
**Required**: YES  
**Description**: Debug mode configuration

| Field | Type | Required | Description | Allowed Values |
|-------|------|----------|-------------|----------------|
| `enabled` | boolean | YES | Enable debug mode | `true`, `false` |
| `level` | string | YES | Debug level | `"DEBUG"`, `"INFO"`, `"WARNING"`, `"ERROR"` |

```json
{
  "debug": {
    "enabled": false,
    "level": "WARNING"
  }
}
```

### Protocol-Specific Requirements

#### HTTP Protocol
**Required Sections**: `server`, `logging`, `commands`, `transport`, `debug`, `security`, `roles`  
**SSL Required**: NO  
**Client Verification**: NO

#### HTTPS Protocol
**Required Sections**: All sections + `ssl`  
**SSL Required**: YES  
**Client Verification**: NO  
**Required Files**: 
- `ssl.cert_file` - Server certificate
- `ssl.key_file` - Server private key

#### mTLS Protocol
**Required Sections**: All sections + `ssl`  
**SSL Required**: YES  
**Client Verification**: YES  
**Required Files**: 
- `ssl.cert_file` - Server certificate
- `ssl.key_file` - Server private key
- `ssl.ca_cert` - CA certificate for client verification

### Configuration Validation

The framework automatically validates configuration on load:
- **Required sections**: All mandatory configuration sections are present
- **Required keys**: All required keys within sections are present
- **Type validation**: All values have correct data types
- **File existence**: All referenced files exist (when features are enabled)
- **Feature dependencies**: All feature dependencies are satisfied
- **UUID format**: UUID4 format validation
- **Certificate validation**: Certificate format, expiration, key matching

### Complete Configuration Example

```json
{
  "uuid": "123e4567-e89b-42d3-a456-426614174000",
  "server": {
    "host": "0.0.0.0",
    "port": 8080,
    "protocol": "mtls",
    "debug": false,
    "log_level": "INFO"
  },
  "logging": {
    "level": "INFO",
    "log_dir": "./logs",
    "log_file": "mcp_proxy_adapter.log",
    "error_log_file": "mcp_proxy_adapter_error.log",
    "access_log_file": "mcp_proxy_adapter_access.log",
    "max_file_size": "10MB",
    "backup_count": 5,
    "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    "date_format": "%Y-%m-%d %H:%M:%S",
    "console_output": true,
    "file_output": true
  },
  "commands": {
    "auto_discovery": true,
    "commands_directory": "./commands",
    "catalog_directory": "./catalog",
    "plugin_servers": [],
    "auto_install_dependencies": true,
    "enabled_commands": ["health", "echo", "help"],
    "disabled_commands": [],
    "custom_commands_path": "./commands"
  },
  "transport": {
    "type": "mtls",
    "port": 8443,
    "verify_client": true,
    "chk_hostname": true,
    "ssl": {
      "enabled": true,
      "cert_file": "./certs/server.crt",
      "key_file": "./certs/server.key",
      "ca_cert": "./certs/ca.crt",
      "verify_ssl": true,
      "verify_hostname": true,
      "verify_mode": "CERT_REQUIRED"
    }
  },
  "ssl": {
    "enabled": true,
    "cert_file": "./certs/server.crt",
    "key_file": "./certs/server.key",
    "ca_cert": "./certs/ca.crt"
  },
  "proxy_registration": {
    "enabled": true,
    "proxy_url": "https://proxy.example.com:3005",
    "server_id": "my-server-001",
    "server_name": "My MCP Server",
    "description": "Production MCP server",
    "version": "1.0.0",
    "protocol": "mtls",
    "registration_timeout": 30,
    "retry_attempts": 3,
    "retry_delay": 5,
    "auto_register_on_startup": true,
    "auto_unregister_on_shutdown": true,
    "ssl": {
      "enabled": true,
      "verify_ssl": true,
      "verify_hostname": false,
      "verify_mode": "CERT_REQUIRED",
      "ca_cert": "./certs/ca.crt",
      "cert_file": "./certs/client.crt",
      "key_file": "./certs/client.key"
    },
    "heartbeat": {
      "enabled": true,
      "interval": 30,
      "timeout": 10,
      "retry_attempts": 3,
      "retry_delay": 5,
      "url": "/heartbeat"
    }
  },
  "debug": {
    "enabled": false,
    "level": "WARNING"
  },
  "security": {
    "enabled": true,
    "tokens": {
      "admin": "admin-secret-key",
      "user": "user-secret-key",
      "readonly": "readonly-secret-key"
    },
    "roles": {
      "admin": ["*"],
      "user": ["health", "echo"],
      "readonly": ["health"]
    },
    "roles_file": null
  },
  "roles": {
    "enabled": false,
    "config_file": null,
    "default_policy": {
      "deny_by_default": true,
      "require_role_match": true,
      "case_sensitive": false,
      "allow_wildcard": true
    },
    "auto_load": true,
    "validation_enabled": true
  }
}
```

For more detailed configuration documentation, see `docs/EN/ALL_CONFIG_SETTINGS.md`.

## Built-in Commands

- `health` - Server health check
- `echo` - Echo test command
- `config` - Configuration management
- `help` - Command help and documentation
- `reload` - Configuration reload
- `settings` - Settings management
- `load`/`unload` - Command loading/unloading
- `plugins` - Plugin management
- `proxy_registration` - Proxy registration control
- `transport_management` - Transport protocol management
- `role_test` - Role-based access testing

## Security Features

- **Authentication**: API keys, JWT tokens, certificate-based auth
- **Authorization**: Role-based permissions with wildcard support
- **SSL/TLS**: Full SSL/TLS and mTLS support
- **Rate Limiting**: Configurable request rate limiting
- **Security Headers**: Automatic security header injection

## Examples

The `mcp_proxy_adapter/examples/` directory contains comprehensive examples for different use cases:

- **Basic Framework**: Simple HTTP server setup
- **Full Application**: Complete application with custom commands and hooks
- **Security Testing**: Comprehensive security test suite
- **Certificate Generation**: SSL/TLS certificate management

### Test Environment Setup

The framework includes a comprehensive test environment setup that automatically creates configurations, generates certificates, and runs tests:

```bash
# Create a complete test environment with all configurations and certificates
python -m mcp_proxy_adapter.examples.setup_test_environment

# Create test environment in a specific directory
python -m mcp_proxy_adapter.examples.setup_test_environment /path/to/test/dir

# Skip certificate generation (use existing certificates)
python -m mcp_proxy_adapter.examples.setup_test_environment --skip-certs

# Skip running tests (setup only)
python -m mcp_proxy_adapter.examples.setup_test_environment --skip-tests
```

### Configuration Generation

Generate test configurations from a comprehensive template:

```bash
# Generate all test configurations
python -m mcp_proxy_adapter.examples.create_test_configs

# Generate from specific comprehensive config
python -m mcp_proxy_adapter.examples.create_test_configs --comprehensive-config config.json

# Generate specific configuration types
python -m mcp_proxy_adapter.examples.create_test_configs --types http,https,mtls
```

### Certificate Generation

Generate SSL/TLS certificates for testing:

```bash
# Generate all certificates using mcp_security_framework
python -m mcp_proxy_adapter.examples.generate_all_certificates

# Generate certificates with custom configuration
python -m mcp_proxy_adapter.examples.generate_certificates_framework --config cert_config.json
```

### Security Testing

Run comprehensive security tests:

```bash
# Run all security tests
python -m mcp_proxy_adapter.examples.run_security_tests_fixed

# Run full test suite (includes setup, config generation, certificate generation, and testing)
python -m mcp_proxy_adapter.examples.run_full_test_suite
```

### Complete Workflow Example

```bash
# 1. Install the package
pip install mcp-proxy-adapter

# 2. Create test environment (automatically runs tests)
python -m mcp_proxy_adapter.examples.setup_test_environment

# 3. Or run individual steps:
# Generate certificates
python -m mcp_proxy_adapter.examples.generate_all_certificates

# Generate configurations
python -m mcp_proxy_adapter.examples.create_test_configs

# Run security tests
python -m mcp_proxy_adapter.examples.run_security_tests_fixed

# 4. Start server with generated configuration
python -m mcp_proxy_adapter --config configs/http_simple.json
```

## Development

The project follows a modular architecture:

- `mcp_proxy_adapter/api/` - FastAPI application and handlers
- `mcp_proxy_adapter/commands/` - Command system and built-in commands
- `mcp_proxy_adapter/core/` - Core functionality and utilities
- `mcp_proxy_adapter/config.py` - Configuration management

## License

This project is licensed under the MIT License.

## Support

For issues and questions, please contact vasilyvz@gmail.com.
