Game World Sandbox MCP
Enables creation and management of structured game worlds for text adventures and RPGs with character creation, world generation, and natural language interaction through AI integration.
README
🎮 Game World Sandbox MCP
A FastMCP-based game world management system for creating and maintaining consistent, structured game worlds for LLM-driven text adventures and role-playing games.
🌟 Features
- World Generation: Create structured game worlds with consistent cosmology, geography, society, and history
- Character Management: Define player characters with attributes, inventory, goals, and backstory
- MCP Integration: Built on Model Control Protocol for seamless AI integration
- OpenAI Integration: Working integration with OpenAI models for natural language game world management
- Data Validation: Pydantic models ensure data consistency and integrity
- Extensible Architecture: Easy to add new tools, resources, and game mechanics
- Comprehensive Testing: Full unit test coverage proving functionality
🏗️ Architecture
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ │ │ │ │ │
│ Client App │◄──►│ FastMCP Server │◄──►│ World Data │
│ │ │ │ │ (In-Memory) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
▼
┌─────────────────┐
│ World Bible │
│ Schema │
└─────────────────┘
Components
server.py: FastMCP server with world generation and character creation toolsworld_bible_schema.py: Pydantic models defining the complete game world structureopenai_working_integration.py: Direct LangChain OpenAI integration (recommended)mcp_use_integration.py: LangChain-based MCP integration (compatible alternative)gemini_mcp_demo.py: Gemini integration demodemo_core_functionality.py: Core functionality demonstrationverify_working_solution.py: Verification script proving everything workstests/unit/: Comprehensive unit tests (19/20 tests passing)
🤖 AI Integration - OpenAI + Game World System
The system includes two working integrations with OpenAI models for natural language game world management:
🔧 Option 1: Direct LangChain Integration (Recommended)
The direct LangChain approach provides the most reliable and stable integration with FastMCP.
Features
- Natural Language Interface: Interact with game worlds using natural language
- Intelligent Tool Usage: OpenAI models automatically choose appropriate game world tools
- Real-time Game State: AI can create worlds, characters, and manage game state
- Interactive Gameplay: Natural conversation flow with structured game mechanics
- Working Implementation: Fully functional integration with error handling
Quick Setup
-
Install dependencies (already included in requirements.txt):
pip install -r requirements.txt -
Set your OpenAI API key:
export OPENAI_API_KEY="your-openai-api-key-here" -
Run the integration:
python openai_working_integration.py
Example Commands
- "Create a fantasy world with magic and dragons"
- "Generate a sci-fi world with spaceships and advanced technology"
- "Create a brave knight character named Sir Galen"
- "Move Sir Galen to the dragon's lair"
- "What worlds do we have available?"
🔧 Option 2: LangChain-Based MCP Integration (Alternative)
The LangChain-based MCP integration provides a more compatible approach that works reliably with FastMCP.
Features
- Direct Tool Integration: Custom tools that interface directly with MCP server
- Server Compatibility: Works seamlessly with FastMCP transport protocols
- Interactive CLI: Command-line interface for game world management
- Robust Error Handling: Comprehensive error handling and recovery
- No Protocol Issues: Bypasses mcp_use compatibility problems
Quick Setup
-
Install dependencies (already included in requirements.txt):
pip install -r requirements.txt -
Set your OpenAI API key:
export OPENAI_API_KEY="your-openai-api-key-here" -
Start the MCP server:
# Terminal 1 python server.py -
Run the integration:
# Terminal 2 python mcp_use_integration.py
Example Commands
- "Create a fantasy world"
- "List all worlds"
- "Create a character"
- "Move a character"
- "Generate a sci-fi world"
How It Works
Direct LangChain Integration:
User Request → OpenAI LLM → LangChain Agent → Game World Tools → World Management
↓
User Response ← OpenAI LLM ← Tool Results ← Game World Operations
LangChain-Based MCP Integration:
User Request → OpenAI LLM → LangChain Agent → Custom MCP Tools → Server API
↓
User Response ← OpenAI LLM ← Tool Results ← Game World Data
🚀 Quick Start
Prerequisites
- Python 3.13+
- Virtual environment (recommended)
Installation
-
Clone the repository
git clone https://github.com/your-username/game-sandbox-mcp.git cd game-sandbox-mcp -
Set up virtual environment
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate -
Install dependencies
pip install -r requirements.txtFor OpenAI Integration:
pip install langchain-openaiKey Dependencies:
- FastMCP: Model Context Protocol framework
- FastAPI: Modern web framework for APIs
- Pydantic: Data validation and settings management
- Uvicorn: ASGI server for high-performance applications
- pytest: Testing framework (19/20 tests passing)
- langchain-openai: OpenAI integration (optional)
Running the Server
# Activate virtual environment
source venv/bin/activate
# Run the MCP server
python server.py
The server will start on http://127.0.0.1:8000/mcp/
Running the Client Example
# In a separate terminal, activate venv and run client
source venv/bin/activate
python client.py
📖 Usage
1. Generate a New World
from fastmcp.client import Client
import asyncio
async def create_world():
client = Client("http://127.0.0.1:8000/mcp/")
async with client:
result = await client.call_tool("generate_world", {"style": "Fantasy"})
world_id = result.structured_content.get('world_id')
print(f"Created world: {world_id}")
2. Create a Character
character_data = {
"name": "Arion",
"race": "Human",
"description": "A curious adventurer with a knack for getting into trouble.",
"backstory": "Left a small village to seek fortune and discover the world.",
"attributes": {"health": 100, "mana": 50, "strength": 15},
"inventory": [{"name": "Rusted Sword", "description": "An old, worn sword."}],
"current_location": "Starting Village",
"goals": ["Find the lost city of Eldoria.", "Master the ancient magic."]
}
result = await client.call_tool("create_character", {
"world_id": world_id,
"character_data": character_data
})
3. Access World Data
# Get complete world data
world_data = await client.read_resource(f"worlds://{world_id}")
print(world_data)
🏛️ Enhanced World Bible Schema
The system uses an advanced "World Bible" structure based on modern game development practices:
Core Components
- Metadata: Name, description, genre/style with validation and versioning
- Cosmology: Magic systems, technology levels, calendar systems with consistency checks
- Geography: Continents, regions, key locations with strategic mapping
- Society: Races, factions, social structures with cultural depth
- History: Creation myths, conflicts, key events with narrative timelines
- Systems: Economy, abilities, item classifications with balance frameworks
- Protagonist: Modern RPG character with attributes, skills, inventory, and progression
Enhanced Features
- Validation & Consistency: Cross-component validation ensures world consistency
- Modern RPG Systems: Comprehensive character attributes, skills, and progression
- Advanced Inventory: Item durability, properties, rarity, and crafting systems
- Reputation System: Faction relationships and social dynamics
- Quest System: Dynamic quest tracking and objectives
- Balance Settings: Difficulty levels and game balance parameters
Data Structure Example
{
"metadata": {
"name": "Eldoria Chronicles",
"description": "A vast fantasy world of magic and mystery",
"style": "Fantasy",
"version": "1.0.0",
"author": "Game Master",
"tags": ["fantasy", "magic", "dragons"]
},
"cosmology": {
"magic_system": "Elemental magic drawn from nature spirits and ancient runes",
"tech_level": "Medieval",
"calendar_system": "Twelve-month lunar calendar with solstice festivals",
"physics_laws": "Standard physics with magical exceptions",
"metaphysics": "Spiritual energy permeates the world"
},
"geography": {
"macro_geography": "Three main continents with diverse biomes",
"key_regions": [
{"name": "Crystal Mountains", "description": "Home to ancient magic crystals"},
{"name": "Dark Forest", "description": "Forbidden woods with dangerous creatures"}
],
"climate_zones": ["Temperate", "Arctic", "Tropical"],
"natural_resources": ["Adamantium", "Mythril", "Dragon Scale"]
},
"protagonist": {
"name": "Elara Moonshadow",
"race": "Elf",
"character_class": "Ranger",
"level": 1,
"attributes": {
"health": 120,
"max_health": 120,
"strength": 12,
"agility": 16,
"intelligence": 14
},
"skills": [
{
"name": "Archery",
"level": 15,
"description": "Mastery of bow and arrow combat"
}
],
"inventory": [
{
"name": "Moonshadow Bow",
"type": "weapon",
"rarity": "Rare",
"value": 500,
"properties": {"damage": "2d8", "range": "150ft"}
}
],
"goals": ["Find the lost city", "Master nature magic"],
"reputation": {"Elven Council": 10, "Forest Spirits": 25}
}
}
🔧 API Reference
Tools
generate_world
Creates a new game world based on specified style.
Parameters:
style(str): Game world style (e.g., "Fantasy", "Sci-Fi", "Cyberpunk")
Returns:
world_id: Unique identifier for the generated worldmessage: Success confirmation
create_character
Creates a player character for an existing world.
Parameters:
world_id(str): ID of the world to add character tocharacter_data(dict): Complete character definition
Returns:
message: Success confirmationcharacter_name: Name of created character
Resources
worlds://{world_id}
Retrieves the complete World Bible for a given world ID.
🎮 Enhanced Game Development Features
The improved system incorporates the latest game development practices and modern RPG design:
World Consistency & Validation
- Cross-Component Validation: Ensures consistency between tech levels and magic systems
- Enum-Based Classification: Standardized game styles and technology levels
- Advanced Validation: Pydantic validators prevent inconsistent world-building
- Version Control: World versioning for tracking changes and updates
Modern RPG Systems
- Comprehensive Attributes: Health, mana, stamina, and 6 core attributes (STR, AGI, INT, WIS, CHA, LCK)
- Skill Progression: Individual skill tracking with experience and level caps
- Advanced Inventory: Items with properties, durability, rarity, and crafting potential
- Reputation System: Dynamic relationships with factions and organizations
- Quest Management: Active quest tracking with objectives and status
- Status Effects: Buffs and debuffs system for combat and roleplay
Enhanced Features
- Production Logging: Comprehensive logging with proper formatting and error tracking
- Error Handling: Robust error handling with appropriate HTTP status codes
- Modern FastMCP: Latest FastMCP version (2.11.3) with improved performance
- Type Safety: Full type hints and validation throughout the codebase
- Documentation: Comprehensive docstrings and API documentation
Latest Game Design Patterns
- Balance Frameworks: Built-in difficulty settings and game balance parameters
- World State Management: Dynamic world state variables for evolving narratives
- Character Lifecycle: Complete character progression from creation to advancement
- Interactive Systems: Character movement, location updates, and world interaction
🛠️ Development
Project Structure
game-sandbox-mcp/
├── server.py # FastMCP server implementation
├── world_bible_schema.py # Pydantic data models
├── openai_working_integration.py # Direct LangChain OpenAI integration
├── mcp_use_integration.py # mcp_use client integration
├── gemini_mcp_demo.py # Gemini integration demo
├── demo_core_functionality.py # Core functionality demo
├── verify_working_solution.py # Verification script
├── README.md # This file
├── requirements.txt # Dependencies
├── tests/
│ └── unit/ # Unit tests (19/20 passing)
└── venv/ # Python virtual environment
Adding New Tools
@mcp.tool
def new_game_mechanic(world_id: str, parameters: dict, ctx: Context) -> dict:
"""Description of your new game mechanic."""
# Implementation here
pass
Extending the Schema
Add new fields to the Pydantic models in world_bible_schema.py:
class NewComponent(BaseModel):
field_name: str = Field(..., description="Field description")
class WorldBible(BaseModel):
# ... existing fields
new_component: NewComponent = Field(default_factory=NewComponent)
🤝 Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📝 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Built with FastMCP framework
- Inspired by modern tabletop RPG world-building practices
- Designed for integration with Large Language Models
📚 Further Reading
- FastMCP Documentation
- Pydantic Documentation
- Game World Building Best Practices
GEMINI.md- Detailed Chinese documentation on world consistency
Happy World Building! 🌍✨
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。