docker-tiny-mcp 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. docker_tiny_mcp/__init__.py +1 -0
  2. docker_tiny_mcp/__main__.py +280 -0
  3. docker_tiny_mcp/consent.py +252 -0
  4. docker_tiny_mcp/daemon.py +71 -0
  5. docker_tiny_mcp/errors.py +89 -0
  6. docker_tiny_mcp/events.py +51 -0
  7. docker_tiny_mcp/models.py +444 -0
  8. docker_tiny_mcp/prompts.py +58 -0
  9. docker_tiny_mcp/resources/__init__.py +15 -0
  10. docker_tiny_mcp/resources/containers.py +13 -0
  11. docker_tiny_mcp/resources/images.py +13 -0
  12. docker_tiny_mcp/resources/info.py +13 -0
  13. docker_tiny_mcp/resources/templates/__init__.py +11 -0
  14. docker_tiny_mcp/resources/templates/container.py +13 -0
  15. docker_tiny_mcp/resources/templates/logs.py +14 -0
  16. docker_tiny_mcp/safety.py +156 -0
  17. docker_tiny_mcp/server.py +115 -0
  18. docker_tiny_mcp/tools/__init__.py +57 -0
  19. docker_tiny_mcp/tools/container.py +104 -0
  20. docker_tiny_mcp/tools/containers.py +44 -0
  21. docker_tiny_mcp/tools/create.py +210 -0
  22. docker_tiny_mcp/tools/events.py +65 -0
  23. docker_tiny_mcp/tools/exec.py +99 -0
  24. docker_tiny_mcp/tools/images.py +71 -0
  25. docker_tiny_mcp/tools/info.py +51 -0
  26. docker_tiny_mcp/tools/logs.py +101 -0
  27. docker_tiny_mcp/tools/networks.py +59 -0
  28. docker_tiny_mcp/tools/prune.py +60 -0
  29. docker_tiny_mcp/tools/pull.py +36 -0
  30. docker_tiny_mcp/tools/read.py +69 -0
  31. docker_tiny_mcp/tools/remove.py +36 -0
  32. docker_tiny_mcp/tools/remove_image.py +37 -0
  33. docker_tiny_mcp/tools/restart.py +31 -0
  34. docker_tiny_mcp/tools/results.py +50 -0
  35. docker_tiny_mcp/tools/start.py +36 -0
  36. docker_tiny_mcp/tools/stats.py +124 -0
  37. docker_tiny_mcp/tools/stop.py +28 -0
  38. docker_tiny_mcp/tools/volumes.py +56 -0
  39. docker_tiny_mcp/tools/wait.py +57 -0
  40. docker_tiny_mcp/tools/write.py +76 -0
  41. docker_tiny_mcp-0.1.0.dist-info/METADATA +424 -0
  42. docker_tiny_mcp-0.1.0.dist-info/RECORD +45 -0
  43. docker_tiny_mcp-0.1.0.dist-info/WHEEL +4 -0
  44. docker_tiny_mcp-0.1.0.dist-info/entry_points.txt +3 -0
  45. docker_tiny_mcp-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,156 @@
