Skip to main content

docker-tiny-mcp

An MCP server for Docker, built on aiohttp-tiny-mcp.

It began as the worked example of a complete server in that repository: a real client library underneath, a real store and event source, a command line, and tests that run where Docker is not installed. Every protocol revision the package speaks is served by the same handlers.

Running it

uvx --from docker-tiny-mcp docker-tiny-mcp         # http://127.0.0.1:8080/mcp
uv run docker-tiny-mcp --stdio               # for a locally-installed client
uv run docker-tiny-mcp --port 9000 --state /var/lib/docker-tiny-mcp/state.sqlite3

Every setting can also come from the environment or a config file. Three files are read where they exist: /etc/docker/mcp.ini, then ~/.config/docker/mcp.ini, then .docker-tiny-mcp.ini in this directory, each overriding the one before. --config FILE overrides all three. The order of precedence is defaults, then those files, then DOCKER_TINY_MCP_*, then the command line:

DOCKER_TINY_MCP_PORT=9000 DOCKER_TINY_MCP_STATE=/tmp/state.sqlite3 uv run docker-tiny-mcp

--help lists everything, including which environment variable each setting reads. --generate-config writes every setting, its help and its default to a config file, so a deployment edits that file instead of a command line:

uv run docker-tiny-mcp --generate-config /etc/docker/mcp.ini
uv run docker-tiny-mcp --generate-config -        # to standard output

Top-level settings go under [DEFAULT], and a group of settings has its own section, such as [jwt]. A list is written as a Python literal, in the config file and in the environment alike:

allowed_origin = ["https://docker.example.com"]
DOCKER_TINY_MCP_ALLOWED_ORIGIN='["https://docker.example.com"]' uv run docker-tiny-mcp

Open /console to browse the MCP catalogue. Clients on MCP 2025-11-25 or 2026-07-28 receive light and dark icons for the server and its catalogue entries.

For an HTTP client that lacks native prompts, add prompts=resource to the endpoint URL. For a client that can only call tools, add resources=tool to list and read resources and prompts with mcp_resources_list and mcp_resources_read. Over stdio, use --stdio-prompts resource or --stdio-resources tool respectively.

Unprivileged mode

Enable runtime checks for host access with --unprivileged:

uv run docker-tiny-mcp --unprivileged
uv run docker-tiny-mcp --unprivileged --network sandbox

The create tool hides and rejects network. Its volumes argument accepts only named volumes, such as data:/data, data:/data:rw or data:/data:ro. Host paths, Docker socket mounts, extra mount flags and unknown creation arguments are rejected. Missing named volumes are created with the local driver. Existing volumes must use local without driver options, because volume options can mount host paths. Named volumes persist after their containers are removed.

For example, call create with:

{"image": "redis:7-alpine", "name": "cache", "volumes": ["cache-data:/data"]}

Before reading a file resource or calling read, write, exec, start or restart, the server inspects the target container. It rejects host mounts, extra capabilities or devices, shared host namespaces, custom runtimes and relaxed security settings. New containers use no-new-privileges and the default bridge network unless the operator selects another local bridge network or none. Published ports remain available.

Equivalent settings are DOCKER_TINY_MCP_UNPRIVILEGED=true or unprivileged=true in the config file. Python callers can use build(registry, client, unprivileged=True).

This mode restricts Docker configuration exposed through MCP. It does not filter container network traffic, provide per-user volume isolation or protect against Docker/kernel vulnerabilities and concurrent changes by another Docker administrator. Use a dedicated daemon for untrusted workloads.

Fixed network

--network NAME works independently of --unprivileged:

uv run docker-tiny-mcp --network sandbox

The network must already exist. The server uses it for new containers, hides and rejects create.network, omits the networks tool and removes networks from prune.what. This option does not enable unprivileged mode.

Equivalent settings are DOCKER_TINY_MCP_NETWORK=sandbox or network=sandbox in the config file. Python callers can use build(registry, client, network="sandbox"). Add --unprivileged separately when both restrictions are needed.

Authentication

--jwt-psk verifies an HS256 JWT on every HTTP request. The audience is this endpoint's public URL: a token must name it, and the endpoint publishes it as its protected resource.

uv run docker-tiny-mcp --jwt-psk "$KEY" \
    --jwt-audience https://docker.example.com/mcp \
    --jwt-issuer https://docker.example.com

