Model Context Protocol server for Docker management with AI assistants
Project description
MCP Docker Server
| Category | Status |
|---|---|
| Build & CI | |
| SonarQube | |
| Security | |
| Package | |
| Technology | |
| Documentation |
A Model Context Protocol (MCP) server that exposes Docker functionality to AI assistants like Claude. Manage containers, images, networks, and volumes through a type-safe, documented API with safety controls.
Features
- 36 Docker Tools: Complete container, image, network, volume, and system management
- 5 AI Prompts: Intelligent troubleshooting, optimization, networking debug, and security analysis
- 2 Resources: Real-time container logs and resource statistics
- Type Safety: Full type hints with Pydantic validation and mypy strict mode
- Safety Controls: Three-tier safety system (safe/moderate/destructive) with configurable restrictions
- Comprehensive Testing: Extensive test coverage with unit, integration, E2E, and fuzz tests
- Continuous Fuzzing: ClusterFuzzLite integration for security and robustness (OpenSSF Scorecard compliant)
- Modern Python: Built with Python 3.11+, uv package manager, and async-first design
Quick Start
Prerequisites
- Python 3.11+ and Docker installed
- uv package manager (recommended)
Installation
Run directly with uvx (no installation needed):
uvx mcp-docker
For detailed installation options (pip, from source, development setup), see docs/SETUP.md.
Configuration
Basic configuration:
# Linux/macOS (default)
export DOCKER_BASE_URL="unix:///var/run/docker.sock"
# Windows
export DOCKER_BASE_URL="npipe:////./pipe/docker_engine"
# Safety (default: moderate operations allowed, destructive blocked)
export SAFETY_ALLOW_DESTRUCTIVE_OPERATIONS=false
For all configuration options (Docker, safety, logging, security), see docs/SETUP.md.
Claude Desktop Setup
Add to your claude_desktop_config.json:
{
"mcpServers": {
"docker": {
"command": "uvx",
"args": ["mcp-docker"]
}
}
}
Note: Authentication is not needed for local Claude Desktop use (stdio transport). The security model is the same as running docker commands directly on your machine.
For Remote Access: SSH key-based authentication is required for SSE transport over the network. Anthropic's Remote Connectors (paid plans) require OAuth, which is not currently implemented. For direct SSE clients, use SSH authentication. See SECURITY.md and docs/SETUP.md for details.
For platform-specific configuration, Windows setup, custom environments, and troubleshooting, see docs/SETUP.md.
Advanced Usage
SSE Transport with TLS
For network-accessible deployments, use SSE transport with TLS/HTTPS:
# Production: Use the startup script with TLS
./start-mcp-docker-sse.sh
# Development: Run with SSE transport (no TLS)
mcp-docker --transport sse --host 127.0.0.1 --port 8000
Command-line options: --transport (stdio/sse), --host, --port
Security
The MCP Docker server includes comprehensive security features for production deployments:
Key Security Features
- TLS/HTTPS: Encrypted transport for SSE mode (required for production)
- Authentication: SSH key-based authentication for remote access
- Rate Limiting: Prevent abuse (60 req/min default, auth failures limited)
- Audit Logging: Track all operations with client IPs
- IP Filtering: Restrict access by network address
- Error Sanitization: Prevent information disclosure
- Security Headers: OWASP-recommended headers via
securelibrary (HSTS, CSP, X-Frame-Options, etc.)
⚠️ Important Security Considerations
Retrieval Agent Deception (RADE) Risk: Container logs are returned unfiltered and may contain malicious prompts injected by untrusted containers. AI agents retrieving logs via docker_container_logs could be manipulated by these embedded instructions.
Mitigation:
- Treat container logs as untrusted user input
- Implement content filtering before presenting logs to AI agents
- Use read-only mode for untrusted containers
- Review audit logs for suspicious patterns
See SECURITY.md for the complete MCP threat model and mitigation strategies.
Quick Production Setup
# Generate certificates
./scripts/generate-certs.sh
# Start with all security features enabled
./start-mcp-docker-sse.sh
# Test security configuration
./test-mcp-sse.sh
Security Configuration
# TLS/HTTPS
MCP_TLS_ENABLED=true
MCP_TLS_CERT_FILE=~/.mcp-docker/certs/cert.pem
MCP_TLS_KEY_FILE=~/.mcp-docker/certs/key.pem
# Authentication
SECURITY_AUTH_ENABLED=true
SECURITY_SSH_AUTH_ENABLED=true
SECURITY_SSH_AUTHORIZED_KEYS_FILE=~/.mcp-docker/authorized_keys
# Rate Limiting
SECURITY_RATE_LIMIT_ENABLED=true
SECURITY_RATE_LIMIT_RPM=60
For complete security documentation, production deployment checklist, and best practices, see SECURITY.md.
Tools Overview
The server provides 36 tools organized into 5 categories:
Container Management (10 tools)
docker_list_containers- List containers with filtersdocker_inspect_container- Get detailed container infodocker_create_container- Create new containerdocker_start_container- Start containerdocker_stop_container- Stop container gracefullydocker_restart_container- Restart containerdocker_remove_container- Remove containerdocker_container_logs- Get container logsdocker_exec_command- Execute command in containerdocker_container_stats- Get resource usage stats
Image Management (9 tools)
docker_list_images- List imagesdocker_inspect_image- Get image detailsdocker_pull_image- Pull from registrydocker_build_image- Build from Dockerfiledocker_push_image- Push to registrydocker_tag_image- Tag imagedocker_remove_image- Remove imagedocker_prune_images- Clean unused imagesdocker_image_history- View layer history
Network Management (6 tools)
docker_list_networks- List networksdocker_inspect_network- Get network detailsdocker_create_network- Create networkdocker_connect_container- Connect container to networkdocker_disconnect_container- Disconnect from networkdocker_remove_network- Remove network
Volume Management (5 tools)
docker_list_volumes- List volumesdocker_inspect_volume- Get volume detailsdocker_create_volume- Create volumedocker_remove_volume- Remove volumedocker_prune_volumes- Clean unused volumes
System Tools (6 tools)
docker_system_info- Get Docker system informationdocker_system_df- Disk usage statisticsdocker_system_prune- Clean all unused resourcesdocker_version- Get Docker version infodocker_events- Stream Docker eventsdocker_healthcheck- Check Docker daemon health
Prompts
Five prompts help AI assistants work with Docker:
- troubleshoot_container - Diagnose container issues with logs and configuration analysis
- optimize_container - Get optimization suggestions for resource usage and security
- generate_compose - Generate docker-compose.yml from containers or descriptions
- debug_networking - Deep-dive analysis of container networking problems with systematic L3-L7 troubleshooting
- security_audit - Comprehensive security analysis following CIS Docker Benchmark with compliance mapping
Resources
Two resources provide real-time access to container data:
- container://logs/{container_id} - Stream container logs
- container://stats/{container_id} - Get resource usage statistics
Safety System
The server implements a three-tier safety system with configurable operation modes:
Operation Safety Levels
-
SAFE - Read-only operations (list, inspect, logs, stats)
- No restrictions
- Always allowed
- Examples:
docker_list_containers,docker_inspect_image,docker_container_logs
-
MODERATE - State-changing but reversible (start, stop, create)
- Can modify system state
- Controlled by
SAFETY_ALLOW_MODERATE_OPERATIONS(default:true) - Examples:
docker_create_container,docker_start_container,docker_pull_image
-
DESTRUCTIVE - Permanent changes (remove, prune)
- Cannot be easily undone
- Requires
SAFETY_ALLOW_DESTRUCTIVE_OPERATIONS=true - Can require confirmation
- Examples:
docker_remove_container,docker_prune_images,docker_system_prune
Safety Modes
Configure the safety mode using environment variables:
Read-Only Mode (Safest) - Monitoring and observability only
SAFETY_ALLOW_MODERATE_OPERATIONS=false
SAFETY_ALLOW_DESTRUCTIVE_OPERATIONS=false
- ✅ List, inspect, logs, stats
- ❌ Create, start, stop, pull
- ❌ Remove, prune
Default Mode (Balanced) - Development and operations
SAFETY_ALLOW_MODERATE_OPERATIONS=true # or omit (default)
SAFETY_ALLOW_DESTRUCTIVE_OPERATIONS=false
- ✅ List, inspect, logs, stats
- ✅ Create, start, stop, pull
- ❌ Remove, prune
Full Mode (Least Restrictive) - Infrastructure management
SAFETY_ALLOW_MODERATE_OPERATIONS=true
SAFETY_ALLOW_DESTRUCTIVE_OPERATIONS=true
- ✅ List, inspect, logs, stats
- ✅ Create, start, stop, pull
- ✅ Remove, prune
Note: Read-only mode is ideal for monitoring, auditing, and observability use cases where no changes to Docker state should be allowed.
MCP Server vs. Docker CLI: An Honest Comparison
Should you use this MCP server or just let Claude run docker commands directly? Here's an honest assessment:
Using Docker CLI Directly
Pros:
- ✅ Simpler setup - No MCP server needed, works immediately
- ✅ Full Docker access - Every Docker feature available
- ✅ No maintenance - No additional service to run or update
- ✅ Transparent - See exactly what commands run
- ✅ Familiar - Standard Docker commands everyone knows
Cons:
- ❌ No safety controls - Can't restrict destructive operations programmatically
- ❌ Text parsing - Claude must parse unstructured CLI output
- ❌ Less efficient - Multiple commands needed for complex operations
- ❌ No audit trail - Unless you implement your own logging
- ❌ No rate limiting - Claude can run unlimited commands
- ❌ Error handling - Parsing error messages from text output
- ❌ Command injection risk - If Claude constructs commands incorrectly
Example:
# Claude needs multiple commands for a complex operation
docker ps --filter "status=running" --format json
docker inspect container_id
docker logs container_id --tail 100
# Parse JSON, extract data, reason about it...
Using MCP Docker Server
Pros:
- ✅ Enables Docker in Claude Desktop - Claude Desktop has no CLI access, so MCP is the only way to use Docker
- ✅ Safety controls - Programmable restrictions (read-only mode, block destructive ops)
- ✅ Structured data - JSON input/output, easier for AI to process
- ✅ Efficient - One tool call can do what requires multiple CLI commands
- ✅ Input validation - Pydantic models prevent malformed requests
- ✅ Audit logging - Track all operations with timestamps and client info
- ✅ Rate limiting - Prevent runaway operations
- ✅ Better errors - Structured error responses with error types
- ✅ Contextual - AI prompts guide Claude on what tools do
Cons:
- ❌ Setup required - Install, configure, and maintain the server
- ❌ Limited coverage - Only 36 tools (doesn't expose every Docker feature)
- ❌ Abstraction layer - Another component in the stack
- ❌ Learning curve - Need to understand MCP protocol and tool schemas
- ❌ Debugging - Harder to see what's happening under the hood
Example:
// One tool call with structured input/output
{
"tool": "docker_list_containers",
"arguments": {
"all": true,
"filters": {"status": ["running"]}
}
}
// Returns clean JSON with exactly the data needed
When to Use Each
Use Docker CLI directly if:
- You're using Claude Code (Claude Desktop has no CLI access)
- You need a Docker feature not exposed by the MCP server
- You want minimal setup and maximum simplicity
- You're comfortable with Claude having full Docker access
- You're doing one-off tasks where safety controls aren't important
- You trust the AI agent completely
Use MCP Docker Server if:
- You're using Claude Desktop (only way to access Docker)
- You want safety controls (read-only mode, block destructive operations)
- You need audit logging for compliance or debugging
- You want structured input/output for better AI reasoning
- You're building production automation with AI agents
- You need rate limiting to prevent runaway operations
- You want to restrict access to specific operations
- Multiple users/agents need different permission levels
Hybrid Approach
You can use both:
- MCP server for common, safe operations (list, inspect, logs, stats)
- Docker CLI for advanced features not in the MCP server (BuildKit, plugins, swarm)
- Safety: Keep destructive operations disabled in MCP, require explicit CLI commands for those
Bottom Line
For Claude Desktop users: MCP server is required (no CLI access available).
For Claude Code users:
- Learning/exploration: Docker CLI is simpler
- Production automation: MCP server provides safety, structure, and control
- Maximum flexibility: Use both as needed
The MCP server doesn't replace the Docker CLI - it provides a safer, more structured interface when you need it.
Documentation
- Security Guide - Security features, TLS/HTTPS, authentication, production checklist
- API Reference - Complete tool documentation with examples
- Setup Guide - Installation, configuration, and troubleshooting
- Usage Examples - Practical usage scenarios
- Testing Guide - Testing strategy and running tests
- Architecture - Design principles and implementation
Development
Setup Development Environment
# Clone repository
git clone https://github.com/williajm/mcp_docker.git
cd mcp_docker
# Install dependencies
uv sync --group dev
# Run tests
uv run pytest
# Run linting
uv run ruff check src tests
uv run ruff format src tests
# Run type checking
uv run mypy src tests
Running Tests
The project includes four levels of testing: unit, integration, end-to-end (E2E), and fuzz tests.
Test Level Comparison
| Aspect | Unit Tests | Integration Tests | E2E Tests | Fuzz Tests |
|---|---|---|---|---|
| Docker Daemon | ❌ Not required | ✅ Required | ✅ Required | ❌ Not required |
| Docker Operations | ❌ None | ✅ Real operations | ✅ Real operations | ❌ None |
| Server Instance | ❌ None / Mocked | ✅ Real MCPDockerServer | ✅ Real MCPDockerServer | ❌ Component-level |
| MCP Client | ❌ None | ❌ Direct server calls | ✅ Real ClientSession | ❌ None |
| Transport Layer | ❌ None | ❌ Bypassed | ✅ Real stdio/SSE | ❌ None |
| Purpose | Logic/validation | Component integration | Full workflows | Security/robustness |
| Speed | ⚡ Very fast (<5s) | ⚡ Fast (~10s) | 🐌 Slower (~30-60s) | ⚡ Continuous (CI) |
Running Different Test Levels
# Run all tests with coverage
uv run pytest --cov=mcp_docker --cov-report=html
# Run unit tests only (fast, no Docker required)
uv run pytest tests/unit/ -v
# Run integration tests (requires Docker)
uv run pytest tests/integration/ -v -m integration
# Run E2E tests (requires Docker, comprehensive)
uv run pytest tests/e2e/ -v -m e2e
# Run E2E tests excluding slow tests
uv run pytest tests/e2e/ -v -m "e2e and not slow"
# Run fuzz tests locally (requires atheris)
python3 tests/fuzz/fuzz_ssh_auth.py -atheris_runs=10000
python3 tests/fuzz/fuzz_validation.py -atheris_runs=10000
Fuzzing
The project uses ClusterFuzzLite for continuous fuzzing to meet OpenSSF Scorecard requirements. Fuzz tests run automatically in CI/CD to discover security vulnerabilities and edge cases. See docs/FUZZING.md for details.
Project Structure
mcp_docker/
├── src/
│ └── mcp_docker/
│ ├── __main__.py # Entry point
│ ├── server.py # MCP server implementation
│ ├── config.py # Configuration management
│ ├── docker/ # Docker SDK wrapper
│ ├── tools/ # MCP tool implementations
│ ├── resources/ # MCP resource providers
│ ├── prompts/ # MCP prompt templates
│ └── utils/ # Utilities (logging, validation, safety)
├── tests/ # Test suite
├── docs/ # Documentation
└── pyproject.toml # Project configuration
Requirements
- Python: 3.11 or higher
- Docker: Any recent version (tested with 20.10+)
- Dependencies:
mcp>=1.2.0- MCP SDKdocker>=7.1.0- Docker SDK for Pythonpydantic>=2.0.0- Data validationloguru>=0.7.0- Loggingsecure>=1.0.1- Security headerscryptography>=41.0.0- SSH authenticationlimits>=5.6.0- Rate limiting
Code Standards
- Follow PEP 8 style guidelines
- Use type hints for all functions
- Write docstrings (Google style)
- Maintain high test coverage
- Pass all linting and type checking
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
- Built with the Model Context Protocol by Anthropic
- Uses the official Docker SDK for Python
- Powered by modern Python tooling: uv, ruff, mypy, pytest
Roadmap
- Docker Swarm operations
- Remote Docker host support
- Enhanced streaming (build/pull progress)
- WebSocket transport option
- Docker Scout integration
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file mcp_docker-1.0.2.tar.gz.
File metadata
- Download URL: mcp_docker-1.0.2.tar.gz
- Upload date:
- Size: 314.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7806fe804c163e3dfe9d422817ebc110debdcffd77bc9460c4fd6ff3262c7e9f
|
|
| MD5 |
7fbbb10b21c52ea5f1accd385b86619a
|
|
| BLAKE2b-256 |
b4c519eb47f8b5eeb2905d082d57586167b78db290c1caefd73490545d3ce668
|
Provenance
The following attestation bundles were made for mcp_docker-1.0.2.tar.gz:
Publisher:
release.yml on williajm/mcp_docker
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
mcp_docker-1.0.2.tar.gz -
Subject digest:
7806fe804c163e3dfe9d422817ebc110debdcffd77bc9460c4fd6ff3262c7e9f - Sigstore transparency entry: 693441103
- Sigstore integration time:
-
Permalink:
williajm/mcp_docker@8a8e0f6ca95ff9e3ac3cb9ccf3bb05512cbf886e -
Branch / Tag:
refs/tags/v1.0.2 - Owner: https://github.com/williajm
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@8a8e0f6ca95ff9e3ac3cb9ccf3bb05512cbf886e -
Trigger Event:
release
-
Statement type:
File details
Details for the file mcp_docker-1.0.2-py3-none-any.whl.
File metadata
- Download URL: mcp_docker-1.0.2-py3-none-any.whl
- Upload date:
- Size: 102.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f372a50ec2bac3562947c9a7d0d5cb07ee99423a18bb3b14daf04f4376ee83c6
|
|
| MD5 |
aad3ded056f677ccd490958fdc3d0763
|
|
| BLAKE2b-256 |
34fb485500a1dc5da1eb0a1355aad08097c8617efb2a90f91a7b3c7ad2a97fbf
|
Provenance
The following attestation bundles were made for mcp_docker-1.0.2-py3-none-any.whl:
Publisher:
release.yml on williajm/mcp_docker
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
mcp_docker-1.0.2-py3-none-any.whl -
Subject digest:
f372a50ec2bac3562947c9a7d0d5cb07ee99423a18bb3b14daf04f4376ee83c6 - Sigstore transparency entry: 693441132
- Sigstore integration time:
-
Permalink:
williajm/mcp_docker@8a8e0f6ca95ff9e3ac3cb9ccf3bb05512cbf886e -
Branch / Tag:
refs/tags/v1.0.2 - Owner: https://github.com/williajm
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@8a8e0f6ca95ff9e3ac3cb9ccf3bb05512cbf886e -
Trigger Event:
release
-
Statement type: