docker-mcp-sdk


Namedocker-mcp-sdk JSON
Version 0.1.0 PyPI version JSON
download
home_pageNone
SummaryA Model Context Protocol server for secure Docker container execution
upload_time2025-08-08 21:12:00
maintainerNone
docs_urlNone
authorNone
requires_python>=3.10
licenseMIT
keywords mcp docker container sandbox llm ai code-execution
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Docker MCP Server

A Model Context Protocol (MCP) server that enables LLMs to safely execute code in isolated Docker containers with strict resource limits and security controls.

## Features

- 🔒 **Secure Isolation**: Containers run with strict resource limits (memory, CPU, PIDs)
- 🏷️ **Session Management**: Group containers by session with persistent workspaces
- ♻️ **Container Reuse**: Optimize performance by reusing existing containers
- 📦 **Smart Dependencies**: Auto-detect and install packages (pip, npm, apt, apk)
- 🔄 **Streaming Output**: Real-time output for long-running processes
- 💾 **Persistent Workspaces**: Session-based volumes maintain state across executions

## Installation

```bash
# Clone the repository
git clone https://github.com/cevatkerim/docker-mcp.git
cd docker-mcp

# Install in development mode
pip install -e .

# Install development dependencies
pip install -r requirements-dev.txt
```

## Prerequisites

- Python 3.10+
- Docker Engine running locally
- MCP-compatible client (e.g., Claude Desktop)

## Quick Start

### 1. Start the MCP Server

```bash
python -m docker_mcp
```

### 2. Configure Your MCP Client

Add to your MCP client configuration:

```json
{
  "mcpServers": {
    "docker": {
      "command": "python",
      "args": ["-m", "docker_mcp"]
    }
  }
}
```

## Available Tools

### 1. check_engine
Check Docker engine availability and version.

```python
result = check_engine()
# Returns: Docker version and status
```

### 2. list_containers
List Docker containers with optional filtering.

```python
result = list_containers(
    show_all=True,  # Show all containers, not just running
    session_id="my-session"  # Filter by session
)
```

### 3. create_container
Create and start a new container with resource limits.

```python
result = create_container(
    image="python:3.11-slim",
    name="my-container",
    session_id="my-session",
    network_enabled=False,  # Network isolation by default
    reuse_existing=True,    # Reuse if exists
    environment={"KEY": "value"}
)
```

### 4. execute_code
Execute commands in a container.

```python
result = execute_code(
    container_id="my-container",
    command="echo 'Hello, World!'",
    timeout=30,
    stream=True,  # Stream output in real-time
    working_dir="/workspace"
)
```

### 5. execute_python_script
Execute Python scripts with automatic dependency management.

```python
result = execute_python_script(
    container_id="my-container",
    script="import numpy; print(numpy.__version__)",
    packages=["numpy"],  # Auto-install if needed
    timeout=60
)
```

### 6. add_dependencies
Install packages in a running container.

```python
result = add_dependencies(
    container_id="my-container",
    packages=["requests", "pandas"],
    package_manager="pip"  # Auto-detected if not specified
)
```

### 7. cleanup_container
Stop and remove containers with optional volume cleanup.

```python
# Remove specific container
result = cleanup_container(container_id="my-container")

# Remove all containers for a session
result = cleanup_container(session_id="my-session", remove_volumes=True)

# Remove all MCP-managed containers
result = cleanup_container(cleanup_all=True)
```

## Security Features

### Resource Limits
- **Memory**: 1GB default (configurable)
- **CPU**: 1.0 cores default (configurable)
- **Process IDs**: 512 max (configurable)
- **Network**: Isolated by default, opt-in for network access

### Container Labels
All containers are labeled with `mcp-managed=true` for easy identification and cleanup.

### Workspace Isolation
Each container gets a `/workspace` directory backed by a named volume, preventing host filesystem access.

## Configuration

Configure via environment variables:

```bash
export DOCKER_MCP_MEMORY_LIMIT=2147483648  # 2GB in bytes
export DOCKER_MCP_CPU_LIMIT=2.0            # 2 CPU cores
export DOCKER_MCP_PIDS_LIMIT=1024          # Max processes
export DOCKER_MCP_TIMEOUT=60               # Default timeout
export DOCKER_MCP_DEBUG=true               # Enable debug logging
```

## Examples

### Example 1: Python Data Analysis

```python
# Create a container for data analysis
container = create_container(
    image="python:3.11-slim",
    session_id="data-analysis"
)

# Install required packages
add_dependencies(
    container_id=container['container_id'],
    packages=["pandas", "matplotlib", "seaborn"]
)

# Execute analysis script
script = """
import pandas as pd
import matplotlib.pyplot as plt

# Create sample data
df = pd.DataFrame({
    'x': range(10),
    'y': [i**2 for i in range(10)]
})

# Save plot
df.plot(x='x', y='y')
plt.savefig('/workspace/plot.png')
print("Plot saved to /workspace/plot.png")
print(df.describe())
"""

execute_python_script(
    container_id=container['container_id'],
    script=script
)
```