The key needs at least 32 bytes. It is a secret argument: its repr is ******, so a log of the settings does not hold it. The config file or DOCKER_TINY_MCP_JWT_PSK keeps it out of the command line, which another user on the machine can read. --jwt-issuer is optional; an empty issuer accepts a token from any issuer.

These three settings are one group, and the config file holds them in one section:

[jwt]
psk = a-key-of-at-least-32-random-bytes
audience = https://docker.example.com/mcp
issuer = https://docker.example.com

Mint a token with the same key, and send it as Authorization: Bearer <token>:

import time

import jwt

from docker_tiny_mcp.__main__ import Parser, authentication

key = "replace-this-example-key-with-32-random-bytes"
parser = Parser()
parser.parse_args(
    [
        "--jwt-psk",
        key,
        "--jwt-audience",
        "https://docker.example.com/mcp",
        "--jwt-issuer",
        "https://docker.example.com",
    ]
)
auth = authentication(parser)

token = jwt.encode(
    {
        "sub": "laptop",
        "iss": "https://docker.example.com",
        "aud": "https://docker.example.com/mcp",
        "exp": time.time() + 86400,
    },
    key,
    algorithm="HS256",
)
assert (await auth.principal(f"Bearer {token}")).subject == "laptop"

--jwt-query-token accepts the token query argument if the Authorization header is empty or missing.

https://docker.example.com/mcp?token=<token>

A nonempty header takes precedence. The option is off by default because the URL can carry credentials into browser history, saved client settings, and logs that keep the query. The aiohttp access log writes token=[REDACTED].

A token expires, and the server rejects one without exp. Revocation is collective: replace the key and restart the server. This is a credential on the wire, so terminate TLS in front of the server. The policy protects the MCP route; the console page itself stays public and asks for the token in its dialog. --stdio ignores the key, because one process serves one caller.

Other deployments need other identity: Registry(auth=...) also takes Basic authentication, an OAuth protected resource, or a policy of your own. See authentication.

What it offers

Enough on its own. An agent given this server and nothing else can find a container, read its files and its log, run a command in it, change it, and start a new one.

Tool Does
containers List containers, filtered by name and by whether they run
logs What it wrote, dated, with a cursor for reading only what is new
images Images with sizes, and what still holds each one
networks, volumes What is attached, and what mounts what
events What the daemon did lately: started, died, removed
stats Processor, memory, network and disk, as rates
create Make one and start it -- docker run, with the flags named
create_volume Create a local named volume with a description shown by volumes
remove_volume Remove one volume and its data after confirmation. Docker refuses if a container uses it
commit Save a stopped container as a localhost/ image with a description
start, stop, restart The obvious things, reporting the state that followed
wait Hold until it is running, stopped, or healthy
exec Run a command inside it -- asks unless the command only reads
read Read a complete file from a running or stopped container
write Put a file into it, running or not
remove, remove_image, prune Reclaim space -- each asks first
pull Download an image, reporting progress

Call read with container and an absolute path. It returns UTF-8 text, an image block, or an embedded resource with the binary file. The server detects PNG, JPEG, GIF, WebP, PDF, ZIP and gzip by signature. Other binary files use application/octet-stream.

You can also read the complete file through docker://containers/{name}/files{+path}. For example, use docker://containers/cache/files/tmp/screenshot.png for /tmp/screenshot.png. Percent-encode URI delimiters such as # and ? in filenames.

By default, create runs Docker's init as PID 1 to reap orphaned processes. This helps when sleep infinity keeps the container running and exec starts background services. Set init=false if the container command must run as PID 1. The docker://containers/{name} resource reports the configured value.

Set shm_size on create to size /dev/shm in MiB. Docker normally uses 64 MiB when the field is omitted. The server limits explicit sizes to 1024 MiB by default. Set --max-shm-size, DOCKER_TINY_MCP_MAX_SHM_SIZE, or max_shm_size in the config file to change that limit. The container details resource reports the size in MiB.

To reuse a prepared container, write /AGENTS.md at its root, stop the container and call commit with an image name such as dev-env:v1 and a description. The image appears in images as localhost/dev-env:v1. Set overwrite=true to replace an existing tag. Read /AGENTS.md from a new container before using the image. The image keeps environment values and files that may contain credentials. Mounted volume data is excluded.

