MN

mekalasubha-n/mcp

Developer tools
0 stars 0 forks Quality 41 Trend 0

A production-grade Model Context Protocol (MCP) server for SVN operations, designed to handle 1 million+ requests with OAuth authentication and scalable architecture.

Overview

A production-grade Model Context Protocol (MCP) server for SVN operations, designed to handle 1 million+ requests with OAuth authentication and scalable architecture. - support - : stdio and http-sse - for secure SVN access - for horizontal scalability - approach with input validation and sanitization - with async I/O and resource limits - Python 3.11+ (installed at C:\Program Files\Python311) - SVN command-line tools - SVN repository access with OAuth token 1. Clone or download this project 2. Install dependencies: 4. Configure your SVN credentials in .

README

SVN MCP Server

A production-grade Model Context Protocol (MCP) server for SVN operations, designed to handle 1 million+ requests with OAuth authentication and scalable architecture.

Features

  • MCP Protocol 2025-06-18 support
  • Dual Transport Modes: stdio and http-sse
  • OAuth Authentication for secure SVN access
  • Stateless Design for horizontal scalability
  • Security-First approach with input validation and sanitization
  • Performance Optimized with async I/O and resource limits

SVN Operations

Tool Description
svn_authenticate Validate SVN credentials using OAuth
svn_info Get repository information
svn_commit Commit changes to repository
svn_diff Show differences between revisions
svn_history Show commit history
svn_last_commit Show latest commit details
svn_status Show working copy status
svn_checkout Checkout repository to local path
svn_update Update working copy
svn_add Add files to version control
svn_delete Delete files from version control
svn_log Show detailed commit log with file changes

Quick Start

Prerequisites

  • Python 3.11+ (installed at C:\Program Files\Python311)
  • SVN command-line tools
  • SVN repository access with OAuth token

Installation

  1. Clone or download this project

  2. Install dependencies:

    pip install -r requirements.txt
    
  3. Create environment file:

    copy .env.example .env
    
  4. Configure your SVN credentials in .env:

    SVN_URL=https://your-svn-server.com/svn/repository
    SVN_USERNAME=your_username
    OAUTH_TOKEN=your_oauth_token
    

Running the Server

stdio mode (default):

python main.py
# or explicitly:
python main.py --transport stdio

HTTP-SSE mode:

python main.py --transport sse --host localhost --port 8082

Command line options:

python main.py --help

# Options:
#   --transport {stdio,sse}  Transport mode (default: stdio)
#   --host HOST             Host for SSE mode (default: localhost)
#   --port PORT             Port for SSE mode (default: 8082)
#   --version               Show version and exit

SSE Mode Endpoints:

  • http://localhost:8082/ - Server information
  • http://localhost:8082/sse - SSE stream for MCP communication
  • http://localhost:8082/tools - Available tools list
  • http://localhost:8082/health - Health check endpoint

Development Setup

For development with proper package structure:

# Install in development mode
pip install -e .

# Install with development dependencies
pip install -e ".[dev]"

# Run tests
python -m pytest tests/

# Run with coverage
python -m pytest tests/ --cov=src/svn_mcp --cov-report=html

Configuration

Environment Variables

Variable Description Default
SVN_URL SVN repository URL None
SVN_USERNAME SVN username None
SVN_PASSWORD SVN password None
OAUTH_TOKEN OAuth token (preferred) None
SVN_WORKING_COPY_ROOT Root directory for working copies None
MAX_REQUESTS_PER_MINUTE Rate limit 1000
MAX_CONCURRENT_REQUESTS Concurrency limit 100
REQUEST_TIMEOUT Request timeout (seconds) 60
ALLOWED_SVN_DOMAINS Comma-separated allowed domains None
LOG_LEVEL Logging level INFO
LOG_FORMAT Log format (text/json) text

Architecture

Project Structure

