Skip to content

unixsysdev/gritty

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MCP Docker Sandbox Server

A scholastic implementation of an MCP (Model Context Protocol) server that creates a Docker sandbox environment where users can execute commands, run scripts, and manage code across multiple programming languages.

Overview

The MCP Docker Sandbox Server provides a secure, isolated environment for executing code in various programming languages through Docker containers. It implements the MCP protocol to enable communication with MCP clients, allowing users to:

  • Create and manage Docker containers for different programming languages
  • Execute commands and scripts within containers
  • Transfer files between host and containers
  • Monitor resource usage and enforce limits
  • Manage language-specific configurations

Features

Multi-Language Support

  • Supports multiple programming languages with configurable Docker environments
  • Each language has its own Docker image, resource limits, and execution environment
  • Easy to add new languages by providing Dockerfile and configuration

Security and Isolation

  • Full container isolation with network, filesystem, and process separation
  • Configurable resource limits (CPU, memory, PIDs) to prevent resource abuse
  • Security monitoring with rule-based event detection
  • Automatic container cleanup and lifecycle management

MCP Protocol Implementation

  • Full implementation of the MCP protocol with JSON-RPC 2.0
  • Support for all standard MCP methods and custom extensions
  • Structured error handling with severity levels
  • Comprehensive metrics collection and reporting

Educational Design

  • Scholastic implementation with detailed code comments
  • Every function and major code block is thoroughly documented
  • Designed for learning and understanding MCP server implementation
  • Follows Go-specific standards and best practices

Installation

Prerequisites

  • Go 1.19 or later
  • Docker and Docker Compose
  • Make (for build automation)

Build from Source

# Clone the repository
git clone https://github.com/yourusername/go-sandbox-mcp.git
cd go-sandbox-mcp

# Build the server
make build

# Or build directly with Go
go build -o bin/mcp-server cmd/server/main.go

Using Docker

# Build the Docker image
docker build -t mcp-sandbox-server .

# Run the server
docker run -p 8080:8080 -v /var/run/docker.sock:/var/run/docker.sock mcp-sandbox-server

Configuration

The server can be configured through environment variables or a configuration file. The main configuration options include:

Environment Variables

# Server configuration
MCP_SERVER_HOST=0.0.0.0
MCP_SERVER_PORT=8080
MCP_SERVER_DEBUG=true

# Docker configuration
DOCKER_HOST=unix:///var/run/docker.sock
DOCKER_API_VERSION=1.41

# Sandbox configuration
SANDBOX_WORK_DIR=/tmp/mcp-sandbox
SANDBOX_DATA_DIR=/var/lib/mcp-sandbox
SANDBOX_LOG_LEVEL=info

Configuration File

Create a config.yaml file:

server:
  host: "0.0.0.0"
  port: 8080
  debug: true

docker:
  host: "unix:///var/run/docker.sock"
  api_version: "1.41"

sandbox:
  work_dir: "/tmp/mcp-sandbox"
  data_dir: "/var/lib/mcp-sandbox"
  log_level: "info"

logging:
  level: "info"
  format: "json"
  output: "stdout"
  rotation:
    max_size: "100MB"
    max_age: "7d"
    max_backups: 5

metrics:
  enabled: true
  port: 9090
  path: "/metrics"

Usage

Starting the Server

# Using default configuration
./bin/mcp-server

# Using custom configuration file
./bin/mcp-server -config /path/to/config.yaml

# Using environment variables
MCP_SERVER_PORT=9090 ./bin/mcp-server

MCP Protocol Usage

The server implements the MCP protocol over HTTP. Clients can connect to the server and send JSON-RPC 2.0 requests.

Example Request

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "create_container",
  "params": {
    "language": "python",
    "options": {
      "name": "my-python-container",
      "env_vars": {
        "PYTHONPATH": "/app"
      }
    }
  }
}

Example Response

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "id": "container-id-here",
    "name": "my-python-container",
    "status": "running",
    "image": "python:3.9-slim",
    "created": "2023-01-01T12:00:00Z"
  }
}

Available MCP Methods

Container Management

  • create_container - Create a new container for a specific language
  • remove_container - Remove a container
  • get_container_status - Get container status
  • get_container_info - Get detailed container information
  • get_container_resource_usage - Get resource usage statistics

Command Execution

  • execute_command - Execute a command in a container
  • run_script - Create and execute a script in a container

File Operations

  • copy_file - Copy file from host to container
  • copy_file_from_container - Copy file from container to host
  • list_files - List files in a container directory

Language Management

  • list_languages - List available languages
  • get_language_info - Get language configuration
  • enable_language - Enable a language
  • disable_language - Disable a language
  • reload_language - Reload language configuration

Language Configuration