### Example 2: Node.js Development

```python
# Create Node.js container
container = create_container(
    image="node:18-alpine",
    session_id="nodejs-dev",
    network_enabled=True  # Need network for npm
)

# Install packages
add_dependencies(
    container_id=container['container_id'],
    packages=["express", "axios"],
    package_manager="npm"
)

# Run Node.js code
execute_code(
    container_id=container['container_id'],
    command="node -e \"console.log('Node version:', process.version)\""
)
```

### Example 3: Multi-Language Project

```python
# Create container with Python and Node.js
container = create_container(
    image="nikolaik/python-nodejs:python3.11-nodejs18",
    session_id="multi-lang"
)

# Install Python packages
add_dependencies(
    container_id=container['container_id'],
    packages=["fastapi", "uvicorn"],
    package_manager="pip"
)

# Install Node packages
add_dependencies(
    container_id=container['container_id'],
    packages=["webpack", "babel-core"],
    package_manager="npm"
)
```

## Development

### Running Tests

```bash
# Run all tests
pytest

# Run with coverage
pytest --cov=src --cov-report=term

# Run specific test file
pytest tests/test_docker_client.py -v
```

### Project Structure

```
docker-mcp/
├── src/
│   └── docker_mcp/
│       ├── __init__.py
│       ├── server.py         # MCP server implementation
│       ├── container_ops.py  # Tool implementations
│       ├── docker_client.py  # Docker SDK wrapper
│       ├── config.py         # Configuration
│       └── schemas.py        # Data models
├── tests/
│   ├── test_docker_client.py
│   ├── test_tools_comprehensive.py
│   └── ...
├── pyproject.toml
├── requirements.txt
└── README.md
```

## Troubleshooting

### Docker Not Available
```
Error: Cannot connect to Docker daemon
```
**Solution**: Ensure Docker Desktop is running and the Docker socket is accessible.

### Permission Denied
```
Error: Permission denied while trying to connect to Docker daemon
```
**Solution**: Add your user to the docker group or run with appropriate permissions.

### Container Creation Failed
```
Error: Image not found
```
**Solution**: The image will be automatically pulled. Ensure you have internet connectivity.

## Contributing

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

## License

MIT License - see LICENSE file for details.

## Support

