# 🛠️ MMORPG with MCP Integration - Developer Documentation ## 📖 Table of Contents 1. [Introduction](#introduction) 2. [Project Setup](#project-setup) 3. [Architecture Overview](#architecture-overview) 4. [MCP API Reference](#mcp-api-reference) * [Connection](#connection) * [Available Tools/Commands](#available-toolscommands) * [Common Operations](#common-operations) 5. [Extending the Game](#extending-the-game) * [NPC Add-on Development](#npc-add-on-development) * [Adding New Game Mechanics](#adding-new-game-mechanics) 6. [AI Agent Integration](#ai-agent-integration) 7. [Debugging](#debugging) --- ## 📜 Introduction This document provides technical guidance for developers working on the **MMORPG with MCP Integration** project. It covers project setup, architecture, API usage for client/agent development, and how to extend the game's functionalities. --- ## ⚙️ Project Setup ### Prerequisites * Python 3.8 or higher * `pip` for package management ### Getting the Code Clone the repository to your local machine (if you haven't already). ### Installation 1. Navigate to the project directory (e.g., `c:\\Users\\Chris4K\\Projekte\\projecthub\\projects\\MMOP_second_try`). ```powershell cd c:\Users\Chris4K\Projekte\projecthub\projects\MMOP_second_try ``` 2. Install the required Python dependencies: ```bash pip install gradio mcp aiohttp asyncio ``` (Ensure other project-specific dependencies from your `requirements.txt` are also installed). ### Running the Game Server Execute the main application file (assumed to be `app.py` in the root of `MMOP_second_try`): ```bash python app.py ``` The server should start, typically making the Gradio UI available at `http://127.0.0.1:7868` and the MCP SSE endpoint at `http://127.0.0.1:7868/gradio_api/mcp/sse`. --- ## 🏗️ Architecture Overview (High-Level) * **Game Server (`app.py`)**: The main entry point. Initializes and runs the Gradio web interface, integrates game components, and likely hosts the MCP endpoint. * **Game Engine (`src/core/game_engine.py`)**: Contains the core game logic, manages world state, player data, NPC interactions, and game rules. * **UI Layer (`src/ui/interface_manager.py`, `src/ui/huggingface_ui.py`)**: Manages the Gradio user interface, defining layouts, components, and event handling for human players. * **MCP Integration Layer**: A facade or service within the server that exposes game functionalities to MCP clients. This allows AI agents or other external systems to interact with the game. * **NPC Addons**: Modular components that extend NPC functionalities. See `NPC_Addon_Development_Guide.md`. --- ## 🔌 MCP API Reference The game server exposes its functionalities via the Model Context Protocol (MCP), allowing external clients (like AI agents or custom tools) to interact with the game world programmatically. ### Connection * **Endpoint URL**: `http://127.0.0.1:7868/gradio_api/mcp/sse` (for Server-Sent Events) * **Protocol**: MCP over SSE. * **Client Implementation**: Refer to `simple_game_client.py` for a reference Python client. It uses `mcp.ClientSession` and `mcp.client.sse.sse_client`. **Example Connection Snippet (from `simple_game_client.py`):** ```python from mcp import ClientSession from mcp.client.sse import sse_client from contextlib import AsyncExitStack import asyncio class GameClient: def __init__(self, server_url="http://127.0.0.1:7868/gradio_api/mcp/sse"): self.server_url = server_url self.session = None self.exit_stack = AsyncExitStack() self.connected = False self.tools = [] async def connect(self): try: transport = await self.exit_stack.enter_async_context( sse_client(self.server_url) ) read_stream, write_callable = transport self.session = await self.exit_stack.enter_async_context( ClientSession(read_stream, write_callable) ) await self.session.initialize() response = await self.session.list_tools() self.tools = response.tools self.connected = True print(f"✅ Connected! Available tools: {[tool.name for tool in self.tools]}") return True except Exception as e: print(f"❌ Connection failed: {e}") return False async def disconnect(self): if self.connected: await self.exit_stack.aclose() self.connected = False print("🔌 Disconnected.") ``` ### Available Tools/Commands Upon connection, the client can list available tools (commands) from the server. Common tools exposed by the MMORPG server typically include: * `register_ai_agent` (or similar): To join the game as a new player/agent. * `move_agent` (or similar): To move the player/agent in the game world. * `send_chat_message` (or similar): To send messages to the public game chat. * `interact_with_npc` (or similar): To send messages or commands to specific NPCs. * `get_game_state` (or similar): To retrieve information about the current game world, other players, etc. The exact names and parameters of these tools are defined by the server-side MCP implementation. Use `session.list_tools()` to get the current list and `tool.parameters_json_schema` for expected inputs. ### Common Operations **1. Registering a Player/Agent:** * **Tool**: Look for a tool like `register_ai_agent`. * **Parameters**: Typically `player_name` (string) and `client_id` (string, unique identifier for the client). * **Response**: Often includes an `agent_id` or `player_id` assigned by the server. **2. Moving a Player/Agent:** * **Tool**: Look for a tool like `move_agent`. * **Parameters**: `agent_id` (string) and `direction` (string, e.g., "north", "south", "east", "west", "up", "down"). * **Response**: Confirmation of movement, new coordinates, or error if movement is not possible. **3. Sending Chat Messages:** * **Tool**: Look for a tool like `send_chat_message`. * **Parameters**: `agent_id` (string) and `message` (string). * **Response**: Confirmation that the message was sent. **4. Interacting with NPCs:** * **Tool**: Look for a tool like `interact_with_npc`. * **Parameters**: `agent_id` (string), `npc_id` (string), and `message` or `command` (string). * **Response**: NPC's reply or result of the interaction. **5. Getting Game State:** * **Tool**: Look for a tool like `get_game_state`. * **Parameters**: May include `agent_id` (string) or be parameterless. * **Response**: JSON object containing game world information, list of players, NPCs, etc. **Example MCP Tool Usage:** ```python # Register as AI agent response = await session.call_tool("register_ai_agent", { "player_name": "MyBot", "client_id": "bot_001" }) # Move the agent response = await session.call_tool("move_agent", { "agent_id": "bot_001", "direction": "north" }) # Send chat message response = await session.call_tool("send_chat_message", { "agent_id": "bot_001", "message": "Hello everyone!" }) ``` --- ## 🧩 Extending the Game ### NPC Add-on Development For creating new NPCs with custom behaviors and UI components, please refer to the **`NPC_Addon_Development_Guide.md`**. It provides a comprehensive, up-to-date guide covering the modern auto-registration system, working examples from the codebase, and best practices. ### Adding New Game Mechanics To introduce new core game mechanics: 1. **Game Engine (`src/core/game_engine.py`):** Implement the fundamental logic for the new mechanic here. This might involve modifying player states, world interactions, or introducing new entities. 2. **Facade Layer:** If the mechanic needs to be exposed to the UI or MCP clients, update or create methods in your game facade (e.g., `src/facades/game_facade.py`) to provide a clean interface to the engine's functionality. 3. **UI Integration (`src/ui/interface_manager.py`):** If human players should interact with this mechanic, add new UI elements and event handlers in the Gradio interface. 4. **MCP Exposure:** If AI agents or external clients should use this mechanic, expose the relevant facade methods as new MCP tools. --- ## 🤖 AI Agent Integration AI agents can connect to the MMORPG as players using an MCP client (like the one shown in `simple_game_client.py`). 1. **Connection**: The agent connects to the MCP SSE endpoint. 2. **Registration**: The agent registers itself, providing a name. 3. **Interaction**: The agent uses the available MCP tools to perceive the game state (`get_game_state`), move (`move_agent`), chat (`send_chat_message`), and interact with NPCs (`interact_with_npc`). 4. **Decision Making**: The agent's internal logic processes game state information and decides on actions to take. The `simple_game_client.py` script serves as a foundational example for building more sophisticated AI agents. --- ## 🐞 Debugging * **Server Logs**: Check the console output where `python app.py` is running for server-side errors, print statements, and game event logs. * **Gradio UI**: Use your web browser's developer tools (especially the console) to debug issues related to the Gradio interface and JavaScript (like the keyboard control script). * **MCP Client-Side**: Add extensive logging in your MCP client to trace requests sent to the server and responses received. Print the full content of MCP tool calls and results. * **Game State Dumps**: Periodically use the `get_game_state` MCP tool (if available) or implement a debug feature to dump the current game state to understand the situation from the server's perspective. * **Incremental Testing**: When developing new features or MCP tools, test them incrementally. ---