1
+ """Deployment restrictions for Docker host access."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from aiodocker import Docker
8
+ from aiodocker.containers import DockerContainer
9
+ from aiodocker.exceptions import DockerError
10
+
11
+ from . import daemon
12
+ from .errors import Refused, clear
13
+ from .models import CreateRequest, UnprivilegedCreateRequest
14
+
15
+ PROTECTED_PATHS = {
16
+ "MaskedPaths": frozenset(
17
+ (
18
+ "/proc/asound",
19
+ "/proc/acpi",
20
+ "/proc/kcore",
21
+ "/proc/keys",
22
+ "/proc/latency_stats",
23
+ "/proc/timer_list",
24
+ "/proc/timer_stats",
25
+ "/proc/sched_debug",
26
+ "/proc/scsi",
27
+ "/sys/firmware",
28
+ "/sys/devices/virtual/powercap",
29
+ )
30
+ ),
31
+ "ReadonlyPaths": frozenset(
32
+ (
33
+ "/proc/bus",
34
+ "/proc/fs",
35
+ "/proc/irq",
36
+ "/proc/sys",
37
+ "/proc/sysrq-trigger",
38
+ )
39
+ ),
40
+ }
41
+
42
+
43
+ async def check_volume(client: Docker, name: str, *, create: bool = False) -> None:
44
+ """Allow local volumes without mount options, including existing names."""
45
+ async with clear("checking the volume", subject=name):
46
+ try:
47
+ volume = await client.volumes.get(name)
48
+ except DockerError as error:
49
+ if error.status != 404 or not create:
50
+ raise
51
+ volume = await client.volumes.create({"Name": name, "Driver": "local"})
52
+ raw = await volume.show()
53
+ if raw.get("Driver") != "local" or raw.get("Options"):
54
+ raise Refused(f"unprivileged mode requires a local volume without options: {name}")
55
+
56
+
57
+ async def check_network(client: Docker, name: str) -> None:
58
+ """Allow bridge networks and the built-in network without connectivity."""
59
+ if name == "none":
60
+ return
61
+ if name == "host" or name.startswith("container:"):
62
+ raise Refused("unprivileged mode forbids host and container network namespaces")
63
+ async with clear("checking the network", subject=name):
64
+ network = await client.networks.get(name)
65
+ raw = await network.show()
66
+ if raw.get("Driver") != "bridge" or raw.get("Scope") != "local":
67
+ raise Refused(f"unprivileged mode requires a local bridge network: {name}")
68
+
69
+
70
+ async def configure_unprivileged(
71
+ client: Docker, args: CreateRequest, config: dict[str, Any]
72
+ ) -> None:
73
+ """Apply deployment settings before the container is created."""
74
+ host = config["HostConfig"]
75
+ checked = UnprivilegedCreateRequest.model_validate(args.model_dump(exclude={"network"}))
76
+ network = args.network or "bridge"
77
+ await check_network(client, network)
78
+ mounts = []
79
+ for spec in checked.volumes:
80
+ source, target, *mode = spec.split(":")
81
+ await check_volume(client, source, create=True)
82
+ mounts.append(
83
+ {"Type": "volume", "Source": source, "Target": target, "ReadOnly": mode == ["ro"]}
84
+ )
85
+ host.pop("Binds", None)
86
+ if mounts:
87
+ host["Mounts"] = mounts
88
+ host["NetworkMode"] = network
89
+ host["CgroupnsMode"] = "private"
90
+ host["IpcMode"] = "private"
91
+ host["SecurityOpt"] = ["no-new-privileges:true"]
92
+ host["Privileged"] = False
93
+
94
+
95
+ async def check_container(client: Docker, container: DockerContainer) -> None:
96
+ """Check existing containers before file access or process execution."""
97
+ async with clear("checking container isolation"):
98
+ raw = await container.show()
99
+ host = raw.get("HostConfig")
100
+ if not isinstance(host, dict):
101
+ raise Refused("unprivileged mode requires container isolation details")
102
+ for key in (
103
+ "Privileged",
104
+ "CapAdd",
105
+ "Devices",
106
+ "DeviceRequests",
107
+ "DeviceCgroupRules",
108
+ "VolumesFrom",
109
+ "ExtraHosts",
110
+ "Sysctls",
111
+ "StorageOpt",
112
+ "UseApiSocket",
113
+ ):
114
+ if host.get(key):
115
+ raise Refused(f"unprivileged mode forbids containers with {key}")
116
+ for key, allowed in (
117
+ ("PidMode", ("", "private")),
118
+ ("IpcMode", ("", "private", "none")),
119
+ ("UTSMode", ("", "private")),
120
+ ("UsernsMode", ("", "private")),
121
+ ("CgroupnsMode", ("", "private")),
122
+ ("Runtime", ("", "runc")),
123
+ ):
124
+ if (host.get(key) or "") not in allowed:
125
+ raise Refused(f"unprivileged mode forbids this {key}")
126
+ for option in host.get("SecurityOpt") or []:
127
+ if option not in (
128
+ "no-new-privileges",
129
+ "no-new-privileges:true",
130
+ "no-new-privileges=true",
131
+ ):
132
+ raise Refused("unprivileged mode forbids custom security options")
133
+ for key, required in PROTECTED_PATHS.items():
134
+ if key in host and not required.issubset(host[key] or []):
135
+ raise Refused(f"unprivileged mode requires protected system paths in {key}")
136
+ for spec in host.get("Binds") or []:
137
+ UnprivilegedCreateRequest(image="unused", volumes=[spec])
138
+ for mount in host.get("Mounts") or []:
139
+ if mount.get("Type") not in ("volume", "tmpfs") or mount.get("VolumeOptions"):
140
+ raise Refused("unprivileged mode forbids host mounts and volume options")
141
+ for mount in raw.get("Mounts") or []:
142
+ if mount.get("Type") == "volume" and mount.get("Name"):
143
+ await check_volume(client, mount["Name"])
144
+ elif mount.get("Type") != "tmpfs":
145
+ raise Refused("unprivileged mode forbids host mounts")
146
+ network = host.get("NetworkMode") or "bridge"
147
+ await check_network(client, "bridge" if network == "default" else network)
148
+ for name in (raw.get("NetworkSettings") or {}).get("Networks") or {}:
149
+ await check_network(client, name)
150
+
151
+
152
+ async def checked_container(client: Docker, reference: str) -> str:
153
+ """Resolve and check a container, then return its immutable ID."""
154
+ container = await daemon.find(client, reference)
155
+ await check_container(client, container)
156
+ return container.id
@@ -0,0 +1,115 @@
1
+ """Register Docker handlers, descriptions, and annotations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from aiodocker import Docker
6
+ from aiohttp_tiny_mcp import Hint, Registry
7
+
8
+ from . import prompts, resources, tools
9
+ from .consent import Policy
10
+ from .resources import templates
11
+ from .tools.create import fixed_network_create, unprivileged_create
12
+ from .tools.prune import prune_fixed_network
13
+
14
+ INSTRUCTIONS = (
15
+ "Inspect and control Docker. Start with `containers` to find what to act "
16
+ "on; `container`, `logs`, `read` and `stats` to understand one; `events` "
17
+ "for what happened before now; and `info` to confirm the daemon is "
18
+ "reachable and is the one you meant.\n\n"
19
+ "To change something: `create` makes and starts a container, `start`, "
20
+ "`stop` and `restart` do the obvious, `wait` holds until a container is "
21
+ "running or healthy, `exec` runs a command inside one, and `write` puts a "
22
+ "file into one. `prune`, `remove` and `remove_image` reclaim space.\n\n"
23
+ "Reading never asks, and neither does a command that only reads, such as "
24
+ "`ls` or `cat`. What cannot be undone -- `remove`, `remove_image`, "
25
+ "`prune`, and a command that is not merely reading -- asks once, and the "
26
+ "person answering may say not to ask again."
27
+ )
28
+
29
+ READS = Hint.READ_ONLY | Hint.IDEMPOTENT
30
+
31
+ WATCHES = Hint.READ_ONLY
32
+
33
+
34
+ def build(
35
+ registry: Registry,
36
+ client: Docker,
37
+ policy: Policy | None = None,
38
+ *,
39
+ unprivileged: bool = False,
40
+ network: str | None = None,
41
+ ) -> Registry:
42
+ """Register handlers and inject the Docker client and deployment confirmation policy."""
43
+ registry.instructions = INSTRUCTIONS
44
+ registry.provide_instance(client)
45
+ registry.provide_instance(policy or Policy())
46
+ if unprivileged:
47
+ registry.instructions += (
48
+ "\n\nUnprivileged mode: host mounts and privileged containers are forbidden. "
49
+ "Use named local volumes for persistent data. The server selects the network."
50
+ )
51
+ if network:
52
+ registry.instructions += (
53
+ "\n\nThe network is fixed by the server; network management is disabled."
54
+ )
55
+
56
+ registry.tool(tools.containers, annotations=READS)
57
+ registry.tool(tools.container, annotations=READS)
58
+ registry.tool(tools.images, annotations=READS)
59
+ if not network:
60
+ registry.tool(tools.networks, annotations=READS)
61
+ registry.tool(tools.volumes, annotations=READS)
62
+ registry.tool(tools.info, annotations=READS)
63
+ registry.tool(tools.logs, annotations=WATCHES)
64
+ registry.tool(tools.stats, annotations=WATCHES)
65
+ registry.tool(tools.events, annotations=WATCHES)
66
+ registry.tool(tools.wait, annotations=WATCHES)
67
+
68
+ if unprivileged:
69
+ registry.tool(unprivileged_create(network), name="create", annotations=Hint.OPEN_WORLD)
70
+ registry.tool(tools.read_unprivileged, name="read", annotations=READS)
71
+ registry.tool(tools.start_unprivileged, name="start", annotations=Hint.IDEMPOTENT)
72
+ registry.tool(tools.restart_unprivileged, name="restart")
73
+ registry.tool(tools.write_unprivileged, name="write", annotations=Hint.DESTRUCTIVE)
74
+ registry.tool(
75
+ tools.exec_unprivileged, name="exec", annotations=Hint.DESTRUCTIVE | Hint.OPEN_WORLD
76
+ )
77
+ else:
78
+ if network:
79
+ registry.tool(fixed_network_create(network), name="create", annotations=Hint.OPEN_WORLD)
80
+ else:
81
+ registry.tool(tools.create, annotations=Hint.OPEN_WORLD)
82
+ registry.tool(tools.read, annotations=READS)
83
+ registry.tool(tools.start, annotations=Hint.IDEMPOTENT)
84
+ registry.tool(tools.restart)
85
+ registry.tool(tools.write, annotations=Hint.DESTRUCTIVE)
86
+ registry.tool(tools.exec, annotations=Hint.DESTRUCTIVE | Hint.OPEN_WORLD)
87
+
88
+ registry.tool(tools.stop, annotations=Hint.IDEMPOTENT)
89
+ registry.tool(tools.remove, annotations=Hint.DESTRUCTIVE)
90
+ registry.tool(tools.remove_image, annotations=Hint.DESTRUCTIVE)
91
+ if network:
92
+ registry.tool(prune_fixed_network, name="prune", annotations=Hint.DESTRUCTIVE)
93
+ else:
94
+ registry.tool(tools.prune, annotations=Hint.DESTRUCTIVE)
95
+ registry.tool(tools.pull, streaming=True, annotations=Hint.OPEN_WORLD)
96
+
97
+ registry.resource("docker://info", resources.info, mime_type="application/json")
98
+ registry.resource("docker://containers", resources.containers, mime_type="application/json")
99
+ registry.resource(
100
+ "docker://containers/{name}",
101
+ templates.container,
102
+ name="container",
103
+ mime_type="application/json",
104
+ )
105
+ registry.resource("docker://containers/{name}/logs", templates.logs, name="container-logs")
106
+ registry.resource("docker://images", resources.images, mime_type="application/json")
107
+
108
+ registry.prompt(prompts.diagnose, title="Diagnose a container")
109
+ registry.prompt(prompts.reclaim, title="Find space to reclaim")
110
+
111
+ registry.completions(prompts.complete)
112
+ return registry
113
+
114
+
115
+ __all__ = ["INSTRUCTIONS", "build"]
@@ -0,0 +1,57 @@
1
+ """Docker MCP tool handlers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .container import container
6
+ from .containers import containers
7
+ from .create import create
8
+ from .events import events
9
+ from .exec import exec, exec_unprivileged
10
+ from .images import images
11
+ from .info import info
12
+ from .logs import logs
13
+ from .networks import networks
14
+ from .prune import prune
15
+ from .pull import pull
16
+ from .read import read, read_unprivileged
17
+ from .remove import remove
18
+ from .remove_image import remove_image
19
+ from .restart import restart, restart_unprivileged
20
+ from .results import outcome, settled
21
+ from .start import start, start_unprivileged
22
+ from .stats import stats
23
+ from .stop import stop
24
+ from .volumes import volumes
25
+ from .wait import wait
26
+ from .write import write, write_unprivileged
27
+
28
+ __all__ = [
29
+ "container",
30
+ "containers",
31
+ "create",
32
+ "events",
33
+ "exec",
34
+ "exec_unprivileged",
35
+ "images",
36
+ "info",
37
+ "logs",
38
+ "networks",
39
+ "outcome",
40
+ "prune",
41
+ "pull",
42
+ "read",
43
+ "read_unprivileged",
44
+ "remove",
45
+ "remove_image",
46
+ "restart",
47
+ "restart_unprivileged",
48
+ "settled",
49
+ "start",
50
+ "start_unprivileged",
51
+ "stats",
52
+ "stop",
53
+ "volumes",
54
+ "wait",
55
+ "write",
56
+ "write_unprivileged",
57
+ ]
@@ -0,0 +1,104 @@
1
+ """One container, from the daemon's `inspect` shape.
2
+
3
+ The reshaping lives in `docker.py`. What this file owes a reader is the
4
+ promise it keeps: environment values never leave the daemon, only their names,
5
+ because a value is a password as often as not.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import shlex
11
+ from typing import Any
12
+
13
+ from aiodocker import Docker
14
+
15
+ from docker_tiny_mcp import daemon
16
+ from docker_tiny_mcp.errors import clear
17
+ from docker_tiny_mcp.models import ContainerDetail, ContainerRef, short
18
+
19
+ PROJECT_LABEL = "com.docker.compose.project"
20
+ SERVICE_LABEL = "com.docker.compose.service"
21
+
22
+
23
+ def published_ports(raw: dict[str, Any]) -> list[str]:
24
+ bindings = (raw.get("NetworkSettings") or {}).get("Ports") or {}
25
+ published: list[str] = []
26
+ for private, hosts in bindings.items():
27
+ for binding in hosts or []:
28
+ published.append(
29
+ f"{binding.get('HostIp', '')}:{binding.get('HostPort', '')}->{private}"
30
+ )
31
+ if not hosts:
32
+ published.append(str(private))
33
+ return published
34
+
35
+
36
+ def command_of(config: dict[str, Any], raw: dict[str, Any]) -> str:
37
+ """What the container runs, quoted as a shell would quote it.
38
+
39
+ Joining the arguments with spaces loses the difference between one
40
+ argument containing a space and two arguments, which is the difference
41
+ between what ran and something else.
42
+ """
43
+ parts = [*(config.get("Entrypoint") or []), *(config.get("Cmd") or [])]
44
+ if parts:
45
+ return shlex.join(str(part) for part in parts)
46
+ return str(raw.get("Path", ""))
47
+
48
+
49
+ def compose_of(config: dict[str, Any]) -> str | None:
50
+ """Which Compose service this is, where it is one."""
51
+ labels = config.get("Labels") or {}
52
+ project = labels.get(PROJECT_LABEL)
53
+ service = labels.get(SERVICE_LABEL)
54
+ if project and service:
55
+ return f"{project}/{service}"
56
+ return str(project) if project else None
57
+
58
+
59
+ def detail(raw: dict[str, Any]) -> ContainerDetail:
60
+ """One container, from the daemon's `inspect` shape rather than its list
61
+ shape -- the two differ, which is why this is not `summary` with extras."""
62
+ state = raw.get("State") or {}
63
+ config = raw.get("Config") or {}
64
+ host = raw.get("HostConfig") or {}
65
+ networks = (raw.get("NetworkSettings") or {}).get("Networks") or {}
66
+ health = (state.get("Health") or {}).get("Status")
67
+ exit_code = state.get("ExitCode")
68
+ return ContainerDetail(
69
+ id=short(str(raw.get("Id", ""))),
70
+ name=str(raw.get("Name", "")).lstrip("/"),
71
+ image=str(config.get("Image", "")),
72
+ state=str(state.get("Status", "unknown")),
73
+ ports=published_ports(raw),
74
+ created=daemon.when(raw.get("Created")) or "",
75
+ started=daemon.when(state.get("StartedAt")),
76
+ finished=daemon.when(state.get("FinishedAt")),
77
+ command=command_of(config, raw),
78
+ restart_count=int(raw.get("RestartCount", 0) or 0),
79
+ restart_policy=str((host.get("RestartPolicy") or {}).get("Name") or "no"),
80
+ health=str(health) if health else None,
81
+ exit_code=int(exit_code)
82
+ if exit_code is not None and state.get("Status") != "running"
83
+ else None,
84
+ error=str(state.get("Error")) or None,
85
+ compose=compose_of(config),
86
+ networks=sorted(networks),
87
+ mounts=[
88
+ f"{mount.get('Source', '')}:{mount.get('Destination', '')}"
89
+ for mount in raw.get("Mounts") or []
90
+ ],
91
+ environment=sorted(str(item).split("=", 1)[0] for item in config.get("Env") or []),
92
+ )
93
+
94
+
95
+ async def container(args: ContainerRef, client: Docker) -> ContainerDetail:
96
+ """Everything about one container: health, exit code, restarts, mounts,
97
+ networks, its Compose service, and the names of its environment variables.
98
+
99
+ Values of environment variables are never reported. Use this when a
100
+ container is behaving oddly and the list did not say why.
101
+ """
102
+ found = await daemon.find(client, args.container)
103
+ async with clear("reading", subject=args.container):
104
+ return detail(await found.show())
@@ -0,0 +1,44 @@
1
+ """Where every other tool starts, so the row is short on purpose.
2
+
3
+ Name, image, state and ports answer "which one", which is all this is for.
4
+ Everything else is one more call away, and putting it here would make the
5
+ common case pay for the rare one.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from aiodocker import Docker
13
+
14
+ from docker_tiny_mcp import daemon
15
+ from docker_tiny_mcp.models import Container, ContainerFilter, Containers, port_list, short
16
+
17
+
18
+ def summary(raw: dict[str, Any]) -> Container:
19
+ return Container(
20
+ id=short(str(raw.get("Id", ""))),
21
+ name=daemon.name_of(raw),
22
+ image=str(raw.get("Image", "")),
23
+ state=str(raw.get("State", "unknown")),
24
+ status=str(raw.get("Status", "")),
25
+ ports=port_list(raw.get("Ports")),
26
+ )
27
+
28
+
29
+ async def containers(args: ContainerFilter, client: Docker) -> Containers:
30
+ """List containers. Use this first to find what to act on.
31
+
32
+ Reports name, image, state and published ports. Running only unless `all`
33
+ is true. Ask for `container` when one of these needs explaining.
34
+ """
35
+ found = await daemon.containers(client, all=args.all)
36
+ if args.name:
37
+ wanted = args.name.lower()
38
+ found = [
39
+ raw
40
+ for raw in found
41
+ if any(wanted in str(name).lower() for name in raw.get("Names") or [])
42
+ ]
43
+ shown = [summary(raw) for raw in found[: args.limit]]
44
+ return Containers(containers=shown, shown=len(shown), total=len(found))
@@ -0,0 +1,210 @@
1
+ """Making a container, with the flags named rather than written out.
2
+
3
+ `docker run` takes its options as a command line. A model writing one gets
4
+ the quoting wrong, so every option is a field here and `docker.configuration`
5
+ assembles what the daemon actually takes.
6
+
7
+ The default policy does not ask before this. Creating something is undone by
8
+ removing it, and a question about the most reversible action is the one that
9
+ teaches people to stop reading questions.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
15
+ from typing import Any
16
+
17
+ from aiodocker import Docker
18
+ from aiohttp_tiny_mcp import Exchange
19
+
20
+ from docker_tiny_mcp import daemon
21
+ from docker_tiny_mcp.consent import Policy, confirm, refusal
22
+ from docker_tiny_mcp.errors import Conflict, clear
23
+ from docker_tiny_mcp.events import publish
24
+ from docker_tiny_mcp.models import (
25
+ Created,
26
+ CreateRequest,
27
+ FixedNetworkCreateRequest,
28
+ PullRequest,
29
+ UnprivilegedCreateRequest,
30
+ )
31
+ from docker_tiny_mcp.safety import check_container, configure_unprivileged
32
+
33
+ from .pull import pull
34
+ from .results import settled
35
+
36
+
37
+ def port_binding(spec: str) -> tuple[str, str, dict[str, str]]:
38
+ """One published port, as `docker run -p` states it.
39
+
40
+ Returns the container port with its protocol, and the host address to bind
41
+ it to. Anything this cannot read is refused by name, because a port
42
+ silently not published is found much later.
43
+ """
44
+ body, _, protocol = spec.partition("/")
45
+ parts = body.split(":")
46
+ if len(parts) == 2:
47
+ host_ip, host_port, container_port = "", parts[0], parts[1]
48
+ elif len(parts) == 3:
49
+ host_ip, host_port, container_port = parts
50
+ else:
51
+ raise ValueError(f'cannot read port {spec!r}: write it as "8080:80" or "127.0.0.1:8080:80"')
52
+ if not host_port.isdigit() or not container_port.isdigit():
53
+ raise ValueError(f"cannot read port {spec!r}: both sides must be numbers")
54
+ key = f"{container_port}/{protocol or 'tcp'}"
55
+ return key, container_port, {"HostIp": host_ip, "HostPort": host_port}
56
+
57
+
58
+ def configuration(
59
+ *,
60
+ image: str,
61
+ command: Sequence[str] | None,
62
+ environment: Mapping[str, str],
63
+ ports: Sequence[str],
64
+ volumes: Sequence[str],
65
+ network: str | None,
66
+ restart: str,
67
+ workdir: str | None,
68
+ user: str | None,
69
+ ) -> dict[str, Any]:
70
+ """What `containers/create` takes, built from named arguments.
71
+
72
+ The daemon's shape puts half of this under `HostConfig` and half beside
73
+ it, and a port has to appear in both. Assembling it here keeps that out of
74
+ the tool.
75
+ """
76
+ exposed: dict[str, Any] = {}
77
+ bindings: dict[str, list[dict[str, str]]] = {}
78
+ for spec in ports:
79
+ key, _, binding = port_binding(spec)
80
+ exposed[key] = {}
81
+ bindings.setdefault(key, []).append(binding)
82
+ host: dict[str, Any] = {"RestartPolicy": {"Name": restart}}
83
+ if bindings:
84
+ host["PortBindings"] = bindings
85
+ if volumes:
86
+ host["Binds"] = list(volumes)
87
+ if network:
88
+ host["NetworkMode"] = network
89
+ config: dict[str, Any] = {"Image": image, "HostConfig": host}
90
+ if command:
91
+ config["Cmd"] = list(command)
92
+ if environment:
93
+ config["Env"] = [f"{key}={value}" for key, value in environment.items()]
94
+ if exposed:
95
+ config["ExposedPorts"] = exposed
96
+ if workdir:
97
+ config["WorkingDir"] = workdir
98
+ if user:
99
+ config["User"] = user
100
+ return config
101
+
102
+
103
+ def creation(args: CreateRequest) -> str:
104
+ """The question `create` asks, naming what reaches the host."""
105
+ said = f"Create a container from {args.image}"
106
+ if args.ports:
107
+ said += f", publishing {', '.join(args.ports)}"
108
+ if args.volumes:
109
+ said += f", mounting {', '.join(args.volumes)}"
110
+ return said + "?"
111
+
112
+
113
+ async def create(args: CreateRequest, client: Docker, ex: Exchange, policy: Policy) -> Created:
114
+ """Create a container, and start it unless told not to.
115
+
116
+ This is `docker run`, with the flags named rather than written into one
117
+ string. Ports are "8080:80", volumes are "/on/host:/in/container". The
118
+ image is downloaded first where it is missing.
119
+
120
+ Asks first only where the policy says to: creating something is undone
121
+ by removing it, so the default does not interrupt for this.
122
+ """
123
+ return await create_container(args, client, ex, policy)
124
+
125
+
126
+ async def create_container(
127
+ args: CreateRequest, client: Docker, ex: Exchange, policy: Policy, *, unprivileged: bool = False
128
+ ) -> Created:
129
+ """Create a container after checking deployment restrictions."""
130
+ if not await confirm(ex, policy, "create", args.image, creation(args)):
131
+ raise Conflict(f"not created: {refusal(ex)}")
132
+
133
+ config = configuration(
134
+ image=args.image,
135
+ command=args.command,
136
+ environment=args.environment,
137
+ ports=args.ports,
138
+ volumes=args.volumes,
139
+ network=args.network,
140
+ restart=args.restart,
141
+ workdir=args.workdir,
142
+ user=args.user,
143
+ )
144
+ if unprivileged:
145
+ await configure_unprivileged(client, args, config)
146
+
147
+ held = {tag for raw in await daemon.images(client) for tag in raw.get("RepoTags") or []}
148
+ if args.pull == "always" or (args.pull == "missing" and args.image not in held):
149
+ await pull(PullRequest(image=args.image), client, ex)
150
+
151
+ async with clear("creating the container", subject=args.name or ""):
152
+ made = await client.containers.create(config, name=args.name)
153
+ if unprivileged:
154
+ try:
155
+ await check_container(client, made)
156
+ except Exception as error:
157
+ raise Conflict(
158
+ f"container {made.id} was created but refused by unprivileged mode; "
159
+ f"it was not started: {error}"
160
+ ) from error
161
+ note = None
162
+ if args.start:
163
+ await made.start()
164
+ state = await settled(made)
165
+ if str(state.get("Status")) != "running":
166
+ note = (
167
+ f"created, but it did not stay running: it is {state.get('Status')}. "
168
+ "Read `logs` for why."
169
+ )
170
+ raw = await made.show()
171
+ await publish(ex.registry, "docker://containers")
172
+ return Created(
173
+ id=str(raw.get("Id", ""))[:12],
174
+ name=str(raw.get("Name", "")).lstrip("/"),
175
+ image=args.image,
176
+ state=str((raw.get("State") or {}).get("Status", "created")),
177
+ ports=list(args.ports),
178
+ warnings=[str(item) for item in raw.get("Warnings") or []],
179
+ note=note,
180
+ )
181
+
182
+
183
+ def fixed_network_create(network: str) -> Callable[..., Awaitable[Created]]:
184
+ """Bind operator settings without exposing them as tool arguments."""
185
+
186
+ async def create_fixed_network(
187
+ args: FixedNetworkCreateRequest, client: Docker, ex: Exchange, policy: Policy
188
+ ) -> Created:
189
+ """Create a container on the server's fixed network; callers cannot change the network."""
190
+ request = CreateRequest(**args.model_dump(), network=network)
191
+ return await create_container(request, client, ex, policy)
192
+
193
+ return create_fixed_network
194
+
195
+
196
+ def unprivileged_create(network: str | None) -> Callable[..., Awaitable[Created]]:
197
+ """Bind the operator's network for unprivileged container creation."""
198
+
199
+ async def create_unprivileged(
200
+ args: UnprivilegedCreateRequest, client: Docker, ex: Exchange, policy: Policy
201
+ ) -> Created:
202
+ """Create an isolated container with optional persistent named volumes.
203
+
204
+ Volumes use name:/path[:ro|rw]. Host paths and network overrides are forbidden.
205
+ Missing volumes use the local driver without mount options.
206
+ """
207
+ request = CreateRequest(**args.model_dump(), network=network)
208
+ return await create_container(request, client, ex, policy, unprivileged=True)
209
+
210
+ return create_unprivileged