Languages are configured through JSON files in the sandboxes directory. Each language has its own subdirectory containing a config.json file and optionally a Dockerfile.

Example Language Configuration

{
  "name": "python",
  "version": "3.9",
  "description": "Python 3.9 programming language",
  "enabled": true,
  "image": "python:3.9-slim",
  "commands": [
    "python",
    "pip",
    "python3"
  ],
  "environment": {
    "PYTHONPATH": "/app",
    "PYTHONUNBUFFERED": "1"
  },
  "resource_limits": {
    "cpu_shares": 512,
    "memory": "512m",
    "memory_swap": "1g",
    "cpu_quota": 100000,
    "cpu_period": 100000,
    "blkio_weight": 500,
    "pids_limit": 100
  },
  "timeout": 300,
  "file_extensions": [
    ".py",
    ".pyc"
  ],
  "tags": [
    "interpreted",
    "high-level"
  ],
  "examples": [
    {
      "name": "Hello World",
      "code": "print('Hello, World!')",
      "description": "Simple hello world example"
    }
  ]
}

Adding a New Language

  1. Create a directory in sandboxes for the language
  2. Create a config.json file with the language configuration
  3. Optionally create a custom Dockerfile
  4. Reload the server or use the reload_language MCP method
# Example directory structure
sandboxes/
├── python/
│   ├── config.json
│   └── Dockerfile
├── nodejs/
│   ├── config.json
│   └── Dockerfile
└── golang/
    ├── config.json
    └── Dockerfile

Security

Container Isolation

The server implements multiple layers of security:

  1. Network Isolation: Containers run in isolated networks
  2. Filesystem Isolation: Each container has its own filesystem
  3. Process Isolation: Container processes are isolated from the host
  4. Resource Isolation: Resource limits prevent resource abuse
  5. Security Monitoring: Rule-based security event detection

Resource Limits

Each language can have specific resource limits:

  • CPU Limits: CPU shares, quota, and period
  • Memory Limits: Memory and swap limits
  • Process Limits: Maximum number of processes
  • I/O Limits: Block I/O weight and throttling

Security Rules

The server includes configurable security rules:

  • Command Whitelisting: Only allowed commands can be executed
  • Path Restrictions: Access to specific paths is controlled
  • Resource Monitoring: Real-time monitoring of resource usage
  • Event Alerting: Alerts for security events and policy violations

Monitoring and Metrics

Prometheus Metrics

The server exposes Prometheus metrics at /metrics:

  • mcp_server_requests_total - Total number of requests
  • mcp_server_request_duration_seconds - Request duration
  • mcp_docker_containers_total - Total number of containers
  • mcp_docker_container_cpu_usage - Container CPU usage
  • mcp_docker_container_memory_usage - Container memory usage
  • mcp_sessions_total - Total number of sessions
  • mcp_executions_total - Total number of command executions

Logging

The server provides structured logging with multiple levels:

  • DEBUG: Detailed debugging information
  • INFO: General informational messages
  • WARN: Warning messages
  • ERROR: Error messages
  • FATAL: Fatal error messages

Log formats supported:

  • JSON
  • Text
  • Console

Development

Project Structure

go-sandbox-mcp/
├── cmd/
│   └── server/
│       └── main.go          # Server entry point
├── pkg/
│   ├── config/              # Configuration management
│   ├── docker/              # Docker client and operations
│   ├── languages/           # Language management
│   ├── logging/             # Logging system
│   ├── mcp/                 # MCP protocol implementation
│   ├── metrics/             # Metrics collection
│   ├── sessions/            # Session management
│   ├── executor/            # Command execution
│   ├── files/               # File operations
│   ├── isolation/           # Container isolation
│   ├── limits/              # Resource limits
│   └── monitoring/          # Security monitoring
├── sandboxes/               # Language configurations
├── integration/             # Integration tests
├── performance/             # Performance tests
├── security/                # Security tests
└── docs/                    # Documentation

Running Tests

# Run unit tests
make test

# Run integration tests
make test-integration

# Run performance tests
make test-performance

# Run security tests
make test-security

# Run all tests
make test-all

Building

# Build the server
make build

# Build for multiple platforms
make build-all

# Build Docker image
make docker-build

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

Code Style

  • Follow Go standard formatting
  • Use gofmt for code formatting
  • Write comprehensive tests
  • Add detailed code comments
  • Follow the existing code structure

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

For support, please:

  1. Check the documentation
  2. Search existing issues
  3. Create a new issue with detailed information
  4. Include logs and reproduction steps

Changelog

v1.0.0

  • Initial release
  • Multi-language support
  • MCP protocol implementation
  • Security and resource management
  • Comprehensive documentation

About

The bringer of sandboxes in MCP

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published