A Model Context Protocol (MCP) server that integrates with FoundryVTT, allowing AI assistants to interact with your tabletop gaming sessions. Query actors, roll dice, generate content, and manage your game world through natural language.
- Dice Rolling - Roll dice with standard RPG notation
- Data Querying - Search and inspect actors, items, scenes, and journal entries
- Game State - Access combat status, chat messages, user list, and world information
- Content Generation - Generate NPCs, loot tables, and rule lookups
- World Search - Full-text search across all game entities
- Live Connection - Socket.IO connection loads complete world state on connect
- Combat Tracking - Access initiative order and combat state
- User Awareness - See who's online and their current status
- Chat Messages - Read recent chat history
- Node.js 18+
- FoundryVTT server running with an active world
- MCP-compatible AI client (Claude Desktop, etc.)
Interactive Setup Wizard:
git clone <repository-url>
cd foundry-mcp-server
npm install
npm run setup-wizardThe setup wizard will:
- Automatically detect your FoundryVTT server
- Test connectivity and authentication
- Generate your
.envconfiguration file - Validate the complete setup
- Clone and install:
git clone <repository-url>
cd foundry-mcp-server
npm install- Configure environment:
cp .env.example .env
# Edit .env with your FoundryVTT details- Required environment variables:
FOUNDRY_URL=http://localhost:30000
FOUNDRY_USERNAME=your_username
FOUNDRY_PASSWORD=your_password- Test and start:
npm run test-connection # Verify setup
npm run build
npm startnpm run devThe MCP server connects to FoundryVTT via Socket.IO using a standard FoundryVTT user account. No custom modules are required for full game data access.
- Ensure FoundryVTT is running with an active world (not on the setup screen)
- Create or use an existing FoundryVTT user account with appropriate permissions
- Add credentials to your
.envfile:
FOUNDRY_URL=http://localhost:30000
FOUNDRY_USERNAME=your_username
FOUNDRY_PASSWORD=your_passwordThe server authenticates via a 4-step Socket.IO flow:
- Fetches the
/joinpage to obtain a session cookie - Extracts the session cookie from the response
- Resolves the username to a user ID (or uses
FOUNDRY_USER_IDif set) - Emits
joinGamewith credentials to receive the complete world state
Installing the Foundry Local REST API module adds 5 server monitoring tools (get_recent_logs, search_logs, get_system_health, diagnose_errors, get_health_status):
- In FoundryVTT: Setup > Add-on Modules > Install Module
- Paste:
https://github.com/laurigates/foundryvtt-mcp/releases/latest/download/module.json - Enable the module in your world and copy the generated API key
- Add to
.env:FOUNDRY_API_KEY=your_api_key_here
Your FoundryVTT user needs these permissions:
- View actors, items, scenes, and journals
- Access compendium data
- Use dice rolling API
Ask your AI assistant things like:
Dice Rolling:
- "Roll 1d20+5 for an attack roll"
- "Roll 4d6 drop lowest for ability scores"
- "Roll 2d10+3 for damage"
Game Data:
- "Show me all the NPCs in this scene"
- "Find magic weapons in the party's inventory"
- "What's the current combat initiative order?"
- "Search for healing potions"
Content Generation:
- "Generate a random NPC merchant"
- "Create loot for a CR 5 encounter"
- "Look up the grappling rules"
World Search:
- "Search the world for anything related to dragons"
- "Give me a summary of the current world state"
- "Who's online right now?"
search_actors- Find characters, NPCs, monstersget_actor_details- Detailed character informationsearch_items- Find equipment, spells, consumablesget_scene_info- Current scene detailssearch_journals- Search notes and handoutsget_journal- Retrieve a specific journal entryget_users- List online users and their statusget_combat_state- Combat state and initiative orderget_chat_messages- Recent chat history
search_world- Full-text search across all game entitiesget_world_summary- Overview of the current world staterefresh_world_data- Reload world data from FoundryVTT
roll_dice- Roll dice with any formulalookup_rule- Game rules and spell descriptions
generate_npc- Create random NPCsgenerate_loot- Create treasure appropriate for level
get_recent_logs- Retrieve filtered FoundryVTT logssearch_logs- Search logs with regex patternsget_system_health- Server performance and health metricsdiagnose_errors- Analyze errors with troubleshooting suggestionsget_health_status- Comprehensive health diagnostics
The server exposes these FoundryVTT resources:
foundry://actors- All actors in the worldfoundry://items- All items in the worldfoundry://scenes- All scenesfoundry://scenes/current- Current active scenefoundry://journals- All journal entriesfoundry://users- Online usersfoundry://combat- Active combat statefoundry://world/settings- World and campaign settingsfoundry://system/diagnostics- System diagnostics (requires REST API module)
Edit .env to customize:
# Logging
LOG_LEVEL=info # debug, info, warn, error
# Performance
FOUNDRY_TIMEOUT=10000 # Request timeout (ms)
FOUNDRY_RETRY_ATTEMPTS=3 # Retry failed requests- Limit FoundryVTT user permissions to minimum required
- Run server on internal network only
- Monitor logs for suspicious activity
The server includes diagnostic tools to help troubleshoot connection and performance issues:
Connection Testing:
# Test complete MCP connection and functionality
npm run test-connection
# Clean build and test setup
npm run setupDiagnostic Tools (via AI assistant):
- System Health: "Get the FoundryVTT system health status" (requires REST API module)
- Error Analysis: "Diagnose recent errors and provide recommendations" (requires REST API module)
- Log Search: "Search logs for 'connection' patterns in the last hour" (requires REST API module)
# Test FoundryVTT is accessible
curl http://localhost:30000
# Check server logs
npm run dev # Shows detailed logging"Failed to connect to FoundryVTT"
- Verify FOUNDRY_URL is correct
- Check if FoundryVTT is running with an active world
- Ensure the URL is accessible from where the MCP server runs
"Authentication failed"
- Verify username and password match a FoundryVTT user exactly (case-sensitive)
- Check user permissions in FoundryVTT
- Try setting
FOUNDRY_USER_IDto the 16-character document_id
"Tool not found" errors
- Update to latest server version
- Check tool name spelling
- Review available tools in logs
src/
├── config/ # Zod-validated configuration
├── foundry/
│ ├── auth.ts # Socket.IO 4-step authentication
│ ├── client.ts # FoundryVTT client with worldData cache
│ └── types.ts # TypeScript interfaces + WorldData
├── tools/
│ ├── definitions.ts # Tool schemas by category
│ ├── router.ts # Tool request routing
│ ├── resources.ts # MCP resource definitions
│ └── handlers/ # Per-tool handler implementations
├── diagnostics/ # Optional REST API diagnostics
├── utils/ # Logger, cache utilities
└── index.ts # MCP server entry point
- Define tool schema in
src/tools/definitions.ts - Add handler in
src/tools/handlers/ - Wire the handler in
src/tools/router.ts - Add TypeScript types in
src/foundry/types.tsif needed - Test with your AI assistant
# Run tests
npm test
# Run with coverage
npm run test:coverage
# Lint code
npm run lint# Development build
npm run build
# Clean build
npm run clean && npm run build| Variable | Required | Description | Default |
|---|---|---|---|
FOUNDRY_URL |
Yes | FoundryVTT server URL | - |
FOUNDRY_USERNAME |
Yes | FoundryVTT username | - |
FOUNDRY_PASSWORD |
Yes | FoundryVTT password | - |
FOUNDRY_USER_ID |
No | 16-char document _id (bypasses username resolution) |
- |
FOUNDRY_API_KEY |
No | REST API module key (enables diagnostics) | - |
LOG_LEVEL |
No | Logging verbosity | info |
NODE_ENV |
No | Environment mode | development |
FOUNDRY_TIMEOUT |
No | Request timeout (ms) | 10000 |
FOUNDRY_RETRY_ATTEMPTS |
No | Retry failed requests | 3 |
FOUNDRY_RETRY_DELAY |
No | Delay between retries (ms) | 1000 |
CACHE_ENABLED |
No | Enable response caching | true |
CACHE_TTL_SECONDS |
No | Cache duration (seconds) | 300 |
CACHE_MAX_SIZE |
No | Maximum cache entries | - |
{
"formula": "1d20+5",
"reason": "Attack roll against goblin"
}{
"query": "dragon",
"limit": 10
}{}{
"query": "goblin",
"type": "npc",
"limit": 10
}Add to your Claude Desktop MCP settings:
{
"mcpServers": {
"foundry": {
"command": "node",
"args": ["/path/to/foundry-mcp-server/dist/index.js"],
"env": {
"FOUNDRY_URL": "http://localhost:30000",
"FOUNDRY_USERNAME": "your_username",
"FOUNDRY_PASSWORD": "your_password"
}
}
}
}To enable optional diagnostics tools, add FOUNDRY_API_KEY to the env block:
{
"FOUNDRY_API_KEY": "your_api_key_here"
}import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
const transport = new StdioClientTransport({
command: "node",
args: ["./dist/index.js"],
});
const client = new Client(
{
name: "foundry-client",
version: "1.0.0",
},
{
capabilities: {},
},
);
await client.connect(transport);
// Roll dice
const result = await client.request({
method: "tools/call",
params: {
name: "roll_dice",
arguments: {
formula: "1d20+5",
reason: "Initiative roll",
},
},
});- Socket.IO authentication and world data loading
- Combat state tracking
- User awareness (online status)
- Journal access and search
- World-wide search across all entities
- Chat message history
- NPC and loot generation
- Rule lookups
- Combat management (start/end combat, advance initiative)
- Token manipulation (move, update status effects)
- Scene navigation and switching
- Character sheet editing (level up, add equipment)
- Journal entry creation and editing
- Macro execution and management
- Multi-world support
- Docker deployment
Complete API documentation is available in the docs/ directory, auto-generated from TypeScript source code and JSDoc comments.
Local development:
npm run docs # Generate documentation
npm run docs:serve # Generate and serve locallyOnline: Browse the docs/ folder in this repository or visit the GitHub Pages site (if enabled).
- FoundryClient API - Complete client documentation with examples
- TypeScript Interfaces - All data structures and type definitions
- Configuration - Environment variables and setup options
- Utilities - Helper functions and logging
- Usage Examples - Code samples for common operations
The documentation is automatically updated via GitHub Actions when source code changes.
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes and add tests
- Commit:
git commit -m 'Add amazing feature' - Push:
git push origin feature/amazing-feature - Open a Pull Request
- Use TypeScript strict mode
- Follow existing naming conventions
- Add JSDoc comments for public APIs
- Write tests for new functionality
- Use meaningful commit messages
MIT License - see LICENSE file for details.
npm run test-connection # Test FoundryVTT connectivity
npm run setup-wizard # Re-run interactive setupUse the get_health_status MCP tool for comprehensive diagnostics (requires REST API module), or check server logs during startup for detailed status information.
- Connection refused: Ensure FoundryVTT is running with an active world on the configured port
- Authentication failed: Verify username/password match a FoundryVTT user exactly
- Empty search results: Ensure a world is active (not on setup screen) and the user has view permissions
- World data not loading: Check that Socket.IO authentication completed successfully
Detailed troubleshooting guide: TROUBLESHOOTING.md
- Issues: GitHub Issues for bugs and feature requests
- Discord: FoundryVTT Discord #api-development
- Documentation: FoundryVTT API Docs
- Troubleshooting: TROUBLESHOOTING.md
- FoundryVTT team for the excellent VTT platform
- Anthropic for the Model Context Protocol
- The tabletop gaming community for inspiration and feedback