For issues and questions, please open an issue on GitHub.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "docker-mcp-sdk",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": "Kerim Incedayi <k@kerim.me>",
    "keywords": "mcp, docker, container, sandbox, llm, ai, code-execution",
    "author": null,
    "author_email": "Kerim Incedayi <k@kerim.me>",
    "download_url": "https://files.pythonhosted.org/packages/f7/2a/1ba6f15ab79e80121d62987e863e37327099e25664175d11f1423b6142a8/docker_mcp_sdk-0.1.0.tar.gz",
    "platform": null,
    "description": "# Docker MCP Server\n\nA Model Context Protocol (MCP) server that enables LLMs to safely execute code in isolated Docker containers with strict resource limits and security controls.\n\n## Features\n\n- \ud83d\udd12 **Secure Isolation**: Containers run with strict resource limits (memory, CPU, PIDs)\n- \ud83c\udff7\ufe0f **Session Management**: Group containers by session with persistent workspaces\n- \u267b\ufe0f **Container Reuse**: Optimize performance by reusing existing containers\n- \ud83d\udce6 **Smart Dependencies**: Auto-detect and install packages (pip, npm, apt, apk)\n- \ud83d\udd04 **Streaming Output**: Real-time output for long-running processes\n- \ud83d\udcbe **Persistent Workspaces**: Session-based volumes maintain state across executions\n\n## Installation\n\n```bash\n# Clone the repository\ngit clone https://github.com/cevatkerim/docker-mcp.git\ncd docker-mcp\n\n# Install in development mode\npip install -e .\n\n# Install development dependencies\npip install -r requirements-dev.txt\n```\n\n## Prerequisites\n\n- Python 3.10+\n- Docker Engine running locally\n- MCP-compatible client (e.g., Claude Desktop)\n\n## Quick Start\n\n### 1. Start the MCP Server\n\n```bash\npython -m docker_mcp\n```\n\n### 2. Configure Your MCP Client\n\nAdd to your MCP client configuration:\n\n```json\n{\n  \"mcpServers\": {\n    \"docker\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"docker_mcp\"]\n    }\n  }\n}\n```\n\n## Available Tools\n\n### 1. check_engine\nCheck Docker engine availability and version.\n\n```python\nresult = check_engine()\n# Returns: Docker version and status\n```\n\n### 2. list_containers\nList Docker containers with optional filtering.\n\n```python\nresult = list_containers(\n    show_all=True,  # Show all containers, not just running\n    session_id=\"my-session\"  # Filter by session\n)\n```\n\n### 3. create_container\nCreate and start a new container with resource limits.\n\n```python\nresult = create_container(\n    image=\"python:3.11-slim\",\n    name=\"my-container\",\n    session_id=\"my-session\",\n    network_enabled=False,  # Network isolation by default\n    reuse_existing=True,    # Reuse if exists\n    environment={\"KEY\": \"value\"}\n)\n```\n\n### 4. execute_code\nExecute commands in a container.\n\n```python\nresult = execute_code(\n    container_id=\"my-container\",\n    command=\"echo 'Hello, World!'\",\n    timeout=30,\n    stream=True,  # Stream output in real-time\n    working_dir=\"/workspace\"\n)\n```\n\n### 5. execute_python_script\nExecute Python scripts with automatic dependency management.\n\n```python\nresult = execute_python_script(\n    container_id=\"my-container\",\n    script=\"import numpy; print(numpy.__version__)\",\n    packages=[\"numpy\"],  # Auto-install if needed\n    timeout=60\n)\n```\n\n### 6. add_dependencies\nInstall packages in a running container.\n\n```python\nresult = add_dependencies(\n    container_id=\"my-container\",\n    packages=[\"requests\", \"pandas\"],\n    package_manager=\"pip\"  # Auto-detected if not specified\n)\n```\n\n### 7. cleanup_container\nStop and remove containers with optional volume cleanup.\n\n```python\n# Remove specific container\nresult = cleanup_container(container_id=\"my-container\")\n\n# Remove all containers for a session\nresult = cleanup_container(session_id=\"my-session\", remove_volumes=True)\n\n# Remove all MCP-managed containers\nresult = cleanup_container(cleanup_all=True)\n```\n\n## Security Features\n\n### Resource Limits\n- **Memory**: 1GB default (configurable)\n- **CPU**: 1.0 cores default (configurable)\n- **Process IDs**: 512 max (configurable)\n- **Network**: Isolated by default, opt-in for network access\n\n### Container Labels\nAll containers are labeled with `mcp-managed=true` for easy identification and cleanup.\n\n### Workspace Isolation\nEach container gets a `/workspace` directory backed by a named volume, preventing host filesystem access.\n\n## Configuration\n\nConfigure via environment variables:\n\n```bash\nexport DOCKER_MCP_MEMORY_LIMIT=2147483648  # 2GB in bytes\nexport DOCKER_MCP_CPU_LIMIT=2.0            # 2 CPU cores\nexport DOCKER_MCP_PIDS_LIMIT=1024          # Max processes\nexport DOCKER_MCP_TIMEOUT=60               # Default timeout\nexport DOCKER_MCP_DEBUG=true               # Enable debug logging\n```\n\n## Examples\n\n### Example 1: Python Data Analysis\n\n```python\n# Create a container for data analysis\ncontainer = create_container(\n    image=\"python:3.11-slim\",\n    session_id=\"data-analysis\"\n)\n\n# Install required packages\nadd_dependencies(\n    container_id=container['container_id'],\n    packages=[\"pandas\", \"matplotlib\", \"seaborn\"]\n)\n\n# Execute analysis script\nscript = \"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Create sample data\ndf = pd.DataFrame({\n    'x': range(10),\n    'y': [i**2 for i in range(10)]\n})\n\n# Save plot\ndf.plot(x='x', y='y')\nplt.savefig('/workspace/plot.png')\nprint(\"Plot saved to /workspace/plot.png\")\nprint(df.describe())\n\"\"\"\n\nexecute_python_script(\n    container_id=container['container_id'],\n    script=script\n)\n```\n\n### Example 2: Node.js Development\n\n```python\n# Create Node.js container\ncontainer = create_container(\n    image=\"node:18-alpine\",\n    session_id=\"nodejs-dev\",\n    network_enabled=True  # Need network for npm\n)\n\n# Install packages\nadd_dependencies(\n    container_id=container['container_id'],\n    packages=[\"express\", \"axios\"],\n    package_manager=\"npm\"\n)\n\n# Run Node.js code\nexecute_code(\n    container_id=container['container_id'],\n    command=\"node -e \\\"console.log('Node version:', process.version)\\\"\"\n)\n```\n\n### Example 3: Multi-Language Project\n\n```python\n# Create container with Python and Node.js\ncontainer = create_container(\n    image=\"nikolaik/python-nodejs:python3.11-nodejs18\",\n    session_id=\"multi-lang\"\n)\n\n# Install Python packages\nadd_dependencies(\n    container_id=container['container_id'],\n    packages=[\"fastapi\", \"uvicorn\"],\n    package_manager=\"pip\"\n)\n\n# Install Node packages\nadd_dependencies(\n    container_id=container['container_id'],\n    packages=[\"webpack\", \"babel-core\"],\n    package_manager=\"npm\"\n)\n```\n\n## Development\n\n### Running Tests\n\n```bash\n# Run all tests\npytest\n\n# Run with coverage\npytest --cov=src --cov-report=term\n\n# Run specific test file\npytest tests/test_docker_client.py -v\n```\n\n### Project Structure\n\n```\ndocker-mcp/\n\u251c\u2500\u2500 src/\n\u2502   \u2514\u2500\u2500 docker_mcp/\n\u2502       \u251c\u2500\u2500 __init__.py\n\u2502       \u251c\u2500\u2500 server.py         # MCP server implementation\n\u2502       \u251c\u2500\u2500 container_ops.py  # Tool implementations\n\u2502       \u251c\u2500\u2500 docker_client.py  # Docker SDK wrapper\n\u2502       \u251c\u2500\u2500 config.py         # Configuration\n\u2502       \u2514\u2500\u2500 schemas.py        # Data models\n\u251c\u2500\u2500 tests/\n\u2502   \u251c\u2500\u2500 test_docker_client.py\n\u2502   \u251c\u2500\u2500 test_tools_comprehensive.py\n\u2502   \u2514\u2500\u2500 ...\n\u251c\u2500\u2500 pyproject.toml\n\u251c\u2500\u2500 requirements.txt\n\u2514\u2500\u2500 README.md\n```\n\n## Troubleshooting\n\n### Docker Not Available\n```\nError: Cannot connect to Docker daemon\n```\n**Solution**: Ensure Docker Desktop is running and the Docker socket is accessible.\n\n### Permission Denied\n```\nError: Permission denied while trying to connect to Docker daemon\n```\n**Solution**: Add your user to the docker group or run with appropriate permissions.\n\n### Container Creation Failed\n```\nError: Image not found\n```\n**Solution**: The image will be automatically pulled. Ensure you have internet connectivity.\n\n## Contributing\n\n1. Fork the repository\n2. Create a feature branch\n3. Write tests for new functionality\n4. Implement the feature\n5. Ensure all tests pass\n6. Submit a pull request\n\n## License\n\nMIT License - see LICENSE file for details.\n\n## Support\n\nFor issues and questions, please open an issue on GitHub.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A Model Context Protocol server for secure Docker container execution",
    "version": "0.1.0",
    "project_urls": {
        "Documentation": "https://github.com/cevatkerim/docker-mcp#readme",
        "Homepage": "https://github.com/cevatkerim/docker-mcp",
        "Issues": "https://github.com/cevatkerim/docker-mcp/issues",
        "Repository": "https://github.com/cevatkerim/docker-mcp.git"
    },
    "split_keywords": [
        "mcp",
        " docker",
        " container",
        " sandbox",
        " llm",
        " ai",
        " code-execution"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "495436466cab8f89a33ca05662e587fd7ac3e1d2b19e550fcd55d5f5c40ea1a5",
                "md5": "0b6acfb864e91c84e56871e4e96383b9",
                "sha256": "8dddd8faa0ccdbc1031adc36cac72a3f62364718ceecb99d53735f9cc4bb2ce4"
            },
            "downloads": -1,
            "filename": "docker_mcp_sdk-0.1.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "0b6acfb864e91c84e56871e4e96383b9",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 18244,
            "upload_time": "2025-08-08T21:11:58",
            "upload_time_iso_8601": "2025-08-08T21:11:58.685744Z",
            "url": "https://files.pythonhosted.org/packages/49/54/36466cab8f89a33ca05662e587fd7ac3e1d2b19e550fcd55d5f5c40ea1a5/docker_mcp_sdk-0.1.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "f72a1ba6f15ab79e80121d62987e863e37327099e25664175d11f1423b6142a8",
                "md5": "76491abfebf82ea8155c4917af930f03",
                "sha256": "45a3f3cf39191216c9b521b77a9ab989cb2165c41402c6902d46ae30929553a1"
            },
            "downloads": -1,
            "filename": "docker_mcp_sdk-0.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "76491abfebf82ea8155c4917af930f03",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 27103,
            "upload_time": "2025-08-08T21:12:00",
            "upload_time_iso_8601": "2025-08-08T21:12:00.117498Z",
            "url": "https://files.pythonhosted.org/packages/f7/2a/1ba6f15ab79e80121d62987e863e37327099e25664175d11f1423b6142a8/docker_mcp_sdk-0.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-08 21:12:00",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "cevatkerim",
    "github_project": "docker-mcp#readme",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "docker-mcp-sdk"
}
        
Elapsed time: 1.33273s