# MCP Gateway
A lightweight, security-focused FastAPI gateway for Model Context Protocol (MCP) servers. This gateway acts as an intermediary between MCP clients and servers, providing authentication, authorization, rate limiting, request validation, and audit logging.
## Features
### Security
- **Authentication & Authorization**: Token-based authentication with configurable client policies
- **Request Validation**: Validates requests against allowed tools and resources
- **Response Sanitization**: Removes sensitive information from responses
- **Rate Limiting**: Token bucket algorithm for request rate limiting
- **Audit Logging**: Comprehensive logging of all requests and responses
- **Sandbox Mode**: Isolates MCP server execution (planned enhancement)
### Gateway Functionality
- **Request Proxying**: Forwards validated requests to appropriate MCP servers
- **Policy Enforcement**: Enforces client-specific security policies
- **Error Handling**: Graceful error handling with proper HTTP status codes
- **CORS Support**: Configurable CORS policies for web clients
### Monitoring & Management
- **Health Checks**: Built-in health check endpoint
- **Metrics**: Request metrics and performance monitoring (planned)
- **Admin API**: Client registration and management endpoints
## Quick Start
### Installation
1. Clone or create the project directory:
```bash
mkdir mcpgw && cd mcpgw
```
2. Install dependencies:
```bash
pip install -r requirements.txt
```
3. Run the gateway:
```bash
python main.py
```
The gateway will start on `http://localhost:8000`
### Basic Usage
1. **Health Check**:
```bash
curl http://localhost:8000/health
```
2. **Register a Client** (for testing):
```bash
curl -X POST http://localhost:8000/admin/register-client \
-H "Content-Type: application/json" \
-d '{
"client_id": "my-client",
"client_secret": "my-secret",
"policy": {
"allowed_tools": ["get_weather"],
"allowed_resources": ["weather://*"],
"max_requests_per_minute": 100,
"require_auth": true,
"sandbox_mode": true
}
}'
```
3. **Make MCP Request**:
```bash
curl -X POST http://localhost:8000/mcp/request \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-H "Content-Type: application/json" \
-d '{
"server_name": "example-weather",
"request": {
"jsonrpc": "2.0",
"method": "tools/list",
"id": "1"
}
}'
```
## Configuration
### Security Policies
Each client can have a custom security policy:
```python
{
"allowed_tools": ["tool1", "tool2"], # Allowed tool names
"allowed_resources": ["resource://*"], # Resource patterns (regex)
"max_requests_per_minute": 60, # Rate limit
"max_request_size": 1048576, # Max request size (bytes)
"require_auth": true, # Require authentication
"allowed_origins": ["https://example.com"], # CORS origins
"sandbox_mode": true # Enable sandboxing
}
```
### MCP Server Configuration
Configure MCP servers in the `MCPServerManager.load_server_config()` method or via configuration files:
```python
{
"server-name": {
"command": "node",
"args": ["/path/to/server/build/index.js"],
"env": {"API_KEY": "your-key"},
"enabled": true
}
}
```
## API Endpoints
### Public Endpoints
- `GET /health` - Health check
- `POST /admin/register-client` - Register new client (admin only)
### Authenticated Endpoints
- `GET /servers` - List available MCP servers
- `POST /mcp/request` - Proxy MCP request to server
- `GET /audit/logs` - Get audit logs
## Security Features
### Authentication
- Bearer token authentication
- Client-specific tokens with policies
- Token validation and expiration
### Request Validation
- Method validation against allowed tools/resources
- Request size limits
- Input sanitization
- Policy enforcement
### Rate Limiting
- Token bucket algorithm
- Per-client rate limits
- Configurable limits per security policy
### Audit Logging
- All requests logged with timestamps
- Client identification
- Success/failure tracking
- Error details
### Response Sanitization
- Removes sensitive fields (passwords, tokens, keys, secrets)
- Recursive sanitization of nested objects
- Configurable sensitive field patterns
## Architecture
```
Client → Gateway → MCP Server
↓ ↓ ↓
Auth Validation Response
Rate Logging Sanitization
Limit Policy Error Handling
Enforcement
```
### Components
1. **SecurityManager**: Handles authentication, authorization, and policy enforcement
2. **MCPServerManager**: Manages connections and communication with MCP servers
3. **RateLimitBucket**: Implements token bucket rate limiting
4. **FastAPI App**: HTTP server with middleware and endpoints
## Future Enhancements
### Security
- [ ] JWT token support
- [ ] OAuth2 integration
- [ ] Role-based access control (RBAC)
- [ ] Request signing and verification
- [ ] IP whitelisting/blacklisting
- [ ] Advanced sandboxing with containers
### Functionality
- [ ] WebSocket support for real-time communication
- [ ] Request/response caching
- [ ] Load balancing across multiple MCP servers
- [ ] Circuit breaker pattern for fault tolerance
- [ ] Request transformation and middleware
### Monitoring
- [ ] Prometheus metrics
- [ ] Distributed tracing
- [ ] Performance monitoring
- [ ] Alert system
- [ ] Dashboard UI
### Storage
- [ ] Redis backend for rate limiting
- [ ] Database storage for audit logs
- [ ] Configuration management UI
- [ ] Client management dashboard
## Development
### Running in Development Mode
```bash
python main.py
```
The server will reload automatically on code changes.
### Testing
Create test clients and policies:
```python
# Example test client
test_policy = SecurityPolicy(
allowed_tools={"get_weather", "get_forecast"},
allowed_resources={"weather://*"},
max_requests_per_minute=100
)
test_client = ClientConfig(
client_id="test-client",
client_secret="test-secret",
policy=test_policy
)
```
### Adding New MCP Servers
1. Update the `MCPServerManager.load_server_config()` method
2. Add server configuration with command, args, and environment
3. Implement actual MCP communication in `send_request()` method
## Security Considerations
### Threat Model
The gateway protects against:
- **Malicious MCP servers**: Policy enforcement prevents unauthorized access
- **Compromised clients**: Rate limiting and validation prevent abuse
- **Data exfiltration**: Response sanitization removes sensitive data
- **DoS attacks**: Rate limiting and request size limits
- **Injection attacks**: Input validation and sanitization
### Best Practices
1. **Use strong authentication tokens**
2. **Implement least-privilege policies**
3. **Monitor audit logs regularly**
4. **Keep dependencies updated**
5. **Use HTTPS in production**
6. **Implement proper error handling**
7. **Regular security audits**
## License
This project is provided as an MVP example. Enhance and adapt according to your security requirements.
## Contributing
This is an MVP implementation. Key areas for contribution:
- Real MCP server communication implementation
- Enhanced security features
- Performance optimizations
- Comprehensive testing
- Documentation improvements
Raw data
{
"_id": null,
"home_page": "https://github.com/marklechner/mcpgw",
"name": "mcpgw",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": "mcp, model-context-protocol, gateway, api-gateway, security, fastapi, authentication, authorization, rate-limiting, proxy, middleware",
"author": "Mark Lechner",
"author_email": "Mark Lechner <hello@marklechner.dev>",
"download_url": "https://files.pythonhosted.org/packages/1c/85/1f3a86541a4a6151c6ef0d53d118a0a3942234c90c19e19f99d7d2d588ac/mcpgw-0.1.0.tar.gz",
"platform": null,
"description": "# MCP Gateway\n\nA lightweight, security-focused FastAPI gateway for Model Context Protocol (MCP) servers. This gateway acts as an intermediary between MCP clients and servers, providing authentication, authorization, rate limiting, request validation, and audit logging.\n\n## Features\n\n### Security\n- **Authentication & Authorization**: Token-based authentication with configurable client policies\n- **Request Validation**: Validates requests against allowed tools and resources\n- **Response Sanitization**: Removes sensitive information from responses\n- **Rate Limiting**: Token bucket algorithm for request rate limiting\n- **Audit Logging**: Comprehensive logging of all requests and responses\n- **Sandbox Mode**: Isolates MCP server execution (planned enhancement)\n\n### Gateway Functionality\n- **Request Proxying**: Forwards validated requests to appropriate MCP servers\n- **Policy Enforcement**: Enforces client-specific security policies\n- **Error Handling**: Graceful error handling with proper HTTP status codes\n- **CORS Support**: Configurable CORS policies for web clients\n\n### Monitoring & Management\n- **Health Checks**: Built-in health check endpoint\n- **Metrics**: Request metrics and performance monitoring (planned)\n- **Admin API**: Client registration and management endpoints\n\n## Quick Start\n\n### Installation\n\n1. Clone or create the project directory:\n```bash\nmkdir mcpgw && cd mcpgw\n```\n\n2. Install dependencies:\n```bash\npip install -r requirements.txt\n```\n\n3. Run the gateway:\n```bash\npython main.py\n```\n\nThe gateway will start on `http://localhost:8000`\n\n### Basic Usage\n\n1. **Health Check**:\n```bash\ncurl http://localhost:8000/health\n```\n\n2. **Register a Client** (for testing):\n```bash\ncurl -X POST http://localhost:8000/admin/register-client \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"client_id\": \"my-client\",\n \"client_secret\": \"my-secret\",\n \"policy\": {\n \"allowed_tools\": [\"get_weather\"],\n \"allowed_resources\": [\"weather://*\"],\n \"max_requests_per_minute\": 100,\n \"require_auth\": true,\n \"sandbox_mode\": true\n }\n }'\n```\n\n3. **Make MCP Request**:\n```bash\ncurl -X POST http://localhost:8000/mcp/request \\\n -H \"Authorization: Bearer YOUR_TOKEN_HERE\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"server_name\": \"example-weather\",\n \"request\": {\n \"jsonrpc\": \"2.0\",\n \"method\": \"tools/list\",\n \"id\": \"1\"\n }\n }'\n```\n\n## Configuration\n\n### Security Policies\n\nEach client can have a custom security policy:\n\n```python\n{\n \"allowed_tools\": [\"tool1\", \"tool2\"], # Allowed tool names\n \"allowed_resources\": [\"resource://*\"], # Resource patterns (regex)\n \"max_requests_per_minute\": 60, # Rate limit\n \"max_request_size\": 1048576, # Max request size (bytes)\n \"require_auth\": true, # Require authentication\n \"allowed_origins\": [\"https://example.com\"], # CORS origins\n \"sandbox_mode\": true # Enable sandboxing\n}\n```\n\n### MCP Server Configuration\n\nConfigure MCP servers in the `MCPServerManager.load_server_config()` method or via configuration files:\n\n```python\n{\n \"server-name\": {\n \"command\": \"node\",\n \"args\": [\"/path/to/server/build/index.js\"],\n \"env\": {\"API_KEY\": \"your-key\"},\n \"enabled\": true\n }\n}\n```\n\n## API Endpoints\n\n### Public Endpoints\n\n- `GET /health` - Health check\n- `POST /admin/register-client` - Register new client (admin only)\n\n### Authenticated Endpoints\n\n- `GET /servers` - List available MCP servers\n- `POST /mcp/request` - Proxy MCP request to server\n- `GET /audit/logs` - Get audit logs\n\n## Security Features\n\n### Authentication\n- Bearer token authentication\n- Client-specific tokens with policies\n- Token validation and expiration\n\n### Request Validation\n- Method validation against allowed tools/resources\n- Request size limits\n- Input sanitization\n- Policy enforcement\n\n### Rate Limiting\n- Token bucket algorithm\n- Per-client rate limits\n- Configurable limits per security policy\n\n### Audit Logging\n- All requests logged with timestamps\n- Client identification\n- Success/failure tracking\n- Error details\n\n### Response Sanitization\n- Removes sensitive fields (passwords, tokens, keys, secrets)\n- Recursive sanitization of nested objects\n- Configurable sensitive field patterns\n\n## Architecture\n\n```\nClient \u2192 Gateway \u2192 MCP Server\n \u2193 \u2193 \u2193\nAuth Validation Response\nRate Logging Sanitization\nLimit Policy Error Handling\n Enforcement\n```\n\n### Components\n\n1. **SecurityManager**: Handles authentication, authorization, and policy enforcement\n2. **MCPServerManager**: Manages connections and communication with MCP servers\n3. **RateLimitBucket**: Implements token bucket rate limiting\n4. **FastAPI App**: HTTP server with middleware and endpoints\n\n## Future Enhancements\n\n### Security\n- [ ] JWT token support\n- [ ] OAuth2 integration\n- [ ] Role-based access control (RBAC)\n- [ ] Request signing and verification\n- [ ] IP whitelisting/blacklisting\n- [ ] Advanced sandboxing with containers\n\n### Functionality\n- [ ] WebSocket support for real-time communication\n- [ ] Request/response caching\n- [ ] Load balancing across multiple MCP servers\n- [ ] Circuit breaker pattern for fault tolerance\n- [ ] Request transformation and middleware\n\n### Monitoring\n- [ ] Prometheus metrics\n- [ ] Distributed tracing\n- [ ] Performance monitoring\n- [ ] Alert system\n- [ ] Dashboard UI\n\n### Storage\n- [ ] Redis backend for rate limiting\n- [ ] Database storage for audit logs\n- [ ] Configuration management UI\n- [ ] Client management dashboard\n\n## Development\n\n### Running in Development Mode\n\n```bash\npython main.py\n```\n\nThe server will reload automatically on code changes.\n\n### Testing\n\nCreate test clients and policies:\n\n```python\n# Example test client\ntest_policy = SecurityPolicy(\n allowed_tools={\"get_weather\", \"get_forecast\"},\n allowed_resources={\"weather://*\"},\n max_requests_per_minute=100\n)\n\ntest_client = ClientConfig(\n client_id=\"test-client\",\n client_secret=\"test-secret\",\n policy=test_policy\n)\n```\n\n### Adding New MCP Servers\n\n1. Update the `MCPServerManager.load_server_config()` method\n2. Add server configuration with command, args, and environment\n3. Implement actual MCP communication in `send_request()` method\n\n## Security Considerations\n\n### Threat Model\n\nThe gateway protects against:\n- **Malicious MCP servers**: Policy enforcement prevents unauthorized access\n- **Compromised clients**: Rate limiting and validation prevent abuse\n- **Data exfiltration**: Response sanitization removes sensitive data\n- **DoS attacks**: Rate limiting and request size limits\n- **Injection attacks**: Input validation and sanitization\n\n### Best Practices\n\n1. **Use strong authentication tokens**\n2. **Implement least-privilege policies**\n3. **Monitor audit logs regularly**\n4. **Keep dependencies updated**\n5. **Use HTTPS in production**\n6. **Implement proper error handling**\n7. **Regular security audits**\n\n## License\n\nThis project is provided as an MVP example. Enhance and adapt according to your security requirements.\n\n## Contributing\n\nThis is an MVP implementation. Key areas for contribution:\n- Real MCP server communication implementation\n- Enhanced security features\n- Performance optimizations\n- Comprehensive testing\n- Documentation improvements\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "A lightweight, security-focused FastAPI gateway for Model Context Protocol (MCP) servers",
"version": "0.1.0",
"project_urls": {
"Bug Tracker": "https://github.com/marklechner/mcpgw/issues",
"Documentation": "https://github.com/marklechner/mcpgw#readme",
"Homepage": "https://github.com/marklechner/mcpgw",
"Repository": "https://github.com/marklechner/mcpgw"
},
"split_keywords": [
"mcp",
" model-context-protocol",
" gateway",
" api-gateway",
" security",
" fastapi",
" authentication",
" authorization",
" rate-limiting",
" proxy",
" middleware"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "0e84d4c674e4548f74532d701f78091abe0836939c88fcff7d3f6a6e76de7c79",
"md5": "4405c21b43f5a656e1804552d3b550c7",
"sha256": "3caab27eb9fe3db3120f8bd894108e833adeedaa2769145a96a48a97834bae4f"
},
"downloads": -1,
"filename": "mcpgw-0.1.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "4405c21b43f5a656e1804552d3b550c7",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 11082,
"upload_time": "2025-08-16T09:20:57",
"upload_time_iso_8601": "2025-08-16T09:20:57.475956Z",
"url": "https://files.pythonhosted.org/packages/0e/84/d4c674e4548f74532d701f78091abe0836939c88fcff7d3f6a6e76de7c79/mcpgw-0.1.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "1c851f3a86541a4a6151c6ef0d53d118a0a3942234c90c19e19f99d7d2d588ac",
"md5": "bbcecfd240df3dff417ab66bae987db2",
"sha256": "78f6e0d236ada6d3448c938e86f68cc33ece92f47335d1c75881dd3fb183bdc6"
},
"downloads": -1,
"filename": "mcpgw-0.1.0.tar.gz",
"has_sig": false,
"md5_digest": "bbcecfd240df3dff417ab66bae987db2",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 14614,
"upload_time": "2025-08-16T09:20:58",
"upload_time_iso_8601": "2025-08-16T09:20:58.985039Z",
"url": "https://files.pythonhosted.org/packages/1c/85/1f3a86541a4a6151c6ef0d53d118a0a3942234c90c19e19f99d7d2d588ac/mcpgw-0.1.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-16 09:20:58",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "marklechner",
"github_project": "mcpgw",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"requirements": [
{
"name": "fastapi",
"specs": [
[
"==",
"0.104.1"
]
]
},
{
"name": "uvicorn",
"specs": [
[
"==",
"0.24.0"
]
]
},
{
"name": "pydantic",
"specs": [
[
"==",
"2.5.0"
]
]
},
{
"name": "python-multipart",
"specs": [
[
"==",
"0.0.6"
]
]
},
{
"name": "requests",
"specs": [
[
"==",
"2.31.0"
]
]
},
{
"name": "pyyaml",
"specs": [
[
"==",
"6.0.1"
]
]
}
],
"lcname": "mcpgw"
}