minecraft-mcp-server

repository·main·Indexed 20 days ago

https://github.com/yuniko-software/minecraft-mcp-server

A Minecraft bot powered by large language models and the Mineflayer API. It implements the Model Context Protocol (MCP) to allow LLMs, such as Claude, to control a Minecraft character, perform tasks, and interact with the game world. The server provides tools for movement, flight, inventory management, block interaction, furnace use, entity interaction, and game state detection. It is compatible with Minecraft Java Edition (tested with version 1.21.8 and 1.21.11).

Tokens
5.6K
Snippets
19
Records
26
Agent score
71%

What's inside minecraft-mcp-server

  1. Use the Minecraft MCP Server in Claude Desktop

    main

    Once configured and running, the bot will join your Minecraft world. To trigger the bot to perform actions, you must explicitly mention in your Claude Desktop prompt that the bot should do something in Minecraft.

    Example usage: "Claude, please go to coordinates 100, 64, 100 and dig a block."

    When the bot attempts an action, Claude will ask for your permission to run the MCP tool. You can also upload images of buildings to Claude and ask the bot to build them.

  2. Install and Configure Minecraft MCP Server for Claude Desktop

    main

    To use the Minecraft MCP server with Claude Desktop, you must configure your claude_desktop_config.json to run the server via npx.

    Prerequisites

    • Git
    • Node.js (>= 20.10.0)
    • A running Minecraft game (tested with version 1.21.8 Java Edition)
    • An MCP-compatible client (e.g., Claude Desktop)

    Setup Steps

    1. Run Minecraft: Create a singleplayer world and open it to LAN (ESC -> Open to LAN). By default, the bot connects to localhost on port 25565.
    2. Configure Claude Desktop:
      • Open Claude Desktop.
      • Navigate to File -> Settings -> Developer -> Edit Config.
      • In the claude_desktop_config.json file, add the minecraft server configuration.
    3. Reboot: Completely restart Claude Desktop (ensure it is closed in the OS tray) for changes to take effect.

    Note: The server currently supports Minecraft version 1.21.11. Newer versions may not be compatible.

    {
      "mcpServers": {
        "minecraft": {
          "command": "npx",
          "args": [
            "-y",
            "github:yuniko-software/minecraft-mcp-server",
            "--host",
            "localhost",
            "--port",
            "25565",
            "--username",
            "ClaudeBot"
          ]
        }
      }
    }
  3. How the Minecraft MCP Server initializes

    main

    The minecraft-mcp-server operates as a Model Context Protocol (MCP) server using StdioServerTransport. It establishes a connection to a Minecraft bot via BotConnection and exposes a suite of tools to the MCP client.

    Key components of the initialization lifecycle:

    1. Configuration: Loads settings via parseConfig().
    2. Bot Connection: Initializes BotConnection which manages the link to the Minecraft instance. It accepts an onChatMessage callback to populate a MessageStore.
    3. Tool Registration: Uses a ToolFactory to register various tool categories (Position, Inventory, Block, Entity, Chat, Flight, GameState, Crafting, and Furnace) with the McpServer instance.
    4. Transport: Connects the server to stdin/stdout using StdioServerTransport to communicate with the MCP host.
    5. Cleanup: Listens for process.stdin 'end' events to trigger connection.cleanup() and exit gracefully.
    // Conceptual flow of the server startup
    const config = parseConfig();
    const connection = new BotConnection(config, { ... });
    connection.connect();
    
    const server = new McpServer({ name: "minecraft-mcp-server", version: "2.0.4" });
    const factory = new ToolFactory(server, connection);
    
    // Tools are registered to the factory
    registerPositionTools(factory, () => connection.getBot()!);
    
    const transport = new StdioServerTransport();
    await server.connect(transport);
  4. Reference: Available Minecraft MCP Commands

    main

    The following commands are available for the LLM to control the Minecraft character once connected to a server:

    Movement

    • get-position: Get the current position of the bot
    • move-to-position: Move to specific coordinates
    • look-at: Make the bot look at specific coordinates
    • jump: Make the bot jump
    • move-in-direction: Move in a specific direction for a duration

    Flight

    • fly-to: Make the bot fly directly to specific coordinates

    Inventory

    • list-inventory: List all items in the bot's inventory
    • find-item: Find a specific item in inventory
    • equip-item: Equip a specific item

    Block Interaction

    • place-block: Place a block at specified coordinates
    • dig-block: Dig a block at specified coordinates
    • get-block-info: Get information about a block
    • find-blocks: Find one or more nearby blocks of a specific type

    Furnace

    • smelt-item: Smelt items using a furnace-like block

    Entity Interaction

    • find-entity: Find the nearest entity of a specific type

    Communication

    • send-chat: Send a chat message in-game
    • read-chat: Get recent chat messages from players

    Game State

    • detect-gamemode: Detect the gamemode on game
  5. Move the bot to a specific position

    main

    Use the move-to-position tool to navigate the bot to target coordinates. The bot uses pathfinding to reach the destination.

    Arguments:

    • x (number): X coordinate.
    • y (number): Y coordinate.
    • z (number): Z coordinate.
    • range (number, optional): How close to get to the target. Defaults to 1.
    • timeoutMs (number, optional): Timeout in milliseconds before cancelling the movement. Minimum value is 50.
    {
      "name": "move-to-position",
      "arguments": {
        "x": 100,
        "y": 64,
        "z": -200,
        "range": 1,
        "timeoutMs": 5000
      }
    }
  6. Register a new MCP tool with ToolFactory

    main

    The ToolFactory class is used to register tools with the Model Context Protocol (MCP) server. When registering a tool, the factory automatically handles connection checks to the Minecraft bot and validates incoming arguments against a provided schema.

    To register a tool, use the registerTool method. If the provided schema contains Zod types, the factory will automatically validate the arguments and return a formatted error message if validation fails. If the bot connection is lost, the tool will return an error response instead of attempting execution.

    // Example usage of registerTool
    toolFactory.registerTool(
      "example_tool",
      "A description of what the tool does",
      { 
        param1: z.string().describe("Description of param1") 
      },
      async (args) => {
        // args is automatically parsed and validated based on the schema
        return {
          content: [{ type: "text", text: `Executed with ${args.param1}` }]
        };
      }
    );
  7. Initialize and manage a Minecraft bot connection with BotConnection

    main

    The BotConnection class manages the lifecycle of a Mineflayer-based Minecraft bot, including connection, reconnection logic, and event handling.

    To use it, provide a BotConfig object and ConnectionCallbacks to handle logs and chat messages. You can then call .connect() to start the connection or .checkConnectionAndReconnect() to ensure the bot is online before performing actions.

    Key Methods:

    • connect(): Initializes the Mineflayer bot with the provided configuration and plugins (includes mineflayer-pathfinder).
    • checkConnectionAndReconnect(): A robust way to ensure connectivity. If the bot is disconnected, it triggers a reconnection attempt and polls for a successful connection for a limited time.
    • attemptReconnect(): Manually triggers a reconnection attempt after a configured delay.
    • cleanup(): Gracefully shuts down the bot and clears any pending reconnection timers.
    import { BotConnection } from './bot-connection';
    
    const config = {
      host: 'localhost',
      port: 25565,
      username: 'MCP_Bot'
    };
    
    const callbacks = {
      onLog: (level, message) => console.log(`[${level}] ${message}`),
      onChatMessage: (username, message) => console.log(`${username}: ${message}`)
    };
    
    const connection = new BotConnection(config, callbacks, 2000);
    
    // Start connection
    connection.connect();
    
    // Or use the safer check method
    const status = await connection.checkConnectionAndReconnect();
    if (!status.connected) {
      console.error(status.message);
    }
  8. Use chat tools to interact with Minecraft chat

    main

    The registerChatTools function provides two MCP tools for interacting with the Minecraft chat environment via a mineflayer bot and a MessageStore:

    1. send-chat: Sends a text message to the in-game chat.
    2. read-chat: Retrieves a list of recent chat messages stored in the MessageStore.

    These tools allow an MCP client to both broadcast messages and observe player conversations.

    // Example of how these tools are registered within the server setup
    registerChatTools(factory, () => bot, messageStore);
  9. Monitor BotConnection state and connectivity

    main

    You can query the current status of the bot connection using the following methods:

    • getState(): Returns the current ConnectionState ('connected' | 'connecting' | 'disconnected').
    • isConnected(): Returns true if the state is 'connected', otherwise false.
    • getBot(): Returns the underlying mineflayer.Bot instance if connected, or null if not.
  10. Create MCP tool responses and errors

    main

    The ToolFactory provides helper methods to ensure responses follow the expected McpResponse format required by the MCP server.

    createResponse(text: string)

    Creates a successful text-based response.

    • Returns: { content: [{ type: "text", text: string }] }

    createErrorResponse(error: Error | string)

    Creates an error response that signals failure to the MCP client.

    • Returns: { content: [{ type: "text", text: "Failed: <message>" }], isError: true }
    // Successful response
    return toolFactory.createResponse("Success message");
    
    // Error response
    return toolFactory.createErrorResponse("Something went wrong");
  11. Register a tool with schema validation using Zod

    main

    The registerTool method supports automatic argument validation if the schema argument contains ZodType instances.

    When a schema is provided using Zod, the ToolFactory performs the following:

    1. Connection Check: Ensures the BotConnection is active.
    2. Parsing: Uses z.object(schema).passthrough().parse(args) to validate the input.
    3. Error Handling: If validation fails, it catches the ZodError and returns a formatted error response in the format: Invalid tool arguments: path.to.field: error message; ....

    If the schema is an empty object or does not contain Zod types, validation is skipped and the raw args are passed to the executor.

    import { z } from "zod";
    
    toolFactory.registerTool(
      "move_player",
      "Moves the player to specific coordinates",
      {
        x: z.number().int().describe("X coordinate"),
        y: z.number().int().describe("Y coordinate"),
        z: z.number().int().describe("Z coordinate"),
        direction: z.enum(["north", "south", "east", "west"]).optional()
      },
      async (args) => {
        // args is typed via the schema during execution
        return toolFactory.createResponse(`Moving to ${args.x}, ${args.y}, ${args.z}`);
      }
    );