{"id":27919348,"url":"https://github.com/ahmed-gelemli/docker-agent-backend","last_synced_at":"2026-04-20T10:03:23.187Z","repository":{"id":291652141,"uuid":"978327751","full_name":"ahmed-gelemli/docker-agent-backend","owner":"ahmed-gelemli","description":"Lightweight, secure Docker agent with REST and WebSocket APIs for container management and real-time monitoring, built with FastAPI.","archived":false,"fork":false,"pushed_at":"2025-12-30T15:19:29.000Z","size":62,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-01-02T04:47:26.472Z","etag":null,"topics":["backend","container-management","docker","docker-compose","fastapi","mcp-server","monitoring","real-time","rest-api","websocket"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ahmed-gelemli.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-05-05T20:16:43.000Z","updated_at":"2025-12-30T15:20:20.000Z","dependencies_parsed_at":"2025-05-05T21:28:22.135Z","dependency_job_id":"d2671717-6e02-4547-9431-85938ecb3b08","html_url":"https://github.com/ahmed-gelemli/docker-agent-backend","commit_stats":null,"previous_names":["ahmed-gelemli/docker-agent-backend"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/ahmed-gelemli/docker-agent-backend","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahmed-gelemli%2Fdocker-agent-backend","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahmed-gelemli%2Fdocker-agent-backend/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahmed-gelemli%2Fdocker-agent-backend/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahmed-gelemli%2Fdocker-agent-backend/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ahmed-gelemli","download_url":"https://codeload.github.com/ahmed-gelemli/docker-agent-backend/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahmed-gelemli%2Fdocker-agent-backend/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32042294,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-20T00:18:06.643Z","status":"online","status_checked_at":"2026-04-20T02:00:06.527Z","response_time":94,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["backend","container-management","docker","docker-compose","fastapi","mcp-server","monitoring","real-time","rest-api","websocket"],"created_at":"2025-05-06T19:16:51.417Z","updated_at":"2026-04-20T10:03:23.181Z","avatar_url":"https://github.com/ahmed-gelemli.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Docker Agent Backend\n\nA lightweight, secure, and extensible backend agent built with **FastAPI** that lets you manage and monitor Docker containers remotely — via both **REST APIs** and **real-time WebSocket streaming**.\n\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)\n[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/ahmed-gelemli/docker-agent-backend)\n\n## Features\n\n- List Docker containers\n- View container details and logs\n- Start / stop / restart containers\n- Real-time log streaming via WebSocket\n- Stream live container stats\n- Docker events stream (start/stop/etc)\n- List images\n- **MCP (Model Context Protocol)** support for AI assistants\n- **API versioning** (`/api/v1/`)\n- **JWT authentication** with token expiration\n- **Rate limiting** to prevent abuse\n- **CORS** configuration\n- **Request tracing** with unique request IDs\n- **Structured logging** (JSON in production)\n- **Production-ready** Docker setup (non-root, health checks)\n\n---\n\n## API Overview\n\n\u003e **Note:** All endpoints are prefixed with `/api/v1`\n\n### Auth\n\n| Method | Endpoint            | Description                     | Auth Required |\n|--------|---------------------|---------------------------------|---------------|\n| POST   | `/api/v1/auth/login`  | Get JWT token                   | No            |\n| GET    | `/api/v1/auth/check`  | Validate token \u0026 get user info  | Yes           |\n\n### Containers\n\n| Method | Endpoint                          | Description               | Rate Limit |\n|--------|-----------------------------------|---------------------------|------------|\n| GET    | `/api/v1/containers/`             | List all containers       | 60/min     |\n| GET    | `/api/v1/containers/{id}`         | Get container details     | 60/min     |\n| GET    | `/api/v1/containers/{id}/logs`    | View container logs       | 60/min     |\n| POST   | `/api/v1/containers/{id}/start`   | Start container           | 10/min     |\n| POST   | `/api/v1/containers/{id}/stop`    | Stop container            | 10/min     |\n| POST   | `/api/v1/containers/{id}/restart` | Restart container         | 10/min     |\n\n### Stats \u0026 System\n\n| Method | Endpoint              | Description                              | Auth Required |\n|--------|-----------------------|------------------------------------------|---------------|\n| GET    | `/api/v1/stats/{id}`  | CPU, memory, network, I/O stats          | Yes           |\n| GET    | `/api/v1/version`     | Docker version, API version, OS, arch    | Yes           |\n| GET    | `/api/v1/healthz`     | Basic health check                       | No            |\n| GET    | `/api/v1/health`      | Enhanced health with system info         | Yes           |\n\n### Images\n\n| Method | Endpoint           | Description          |\n|--------|--------------------|----------------------|\n| GET    | `/api/v1/images/`  | List Docker images   |\n\n### WebSocket Endpoints\n\nReal-time streaming with JWT token passed as query parameter.\n\n| Path                                    | Description                 |\n|-----------------------------------------|-----------------------------|\n| `/api/v1/logs/ws/{id}?token=JWT`        | Stream live logs            |\n| `/api/v1/stats/ws/{id}?token=JWT`       | Stream live CPU/memory      |\n| `/api/v1/events/ws?token=JWT`           | Stream Docker events        |\n\n### MCP (Model Context Protocol)\n\nEnables AI assistants (Claude, Cursor, etc.) to interact with Docker via the MCP protocol.\n\n| Path                  | Description                              | Auth              |\n|-----------------------|------------------------------------------|-------------------|\n| `GET /mcp/sse`        | SSE endpoint for MCP connection          | API Key (Bearer)  |\n| `POST /mcp/messages/` | Handle MCP messages                      | API Key (Bearer)  |\n\n**Available MCP Tools:**\n\n| Tool                  | Description                                      |\n|-----------------------|--------------------------------------------------|\n| `docker_health`       | Get Docker daemon health and system info         |\n| `docker_version`      | Get Docker version information                   |\n| `list_containers`     | List all containers with status and ports        |\n| `get_container`       | Get detailed container info                      |\n| `get_container_logs`  | Get container logs                               |\n| `get_container_stats` | Get container CPU/memory/network stats           |\n| `list_images`         | List all Docker images                           |\n| `start_container`     | Start a stopped container                        |\n| `stop_container`      | Stop a running container                         |\n| `restart_container`   | Restart a container                              |\n\n---\n\n## Installation\n\n### Using Docker Compose (Recommended)\n\n```bash\n# Clone the repo\ngit clone https://github.com/ahmed-gelemli/docker-agent-backend.git\ncd docker-agent-backend\n\n# Create environment file\ncat \u003e .env \u003c\u003c EOF\nSECRET_KEY=$(openssl rand -base64 32)\nAPI_USERNAME=admin\nAPI_PASSWORD=your_secure_password\nEOF\n\n# Build and run\ndocker compose up --build -d\n```\n\n### Local Development\n\n```bash\n# Create virtual environment\npython -m venv venv\nsource venv/bin/activate  # Linux/Mac\n# or: venv\\Scripts\\activate  # Windows\n\n# Install dependencies\npip install -r requirements.txt\n\n# Create .env file (see Configuration section)\n\n# Run development server\npython run.py\n```\n\n---\n\n## Configuration\n\nCreate a `.env` file in the project root:\n\n```env\n# REQUIRED - Generate with: openssl rand -base64 32\nSECRET_KEY=your-secret-key-at-least-32-characters\n\n# API Credentials\nAPI_USERNAME=admin\nAPI_PASSWORD=your_secure_password\n\n# JWT Settings (optional)\nALGORITHM=HS256\nACCESS_TOKEN_EXPIRE_MINUTES=30\n\n# CORS (optional) - comma-separated origins\nCORS_ORIGINS=https://your-dashboard.com,https://another-origin.com\n\n# Rate Limiting (optional)\nRATE_LIMIT_ENABLED=true\nRATE_LIMIT_REQUESTS=100\nRATE_LIMIT_WINDOW=60\n\n# MCP Configuration\nMCP_ENABLED=true\nMCP_API_KEY=your-mcp-api-key-at-least-16-chars  # Generate with: openssl rand -base64 32\nMCP_DEBUG=false\n\n# Application (optional)\nDEBUG=false\nAPP_NAME=Docker Agent\n```\n\n---\n\n## Usage\n\n### 1. Get a JWT Token\n\n```bash\ncurl -X POST http://localhost:9000/api/v1/auth/login \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"username\": \"admin\", \"password\": \"your_password\"}'\n```\n\nResponse:\n```json\n{\n  \"access_token\": \"eyJhbGciOiJIUzI1NiIs...\",\n  \"token_type\": \"bearer\",\n  \"expires_in\": 1800\n}\n```\n\n### 2. Use the Token\n\n```bash\n# List containers\ncurl http://localhost:9000/api/v1/containers/ \\\n  -H \"Authorization: Bearer YOUR_TOKEN\"\n```\n\nResponse:\n```json\n{\n  \"containers\": [\n    {\n      \"id\": \"9a2dd44bdbed\",\n      \"name\": \"my-container\",\n      \"image\": \"nginx:latest\",\n      \"status\": \"running\",\n      \"state\": \"running\",\n      \"created\": 1735123456,\n      \"ports\": []\n    }\n  ],\n  \"total\": 1\n}\n```\n\n```bash\n# Get container details\ncurl http://localhost:9000/api/v1/containers/CONTAINER_ID \\\n  -H \"Authorization: Bearer YOUR_TOKEN\"\n```\n\nResponse:\n```json\n{\n  \"id\": \"9a2dd44bdbedabc123...\",\n  \"short_id\": \"9a2dd44bdbed\",\n  \"name\": \"my-container\",\n  \"image\": \"nginx:latest\",\n  \"status\": \"running\",\n  \"state\": {\n    \"status\": \"running\",\n    \"running\": true,\n    \"paused\": false,\n    \"pid\": 12345,\n    \"exit_code\": 0\n  },\n  \"config\": {\n    \"hostname\": \"9a2dd44bdbed\",\n    \"env\": [\"PATH=/usr/local/bin\", \"NGINX_VERSION=1.25\"],\n    \"cmd\": [\"nginx\", \"-g\", \"daemon off;\"],\n    \"labels\": {}\n  },\n  \"mounts\": [],\n  \"networks\": {\n    \"bridge\": {\n      \"ip_address\": \"172.17.0.2\",\n      \"gateway\": \"172.17.0.1\"\n    }\n  },\n  \"ports\": []\n}\n```\n\n```bash\n# Get enhanced health check\ncurl http://localhost:9000/api/v1/health \\\n  -H \"Authorization: Bearer YOUR_TOKEN\"\n```\n\nResponse:\n```json\n{\n  \"status\": \"ok\",\n  \"docker_connected\": true,\n  \"docker_version\": \"24.0.7\",\n  \"api_version\": \"1.43\",\n  \"os\": \"linux\",\n  \"arch\": \"amd64\",\n  \"containers_running\": 3,\n  \"containers_total\": 5,\n  \"images_total\": 12,\n  \"memory_total\": 16777216000,\n  \"cpus\": 8\n}\n```\n\n```bash\n# Restart a container\ncurl -X POST http://localhost:9000/api/v1/containers/CONTAINER_ID/restart \\\n  -H \"Authorization: Bearer YOUR_TOKEN\"\n```\n\n### 3. WebSocket Connection\n\n```javascript\nconst token = \"your_jwt_token\";\nconst ws = new WebSocket(`ws://localhost:9000/api/v1/logs/ws/CONTAINER_ID?token=${token}`);\n\nws.onmessage = (event) =\u003e {\n  console.log(\"Log:\", event.data);\n};\n```\n\n### 4. MCP Connection\n\nConfigure your AI assistant (Claude Desktop, Cursor, etc.) with the MCP server URL:\n\n```json\n{\n  \"mcpServers\": {\n    \"docker-agent\": {\n      \"url\": \"http://localhost:9000/mcp/sse\",\n      \"headers\": {\n        \"Authorization\": \"Bearer YOUR_MCP_API_KEY\"\n      }\n    }\n  }\n}\n```\n\nOr use the API key as a query parameter:\n\n```\nhttp://localhost:9000/mcp/sse?api_key=YOUR_MCP_API_KEY\n```\n\n---\n\n## MCP Deployment Notes\n\n### ✅ Works With\n\n| Environment                          | Status |\n|--------------------------------------|--------|\n| Single instance deployment           | ✅      |\n| Cloud VMs (EC2, DigitalOcean, etc.)  | ✅      |\n| Kubernetes (1 replica)               | ✅      |\n| Docker Compose (single container)    | ✅      |\n\n### ⚠️ Limitations\n\n| Environment                          | Issue                                        |\n|--------------------------------------|----------------------------------------------|\n| Horizontal scaling (multiple replicas) | SSE sessions are stored in-memory; needs sticky sessions |\n| Serverless (Lambda, Vercel Functions)  | SSE requires long-lived connections          |\n| Some load balancers                    | May timeout idle SSE connections (30-60s)    |\n\n### Workarounds\n\n- **Sticky Sessions**: Configure your load balancer to route the same client to the same instance\n- **Single Replica**: Deploy with `replicas: 1` if horizontal scaling isn't needed\n- **Increase Timeouts**: Configure load balancer idle timeout \u003e expected connection duration\n\n---\n\n## Future TODOs\n\n- [ ] Add `StreamableHTTP` transport for stateless MCP (better scaling support)\n- [ ] Redis-backed session store for multi-instance deployments\n- [ ] MCP tool for `docker exec` commands\n- [ ] MCP tool for pulling images\n- [ ] MCP tool for creating/removing containers\n- [ ] MCP prompts and resources support\n\n---\n\n## Security \u0026 Observability\n\n| Feature | Description |\n|---------|-------------|\n| **API Versioning** | All endpoints prefixed with `/api/v1` for future compatibility |\n| **JWT Auth** | Tokens expire after 30 minutes (configurable) |\n| **Rate Limiting** | Auth: 5/min, Actions: 10/min, Reads: 60/min |\n| **CORS** | Configurable allowed origins |\n| **Request Tracing** | Every response includes `X-Request-ID` and `X-Process-Time` headers |\n| **Structured Logging** | JSON logs in production, colored output in debug mode |\n| **Non-root Container** | Runs as `dockeragent` user |\n| **No Stack Traces** | Errors don't leak internal details |\n| **Health Checks** | Basic (`/healthz`) and enhanced (`/health`) endpoints |\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fahmed-gelemli%2Fdocker-agent-backend","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fahmed-gelemli%2Fdocker-agent-backend","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fahmed-gelemli%2Fdocker-agent-backend/lists"}