The shared SQLite state file coordinates concurrent MCP operations on the same container or image tag. A reservation can last up to one hour after a timeout or interrupted request. Direct commands to the Docker daemon bypass these reservations.

Resources: docker://info, docker://containers, docker://containers/{name}, docker://containers/{name}/logs, docker://images.

On MCP 2026-07-28, clients may privately cache catalogue listings for 60 seconds and docker://containers/{name} for 5 seconds. File and log reads have a cache lifetime of zero.

Prompts: diagnose for a container that misbehaves, reclaim for finding space. Container and image names are suggested while either is filled in.

The parts worth copying

Handlers are plain functions. Nothing in tools/ knows about a registry. Each is a coroutine over a connected aiodocker.Docker, so a test calls it directly:

from docker_tiny_mcp import tools
from docker_tiny_mcp.models import ContainerFilter


async def show(client):
    listed = await tools.containers(ContainerFilter(all=True), client)
    return [item.name for item in listed.containers]

One file per tool, holding the whole tool. tools/stats.py has the two samples, the arithmetic between them, and the handler -- open it and there is nothing else to find. Nothing was factored out for its own sake: a helper moves to daemon.py only where a second tool calls it, which is true of six functions in all.

daemon.py         what more than one tool asks the daemon
tools/            one file per tool, plus results.py
resources/        addressed rather than called
resources/templates/   the ones whose address a client fills in

What a tool may do is read from its signature, not from where its file sits. A handler taking only (args, client) changes nothing and can ask nobody; one taking ex: Exchange may put a question; one taking policy: Policy may destroy something. That is one place to look, and it is in the file already.

There is no wrapper around the daemon. aiodocker.Docker is the connection, the application opens one and hands it to the registry, and a handler takes it as client: Docker. Several functions in daemon.py never see it at all -- a container reads its own log -- which a wrapper hid.

templates/ is apart because a fixed resource can be listed and subscribed to, a template cannot be listed at all, and a client only discovers that difference by failing.

server.py registers handlers and selects deployment restrictions. safety.py checks Docker configuration at runtime in unprivileged mode:

from aiodocker import Docker
from aiohttp_tiny_mcp import MemoryHub, MemorySessionStore, Registry

from docker_tiny_mcp.server import build

# `build` says what is offered and nothing else. Reading it is reading the
# whole surface -- the daemon is never asked anything until a tool is called.
client = Docker()
try:
    registry = build(
        Registry("docker", "0.1.0", hub=MemoryHub(), session_store=MemorySessionStore()),
        client,
    )
    assert {"containers", "logs", "exec", "write", "create"} <= set(registry.tools)
finally:
    await client.close()

Asking is rationed, and the deployment sets the rate. A server that asks before everything is a server whose questions nobody reads -- and there is usually a host in front of this one asking its own permission for every call, so a second question buys only the habit of clicking through both. Four things cut it down, in order: a policy decides which actions are worth a question at all, a command that only reads skips confirmation by default, an answer that said "do not ask again" is honoured, and what is left asks once.

uv run docker-tiny-mcp                      # asks only before what cannot be undone
uv run docker-tiny-mcp --confirm never      # disables default confirmations
uv run docker-tiny-mcp --confirm changes    # also asks before create, write and non-overwriting commit

Under the default, create and write do not interrupt: creating is undone by removing, and a file written into a container goes away with it. remove, remove_image, remove_volume, prune and a command that is not merely reading do:

from docker_tiny_mcp.consent import Policy, only_reads

assert only_reads(["cat", "/etc/hosts"])
assert not only_reads(["sh", "-c", "rm -rf /"])
assert not only_reads(["find", "/app", "-delete"])

assert Policy().asks("remove") and not Policy().asks("write")
assert not Policy("never").asks("remove")
assert Policy("changes").asks("write")

Override the policy for any Docker tool in [confirm]. Set a tool to ask to require approval or to allow to skip it. An omitted tool uses the global mode. An explicit exec = ask also asks before read-only commands. Every confirmation asks again; set a tool to allow to stop the questions.

[confirm]
mode = destructive
remove_volume = ask
read = allow

Use --confirm-remove-volume ask or set DOCKER_TINY_MCP_CONFIRM_REMOVE_VOLUME=ask to set the same flag. Existing [DEFAULT] keys named confirm still set the global mode.