SVN_MCP/
├── src/svn_mcp/           # Main source code package
│   ├── __init__.py        # Package initialization
│   ├── server.py          # Main FastMCP server implementation
│   ├── handlers/          # Business logic handlers
│   │   ├── __init__.py
│   │   ├── auth_handler.py    # Authentication operations
│   │   └── svn_handler.py     # SVN operations
│   ├── tools/             # MCP tool definitions
│   │   ├── __init__.py
│   │   └── svn_tools.py       # SVN tool implementations
│   └── utils/             # Utility modules
│       ├── __init__.py
│       ├── config.py          # Configuration management
│       ├── security.py        # Security utilities
│       ├── validation.py      # Input validation
│       └── logger.py          # Structured logging
├── tests/                 # Test suite
│   ├── __init__.py
│   ├── test_utils.py
│   └── test_tools.py
├── main.py               # Entry point
├── requirements.txt      # Dependencies
├── pyproject.toml       # Modern Python project config
├── setup.py             # Package setup
├── .env.example         # Environment template
└── README.md           # Documentation

Core Components

  • main.py: Entry point that sets up Python path and launches the server
  • src/svn_mcp/server.py: FastMCP server with lifespan management
  • src/svn_mcp/tools/: Tool definitions using FastMCP decorators
    • svn_tools.py: All SVN tool implementations
  • src/svn_mcp/handlers/: Business logic handlers
    • auth_handler.py: Authentication operations
    • svn_handler.py: SVN operations
  • src/svn_mcp/utils/: Utility modules
    • config.py: Configuration management
    • security.py: Security utilities and subprocess handling
    • validation.py: Input validation and sanitization
    • logger.py: Structured logging
  • tests/: Comprehensive test suite

Security Features

  • Input Sanitization: All user inputs are validated and sanitized
  • Command Validation: Only allowed SVN commands can be executed
  • Secure Subprocess: Isolated process execution with timeout
  • Rate Limiting: Built-in rate limiting capabilities
  • OAuth Support: Secure authentication using OAuth tokens
  • Domain Restriction: Configurable SVN domain allowlisting

Performance Features

  • Async I/O: Non-blocking operations throughout
  • Stateless Design: No shared state between requests
  • Resource Limits: Memory and output size limits
  • Request Timeout: Configurable timeout handling
  • Minimal Dependencies: Lightweight dependency footprint

Usage Examples

Authentication

# Authenticate with OAuth token
svn_authenticate(
    svn_url="https://svn.company.com/repo",
    oauth_token="your_oauth_token"
)

Repository Information

# Get repository info
svn_info(
    svn_url="https://svn.company.com/repo",
    project_path="trunk/myproject"
)

Working Copy Operations

# Check working copy status
svn_status(
    working_copy_path="C:/workspace/myproject",
    show_updates=True
)

# Checkout repository
svn_checkout(
    svn_url="https://svn.company.com/repo/trunk/myproject",
    local_path="C:/workspace/myproject",
    revision="HEAD"
)

# Update working copy
svn_update(
    working_copy_path="C:/workspace/myproject",
    revision="HEAD"
)

File Management

# Add files to version control
svn_add(
    files=["new_file.py", "docs/readme.txt"],
    working_copy_path="C:/workspace/myproject",
    force=False
)

# Delete files from version control
svn_delete(
    files=["old_file.py"],
    working_copy_path="C:/workspace/myproject",
    force=False
)

Commit Changes

# Commit specific files
svn_commit(
    svn_url="https://svn.company.com/repo",
    message="Fix bug in authentication module",
    files=["src/auth.py", "tests/test_auth.py"]
)

View Differences

# Compare revisions
svn_diff(
    svn_url="https://svn.company.com/repo",
    revision1="HEAD",
    revision2="PREV",
    file_path="src/main.py"
)

Commit History

# Get recent history (simple)
svn_history(
    svn_url="https://svn.company.com/repo",
    limit=20,
    path="trunk/frontend"
)

# Get detailed log with file changes
svn_log(
    svn_url="https://svn.company.com/repo",
    working_copy_path="C:/workspace/myproject",
    limit=10,
    verbose=True,
    revision_range="HEAD:10"
)

Security Considerations

Input Validation

  • All SVN URLs are validated against allowed patterns
  • File paths are sanitized to prevent directory traversal
  • Command injection protection through argument validation
  • Size limits on all inputs to prevent DoS attacks

Authentication

  • OAuth token authentication preferred over username/password
  • Credentials stored in environment variables only
  • No credential caching or persistence

Subprocess Security

  • Command allowlisting (only SVN commands allowed)
  • Argument sanitization and validation
  • Process isolation with new session
  • Timeout protection against hanging processes

Enterprise Production Bottlenecks and Mitigations

