Skip to main content
Glama

create-container

Create a new standalone Docker container with specified image, name, ports, and environment variables for application deployment.

Instructions

Create a new standalone Docker container

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
imageYes
nameNo
portsNo
environmentNo

Implementation Reference

  • Main execution logic for the create-container tool: validates arguments, parses ports, pulls image if needed, runs the container using python-on-whales DockerClient, handles timeout and errors.
    async def handle_create_container(arguments: Dict[str, Any]) -> List[TextContent]:
        try:
            image = arguments["image"]
            container_name = arguments.get("name")
            ports = arguments.get("ports", {})
            environment = arguments.get("environment", {})
    
            if not image:
                raise ValueError("Image name cannot be empty")
    
            port_mappings = []
            for host_key, container_port in ports.items():
                mapping = await parse_port_mapping(host_key, container_port)
                port_mappings.append(mapping)
    
            async def pull_and_run():
                if not docker_client.image.exists(image):
                    await asyncio.to_thread(docker_client.image.pull, image)
    
                container = await asyncio.to_thread(
                    docker_client.container.run,
                    image,
                    name=container_name,
                    publish=port_mappings,
                    envs=environment,
                    detach=True
                )
                return container
    
            container = await asyncio.wait_for(pull_and_run(), timeout=DockerHandlers.TIMEOUT_AMOUNT)
            return [TextContent(type="text", text=f"Created container '{container.name}' (ID: {container.id})")]
        except asyncio.TimeoutError:
            return [TextContent(type="text", text=f"Operation timed out after {DockerHandlers.TIMEOUT_AMOUNT} seconds")]
        except Exception as e:
            return [TextContent(type="text", text=f"Error creating container: {str(e)} | Arguments: {arguments}")]
  • Input schema definition for the create-container tool, specifying properties for image (required), name, ports (object map), and environment (object map).
    types.Tool(
        name="create-container",
        description="Create a new standalone Docker container",
        inputSchema={
            "type": "object",
            "properties": {
                "image": {"type": "string"},
                "name": {"type": "string"},
                "ports": {
                    "type": "object",
                    "additionalProperties": {"type": "string"}
                },
                "environment": {
                    "type": "object",
                    "additionalProperties": {"type": "string"}
                }
            },
            "required": ["image"]
        }
    ),
  • Tool dispatch registration in the @server.call_tool() handler, routing 'create-container' calls to DockerHandlers.handle_create_container.
    if name == "create-container":
        return await DockerHandlers.handle_create_container(arguments)
  • Registration of the create-container tool in the @server.list_tools() function, exposing it to the MCP server.
    @server.list_tools()
    async def handle_list_tools() -> List[types.Tool]:
        return [
            types.Tool(
                name="create-container",
                description="Create a new standalone Docker container",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "image": {"type": "string"},
                        "name": {"type": "string"},
                        "ports": {
                            "type": "object",
                            "additionalProperties": {"type": "string"}
                        },
                        "environment": {
                            "type": "object",
                            "additionalProperties": {"type": "string"}
                        }
                    },
                    "required": ["image"]
                }
            ),
            types.Tool(
                name="deploy-compose",
                description="Deploy a Docker Compose stack",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "compose_yaml": {"type": "string"},
                        "project_name": {"type": "string"}
                    },
                    "required": ["compose_yaml", "project_name"]
                }
            ),
            types.Tool(
                name="get-logs",
                description="Retrieve the latest logs for a specified Docker container",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "container_name": {"type": "string"}
                    },
                    "required": ["container_name"]
                }
            ),
            types.Tool(
                name="list-containers",
                description="List all Docker containers",
                inputSchema={
                    "type": "object",
                    "properties": {}
                }
            )
        ]
  • Helper function used by the handler to parse port mappings, handling host:container and protocol (tcp/udp).
    async def parse_port_mapping(host_key: str, container_port: str | int) -> tuple[str, str] | tuple[str, str, str]:
        if '/' in str(host_key):
            host_port, protocol = host_key.split('/')
            if protocol.lower() == 'udp':
                return (str(host_port), str(container_port), 'udp')
            return (str(host_port), str(container_port))
    
        if isinstance(container_port, str) and '/' in container_port:
            port, protocol = container_port.split('/')
            if protocol.lower() == 'udp':
                return (str(host_key), port, 'udp')
            return (str(host_key), port)
    
        return (str(host_key), str(container_port))

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/QuantGeekDev/docker-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server