# MCP Proxy Architecture

## Overview

This document describes the architecture and structure of the MCP Proxy with OAuth DCR support.

## Project Structure

```
mcp-proxy/
├── src/
│   └── mcp_proxy/
│       ├── __init__.py              # Main package exports
│       ├── models.py                # Core data models (Pydantic)
│       ├── protocols.py             # Protocol interfaces (typing.Protocol)
│       ├── exceptions.py            # Custom exception hierarchy
│       ├── logging_config.py        # Structured logging setup
│       ├── auth/                    # Authentication module
│       │   ├── __init__.py
│       │   └── manager.py           # OAuth DCR implementation (TBD)
│       ├── config/                  # Configuration module
│       │   ├── __init__.py
│       │   └── manager.py           # Config loading/validation (TBD)
│       ├── http/                    # HTTP client module
│       │   ├── __init__.py
│       │   └── client.py            # HTTP MCP client (TBD)
│       ├── stdio/                   # Stdio interface module
│       │   ├── __init__.py
│       │   └── interface.py         # Stdio communication (TBD)
│       └── translator/              # Protocol translator module
│           ├── __init__.py
│           └── translator.py        # Protocol conversion (TBD)
├── tests/
│   ├── __init__.py
│   ├── conftest.py                  # Pytest fixtures
│   └── test_models.py               # Model tests
├── .kiro/
│   └── specs/
│       └── mcp-proxy-oauth-dcr/     # Feature specifications
├── pyproject.toml                   # Project configuration
├── README.md                        # User documentation
├── ARCHITECTURE.md                  # This file
└── .gitignore                       # Git ignore rules
```

## Core Components

### 1. Data Models (`models.py`)

Defines all data structures using Pydantic for validation:

- **JsonRpcMessage**: JSON-RPC 2.0 message structure
- **HttpMcpRequest/Response**: HTTP MCP protocol structures
- **ClientCredentials**: OAuth client credentials
- **OAuthTokenResponse**: OAuth token response
- **AuthenticationState**: Current authentication state
- **SessionState**: MCP session state
- **MessageCorrelation**: Request/response correlation tracking
- **ProxyConfig**: Proxy configuration

### 2. Protocol Interfaces (`protocols.py`)

Defines abstract interfaces using `typing.Protocol`:

- **StdioInterface**: Stdio communication interface
- **ProtocolTranslator**: Protocol translation interface
- **AuthenticationManager**: OAuth DCR and token management interface
- **HttpClient**: HTTP communication interface
- **ConfigurationManager**: Configuration management interface

### 3. Exception Hierarchy (`exceptions.py`)

Custom exceptions for error handling:

- **McpProxyError**: Base exception
  - **ProtocolError**: Protocol translation errors
  - **AuthenticationError**: Authentication errors
  - **NetworkError**: Network and connection errors
  - **ConfigurationError**: Configuration errors

### 4. Logging (`logging_config.py`)

Structured logging using `structlog`:

- Configurable log levels
- JSON output for production
- Console output for development
- Context variable support

## Module Organization

### Authentication Module (`auth/`)

Handles OAuth Dynamic Client Registration and token management:

- DCR protocol implementation (RFC 7591)
- Token acquisition and refresh
- Credential storage and lifecycle
- Authentication state management

### Configuration Module (`config/`)

Manages proxy configuration:

- Environment variable loading
- Configuration file parsing
- Parameter validation
- Default value management

### HTTP Module (`http/`)

HTTP communication with backend MCP servers:

- aiohttp-based async HTTP client
- Server-Sent Events (SSE) support
- Connection pooling and retry logic
- Session management

### Stdio Module (`stdio/`)

Stdio interface for Kiro communication:

- Async stdin/stdout handling
- JSON-RPC message parsing
- Newline-delimited message protocol
- Subprocess lifecycle management

### Translator Module (`translator/`)

Protocol translation between stdio and HTTP:

- Stdio to HTTP conversion
- HTTP to stdio conversion
- Message correlation tracking
- Error translation

## Design Principles

### 1. Separation of Concerns

Each module has a single, well-defined responsibility:

- Models: Data structures only
- Protocols: Interface definitions only
- Implementations: Concrete behavior in separate modules

### 2. Dependency Injection

Components depend on protocol interfaces, not concrete implementations:

```python
class ProxyOrchestrator:
    def __init__(
        self,
        auth_manager: AuthenticationManager,
        http_client: HttpClient,
        translator: ProtocolTranslator,
    ):
        ...
```

### 3. Async/Await

All I/O operations use async/await for concurrency:

- Stdio communication
- HTTP requests
- Token refresh
- Message processing

### 4. Type Safety

Strong typing throughout:

- Pydantic models for runtime validation
- Type hints for static analysis
- Protocol interfaces for structural typing

### 5. Error Handling

Comprehensive error handling:

- Custom exception hierarchy
- Error translation between protocols
- Graceful degradation
- Detailed error messages

## Testing Strategy

### Unit Tests

Test individual components in isolation:

- Model validation
- Protocol translation
- Authentication flows
- Configuration parsing

### Property-Based Tests

Test universal properties using Hypothesis:

- Protocol compliance
- Message correlation
- Token lifecycle
- Configuration validation

### Integration Tests

Test component interactions:

- End-to-end message flow
- Authentication integration
- Error handling
- Connection resilience

## Development Workflow

### 1. Setup

```bash
python3 -m venv venv
source venv/bin/activate  # or venv\Scripts\activate on Windows
pip install -e ".[dev]"
```

### 2. Testing

```bash
# Run all tests
pytest

# Run specific test file
pytest tests/test_models.py

# Run with coverage
pytest --cov=mcp_proxy --cov-report=html
```

### 3. Code Quality

```bash
# Format code
black src tests
isort src tests

# Type checking
mypy src

# Linting
flake8 src tests
```

## Next Steps

The following components need implementation:

1. **Configuration Manager** (Task 2)
2. **JSON-RPC Message Handling** (Task 3)
3. **Stdio Interface** (Task 4)
4. **OAuth DCR Authentication** (Task 6)
5. **HTTP Client** (Task 7)
6. **Protocol Translator** (Task 8)
7. **Main Proxy Orchestration** (Task 11)
8. **CLI Interface** (Task 12)

Each task builds on the foundation established in Task 1.