Critical System Stability Bottlenecks

1. Memory Exhaustion

  • Risk: Multiple concurrent requests can consume excessive memory
  • Scenarios:
    • Large SVN outputs (diffs, logs) × concurrent requests
    • Memory leaks in subprocess handling
    • Unbounded request queuing
  • Mitigations:
    MAX_OUTPUT_SIZE=1048576          # 1MB per request
    MAX_CONCURRENT_REQUESTS=50       # Reduce for production
    MAX_REQUESTS_PER_MINUTE=500      # Conservative rate limiting
    
  • Monitoring: Track memory usage, implement health checks
  • Fail-safe: Auto-restart on memory threshold breach

2. Process/File Descriptor Exhaustion

  • Risk: Each SVN command spawns subprocess, high concurrency exhausts OS limits
  • Scenarios:
    • 100+ concurrent SVN operations
    • Hanging/zombie processes
    • File descriptor leaks
  • Mitigations:
    # OS-level limits
    ulimit -n 4096                   # File descriptors
    ulimit -u 1024                   # User processes
    
    # Application limits
    MAX_CONCURRENT_REQUESTS=25       # Conservative for enterprise
    REQUEST_TIMEOUT=30               # Shorter timeouts
    
  • Cleanup: Explicit process cleanup, timeout enforcement

3. CPU Starvation

  • Risk: SVN operations are CPU-intensive, can starve other processes
  • Scenarios:
    • Large repository operations
    • Concurrent diff/merge operations
    • No CPU throttling
  • Mitigations:
    # Process priority and CPU limits
    import psutil
    process = psutil.Process()
    process.nice(10)                 # Lower priority
    
    # Consider using cgroups for CPU limits
    

Performance Bottlenecks

1. SVN Command Execution Latency

  • Issue: Each SVN operation may take 1-30 seconds depending on repository size
  • Impact: Blocking operations under high load
  • Mitigations:
    REQUEST_TIMEOUT=15               # Aggressive timeout
    # Implement request queuing with priority
    # Fast-fail for oversized operations
    

2. Network I/O Bottlenecks

  • Issue: Remote SVN operations depend on network performance
  • Scenarios:
    • Slow/unreliable SVN server connections
    • Large file transfers
    • Network partitions
  • Mitigations:
    # Connection validation before operations
    # Retry logic with exponential backoff
    # Circuit breaker pattern for failing repositories
    

3. Stateless Overhead

  • Issue: No caching means repeated authentication/validation
  • Impact: ~100-500ms overhead per request
  • Mitigations:
    # Optimize validation routines
    # Pre-compile regex patterns
    # Minimize subprocess startup overhead
    

Security Bottlenecks

1. Command Injection Vulnerabilities

  • Risk: Malicious input could execute arbitrary commands
  • Attack Vectors:
    # Dangerous inputs
    svn_url="file:///path; rm -rf /"
    revision="HEAD && malicious_command"
    
  • Mitigations:
    # Strict input validation (already implemented)
    # Subprocess argument arrays (not shell commands)
    # Input sanitization with allowlists only
    

2. Resource-Based DoS Attacks

  • Risk: Attackers flood server with expensive operations
  • Attack Scenarios:
    • Large diff requests
    • Deep history requests
    • Rapid-fire authentication attempts
  • Mitigations:
    MAX_REQUESTS_PER_MINUTE=100      # Per IP/client
    REQUEST_SIZE_LIMIT=10KB          # Input size limit
    OPERATION_COMPLEXITY_LIMITS=True # Reject expensive ops
    

3. Credential Exposure

  • Risk: Credentials leaked in logs, memory dumps, or errors
  • Mitigations:
    # Never log sensitive data
    # Clear credentials from memory after use
    # Encrypted credential storage
    # Audit all log outputs
    

Efficiency Bottlenecks

1. Synchronous I/O Blocking

  • Issue: Blocking operations reduce server throughput
  • Solution: Already using async subprocess, but ensure proper implementation
  • Optimization:
    # Use asyncio.create_subprocess_exec
    # Implement proper async/await throughout
    # Non-blocking file I/O where possible
    

2. Redundant Operations

  • Issue: Stateless design prevents optimization
  • Acceptable Trade-off: Scalability over efficiency
  • Optimization:
    # Optimize common code paths
    # Reduce object creation overhead
    # Pre-validate inputs before expensive operations
    

