故事生成器MCP🎮📚
用于AI驱动的交互式故事讲述的MCP(模型上下文协议)服务器。通过自然语言互动创建个性化的“选择自己的冒险”故事。
🌟 特性
- MCP服务器:通过模型上下文协议公开故事生成工具
- AI驱动:使用OpenAI GPT-4o-mini生成创意故事
- 交互式:做出影响故事方向和结果的选择
- 持久化存储:SQLite数据库存储故事以供将来参考
- FastAPI后端:用于故事管理的RESTful API
🏗️ 建筑
storybuilder_MCP/
├── backend/
│ ├── core/ # Core business logic
│ ├── routers/ # API endpoints
│ ├── models/ # Database models
│ ├── schemas/ # Pydantic schemas
│ ├── db/ # Database setup
│ ├── main.py # FastAPI application
│ └── mcp_server.py # MCP server implementation
├── start_backend.sh # Backend startup script
└── README.md🚀 快速开始
先决条件
- Python 3.8+
- OpenAI API密钥
- Node.js(用于MCP检查器)
安装
- 克隆和设置
cd storybuilder_MCP/backend
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt- 配置环境
# Create .env file in backend directory
cat > backend/.env << EOF
DATABASE_URL=sqlite:///./databse.db
API_PREFIX=/api
DEBUG=True
ALLOWED_ORIGINS=*
OPENAI_API_KEY=your_openai_api_key_here
EOF- 启动后端
./start_backend.sh后端将运行http://127.0.0.1:8547
- 使用MCP检查员进行测试
npx @modelcontextprotocol/inspector \
backend/venv/bin/python \
backend/mcp_server.py🤖 MCP工具
MCP服务器公开 7工具 与满 Pydantic响应模型 对于类型安全代理集成:
| 工具 | 描述 | 返回 |
|---|---|---|
list_stories | 列出所有可用的故事 | ListStoriesResponse |
create_story | 生成一个有主题的新故事 | CreateStoryResponse |
check_job_status | 检查故事生成进度 | JobStatusResponse |
get_story | 检索并加载完整的故事 | GetStoryResponse |
make_choice | 做出互动故事选择 | MakeChoiceResponse |
get_current_status | 获取当前游戏状态 | CurrentStatusResponse |
list_available_options | 列出可用选项 | ListOptionsResponse |
所有回复均为 Pydantic模型 与:
- ✅ 类型安全和验证
- ✅ JSON序列化
- ✅ 结构化字段访问
- ✅ 与Pydantic AI试剂兼容
🎯 多步骤工作流
理解故事创作流程
故事生成 异步.遵循以下工作流程:
1. CREATE → 2. WAIT → 3. LOAD → 4. PLAY分步示例:
# STEP 1: CREATE - Start story generation
response = create_story("space adventure with aliens")
job_id = response.job_id # Save this!
# STEP 2: WAIT - Poll until complete (story generation takes ~10-20 seconds)
import time
while True:
status = check_job_status(job_id)
if status.status == "completed":
story_id = status.story_id # Get the story ID
break
elif status.status == "failed":
print(f"Error: {status.error}")
break
time.sleep(2) # Wait 2 seconds between checks
# STEP 3: LOAD - Load the story into game state
story = get_story(story_id)
print(f"📖 {story.title}")
print(story.current_content)
# STEP 4: PLAY - Make choices interactively
while not story.is_ending:
# Show available options
options = list_available_options()
for opt in options.options:
print(f"{opt['number']}. {opt['text']}")
# Make a choice
choice = make_choice("investigate") # Or any option text
print(choice.current_content)
if choice.is_ending:
print(f"🎉 Story ended! Won: {choice.is_winning_ending}")
break⚠️ 代理商须知
- 异步模式:故事创作不是瞬间的。必须投票
check_job_status() - 状态管理:必须致电
get_story()之前make_choice() - 可选字段:始终检查
if response.success:在访问字段之前 - 模糊匹配:
make_choice()接受部分文本匹配(不区分大小写)
📡 API终点
故事管理
GET /api/stories/- 列出所有故事 ⭐ 新POST /api/stories/create-创建一个主题的新故事GET /api/stories/{story_id}/complete-获取完整的故事细节POST /api/stories/{story_id}/choice-选择故事
作业管理
GET /api/jobs/{job_id}-获取作业状态和详细信息
健康检查
GET /health-API健康检查
🧪 使用cURL进行测试
完整工作流示例
# 1. List existing stories
curl -s http://127.0.0.1:8547/api/stories/ | python3 -m json.tool
# 2. Create a new story
curl -X POST http://127.0.0.1:8547/api/stories/create \
-H "Content-Type: application/json" \
-d '{"theme": "space adventure with aliens"}' | python3 -m json.tool
# Returns: {"job_id": "abc-123", "status": "pending", ...}
# 3. Check job status (repeat until completed)
curl -s http://127.0.0.1:8547/api/jobs/abc-123 | python3 -m json.tool
# Returns: {"status": "completed", "story_id": 8, ...}
# 4. Get the complete story
curl -s http://127.0.0.1:8547/api/stories/8/complete | python3 -m json.tool
# Returns full story with options🎯 示例用例
太空探险
{"theme": "space adventure with aliens and mysterious planets"}中世纪幻想
{"theme": "medieval fantasy with dragons and magic"}侦探之谜
{"theme": "detective mystery in Victorian London"}科幻惊悚片
{"theme": "cyberpunk thriller with AI and corporate espionage"}🔧 配置
环境变量 backend/.env:
| 变量 | 描述 | 默认值 |
|---|---|---|
DATABASE_URL | SQLite数据库路径 | sqlite:///./databse.db |
API_PREFIX | API路由前缀 | /api |
DEBUG | 启用调试模式 | True |
ALLOWED_ORIGINS | CORS允许的来源 | * |
OPENAI_API_KEY | OpenAI API密钥 | 必需 |
📦 依赖项
- FastAPI -Web框架
- 优维康 -ASGI服务器
- SQLAlchemy -ORM
- 兰开夏 -OpenAI集成
- fastmcp -MCP服务器框架
- 皮丹提克 -数据验证和响应模型
- 请求: -MCP工具的HTTP客户端
🔍 验证和测试
验证Pydantic模式
python validate_schemas.py这验证了以下所有9个Pydantic响应模型:
- 模型实例化
- JSON序列化/反序列化
- 类型安全性
- 模式生成
测试后端API
# Health check
curl http://127.0.0.1:8547/health
# API documentation
open http://127.0.0.1:8547/docs🛠️ 发展
仅运行后端
cd backend
source venv/bin/activate
python main.py运行MCP检查器
npx @modelcontextprotocol/inspector \
$(pwd)/backend/venv/bin/python \
$(pwd)/backend/mcp_server.pyAPI文档
后端运行时,请访问:
- Swagger用户界面:http://127.0.0.1:8547/docs
- 重新记录:http://127.0.0.1:8547/redoc
📝 许可证
MIT许可证
🙏 致谢
______________________________________________________________________
快乐讲故事! 🎭✨
