import asyncio import sys import json from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client async def run_docker_mcp_explorer(): # Define the server parameters to run the Docker MCP server via npx # Using the official Docker MCP server from the Model Context Protocol organization server_params = StdioServerParameters( command="npx", args=["-y", "@modelcontextprotocol/server-docker"], env=None ) print("--- Connecting to Docker MCP Server ---") try: async with stdio_client(server_params) as (read, write): async with ClientSession(read, write) as session: # Initialize the session print("Initializing session...") await session.initialize() # 1. List available tools print("\n--- Available Tools ---") tools_result = await session.list_tools() for tool in tools_result.tools: print(f"- {tool.name}: {tool.description}") # 2. Call 'docker_list_containers' print("\n--- Calling 'docker_list_containers' ---") # The official server tool name is 'docker_list_containers' # It doesn't require arguments for a basic list containers_result = await session.call_tool("docker_list_containers", arguments={}) # The result comes back as a list of Content objects if containers_result.content: for item in containers_result.content: if item.type == 'text': # Parse the text (which is usually a JSON string for this tool) try: containers = json.loads(item.text) print(f"Found {len(containers)} containers:") for c in containers: status = c.get('Status', 'Unknown') names = ", ".join(c.get('Names', [])) print(f" [{c.get('Id')[:12]}] {names} ({status})") except json.JSONDecodeError: print(item.text) else: print("No containers found or empty response.") except Exception as e: print(f"\nError: {e}") if "npx" in str(e): print("Ensure 'npx' is installed and available in your PATH.") if __name__ == "__main__": asyncio.run(run_docker_mcp_explorer())