Enterprise Production Recommendations

System-Level Safeguards

# Resource limits (systemd service)
[Service]
MemoryMax=2G
TasksMax=100
TimeoutStartSec=30
TimeoutStopSec=30
Restart=always
RestartSec=5

# Monitoring and alerting
# Memory usage > 80%
# CPU usage > 90% for > 30s
# Error rate > 5%
# Response time > 10s average

Application-Level Configuration

# Conservative production settings
MAX_CONCURRENT_REQUESTS=25        # Lower for stability
MAX_REQUESTS_PER_MINUTE=300       # Rate limiting
REQUEST_TIMEOUT=15                # Aggressive timeouts
MAX_OUTPUT_SIZE=524288            # 512KB limit
HEALTH_CHECK_INTERVAL=30          # Auto-restart triggers

Load Balancing Strategy

# Multiple server instances
- Instance 1: Port 3001 (25 concurrent)
- Instance 2: Port 3002 (25 concurrent)  
- Instance 3: Port 3003 (25 concurrent)
# Total capacity: 75 concurrent requests
# Load balancer with health checks

Monitoring and Observability

# Key metrics to track
- Memory usage per process
- Active subprocess count
- Request queue depth
- Average response time
- Error rates by operation type
- Authentication failure rates

Graceful Degradation

# When approaching limits
1. Reject new requests (503 Service Unavailable)
2. Complete in-flight requests
3. Gradual recovery with backpressure
4. Circuit breaker for failing dependencies

Scalability Design

  • Stateless Architecture: Each request is independent
  • No Caching: Compliance with 1M hits requirement without shared state
  • Resource Limits: Memory and CPU usage bounded per request
  • Horizontal Scaling: Multiple server instances can run independently

Enterprise Deployment Checklist

Pre-Deployment

  • [ ] Load testing with realistic SVN repository sizes
  • [ ] Memory profiling under concurrent load
  • [ ] Security penetration testing
  • [ ] Fail-over and recovery testing
  • [ ] Performance baseline establishment

Production Deployment

  • [ ] Resource monitoring and alerting
  • [ ] Log aggregation and analysis
  • [ ] Backup and disaster recovery procedures
  • [ ] Security audit and compliance validation
  • [ ] Performance optimization based on actual usage patterns

Operational Monitoring

# Critical alerts
- Memory usage > 80% for 5 minutes
- CPU usage > 90% for 2 minutes  
- Error rate > 5% over 10 minutes
- Average response time > 10 seconds
- Failed authentication rate > 10%
- Subprocess count > MAX_CONCURRENT_REQUESTS

# Performance metrics
- Request throughput (requests/second)
- Response time percentiles (p50, p95, p99)
- Resource utilization (CPU, memory, file descriptors)
- SVN operation success rates
- Network I/O and latency

Incident Response Procedures

  1. High Memory Usage: Scale down concurrency, restart if needed
  2. Process Exhaustion: Kill hanging processes, restart service
  3. Network Issues: Enable circuit breaker, fail gracefully
  4. Security Incidents: Isolate service, audit logs, notify security team
  5. Performance Degradation: Reduce limits, analyze bottlenecks

Development

Adding New SVN Operations

  1. Add the tool definition to the appropriate handler’s handle_list_tools() method
  2. Implement the handler method following the async pattern
  3. Add input validation using ValidationUtils
  4. Use SecurityUtils.execute_secure_subprocess() for SVN commands
  5. Add comprehensive error handling and logging

Testing

# Run with debug logging
LOG_LEVEL=DEBUG python main.py

# Test with specific SVN URL
SVN_URL=https://your-test-repo.com/svn python main.py

Debugging

The server provides structured logging with request IDs for debugging:

# Enable JSON logging
LOG_FORMAT=json python main.py

# Log to file
LOG_FILE=svn_mcp.log python main.py

License

This project is designed for production use with enterprise SVN systems.

Support

For issues related to:

  • SVN operations: Check SVN server connectivity and credentials
  • Performance: Review resource limits and network latency
  • Security: Verify input validation and authentication configuration
View the full README on GitHub

Install

This server does not publish a one-line install command.

Open the repository installation guide New to MCP? Start with the mcpskill.org guide →