ex.ask reaches a client through MRTR on 2026-07-28, a pushed request on 2025-11-25 and 2025-06-18, and the tool call itself on 2025-03-26. The handler says one line and knows none of that.

Failures are said in words, not status numbers. errors.py translates Docker failures. A command sent to a stopped container came back as DockerError: [409] container 3156cbe0b5f6... is not running, which names an id nobody typed and does not say what to do:

import pytest
from aiodocker.exceptions import DockerError

from docker_tiny_mcp.errors import NotRunning, clear


async def check():
    with pytest.raises(NotRunning, match="Start it first"):
        async with clear("running a command", subject="cache"):
            raise DockerError(409, "container 3156cbe0b5f6 is not running")

A change reports the state that followed it. Docker answers start before the process is up, so a container that starts and dies at once would be reported as started. Every changing tool reads the state a moment later, and says what went differently:

from docker_tiny_mcp import tools

done = tools.outcome("web", "start", {"Status": "exited", "ExitCode": 3}, "running")
assert done.exit_code == 3
assert "did not stay running" in done.note

The application owns the connection. __main__.py opens one aiodocker.Docker, hands it over with registry.provide_instance(client), and closes it on the way out. No lazy opening, no second lifetime to keep in step with the first:

client = Docker(url=parser.docker_url) if parser.docker_url else Docker()
return build(registry, client, parser.confirm.policy()), storage, client

State is SQLite. aiohttp_tiny_mcp.storage.sqlite holds the sessions and the events in one file, which is what several workers on one machine share. This example used to carry its own copy of that; the package ships it now, and aiohttp-tiny-mcp[sqlite] is what brings it. Across machines the same two contracts are served by aiohttp_tiny_mcp.storage.redis or .postgres.

The daemon's own events become notifications. A container that dies is published to the hub, and whoever subscribed hears about it.

Tests

uv sync --all-groups
uv run pytest

They need no Docker. tests/fake_docker.py is an aiohttp application answering the endpoints these tools use, so the real aiodocker, the real SQLite store, the real endpoint and a real MCP client are all exercised -- only the daemon is a stand-in.

Two layers, deliberately:

  • test_functions.py calls the handlers directly. Fast, and it says what broke.
  • test_reading.py, test_changing.py and test_events.py drive a real client over HTTP, once per protocol revision where the revision matters.
  • test_real_daemon.py lives one container end to end against a real daemon: create, wait, exec, write, read, logs, stats, events, stop, remove. It is skipped where Docker is not reachable, and it is what caught since on the log endpoint taking a Unix timestamp while every line it returns is dated RFC 3339.

To run against a real daemon instead, point the tests at it:

DOCKER_TINY_MCP_DOCKER_URL=unix:///var/run/docker.sock uv run pytest -k real

Metadata

Release files for docker-tiny-mcp 0.2.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for docker-tiny-mcp 0.2.3
File Size Uploaded Provenance Actions
docker_tiny_mcp-0.2.3.tar.gz 58.6 kB With provenance Details for docker_tiny_mcp-0.2.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for docker-tiny-mcp 0.2.3
File Interpreter ABI Platform Actions
docker_tiny_mcp-0.2.3-py3-none-any.whl Python 3 none any Details for docker_tiny_mcp-0.2.3-py3-none-any.whl

Total release size: 128.2 kB

Release files / docker_tiny_mcp-0.2.3.tar.gz

Download URL docker_tiny_mcp-0.2.3.tar.gz
Size 58.6 kB
Tags Source
SHA-256 checksum
How to use checksums
7813ffe885bde8b7d4b8db87a114b0420d6b067af20f8e0bc0c147f3af8404be
BLAKE2b-256 checksum
How to use checksums
9a95be077d9390a885a0fe53cddb32c4a89b54072f0332e428bf076154165acb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Release files / docker_tiny_mcp-0.2.3-py3-none-any.whl

Download URL docker_tiny_mcp-0.2.3-py3-none-any.whl
Size 69.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
829c880448b4d47d16c5ffd55bee346f45b435e7c4c05c901daa0d3e49b6309a
BLAKE2b-256 checksum
How to use checksums
b96f418186d58c24b73289ee367c9f674a7a1af1f67413997ca6d5e899cd8589
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Security for docker-tiny-mcp 0.2.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for docker_tiny_mcp-0.2.3.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page