blackjack-mcp-server
v1.0.2
Published
Professional-grade Blackjack MCP server with multi-player support, advanced rule variations, and comprehensive game management
Downloads
12
Maintainers
Readme
Blackjack MCP Server
A professional-grade Blackjack MCP (Model Context Protocol) server with comprehensive multi-player support, advanced rule variations, and complete game management capabilities.
🎯 Features
Game Features
- Multi-player support - Up to 7 players per game
- Advanced rule variations - Dealer hits soft 17, surrender, insurance, double after split
- Complete blackjack logic - Proper Ace handling, splitting, doubling, insurance
- Cryptographically secure shuffling - Fisher-Yates shuffle with crypto.randomBytes
- Multiple deck support - 1-8 decks with configurable penetration
Technical Features
- MCP Protocol Compliance - Full support for tools and resources
- Transaction System - Complete audit trails and payout calculations
- Event System - Real-time game flow coordination
- Persistence Layer - Save/load games with versioning and compression
- Comprehensive Validation - Input validation and business rule enforcement
- TypeScript Support - Full type safety and excellent developer experience
Management Features
- Game State Management - Complete game state tracking and validation
- Player Statistics - Detailed performance analytics and history
- Basic Strategy Helper - Built-in strategy recommendations
- House Edge Calculator - Analysis tools for different rule variations
- Administrative Tools - Game management and monitoring capabilities
🚀 Quick Start
Installation
# Install globally via npx (recommended)
npx @accounts_mgk/blackjack-mcp-server
# Or install as a dependency
npm install @accounts_mgk/blackjack-mcp-server
# Or install globally
npm install -g @accounts_mgk/blackjack-mcp-serverBasic Usage
As a Standalone Server
# Start the server
blackjack-mcp-server
# With custom configuration
BLACKJACK_LOG_LEVEL=debug BLACKJACK_SAVES_PATH=./my-saves blackjack-mcp-serverProgrammatic Usage
import { BlackjackMCPServer } from '@accounts_mgk/blackjack-mcp-server';
const server = new BlackjackMCPServer({
logLevel: 'info',
persistence: {
enabled: true,
path: './saves'
}
});
await server.start();🛠 MCP Tools
The server provides comprehensive tools for game management:
Game Management Tools
blackjack.create_game- Create a new blackjack gameblackjack.join_game- Join an existing gameblackjack.leave_game- Leave a gameblackjack.start_game- Start the betting phaseblackjack.end_game- End a game
Betting Tools
blackjack.place_bet- Place a bet for the current round
Player Action Tools
blackjack.hit- Request another cardblackjack.stand- Keep current hand valueblackjack.double_down- Double bet and receive one cardblackjack.split- Split a pair into two handsblackjack.surrender- Forfeit hand for half bet backblackjack.insurance- Place insurance bet when dealer shows Ace
Game Flow Tools
blackjack.deal_cards- Deal initial cards to all playersblackjack.dealer_play- Execute dealer's turnblackjack.resolve_round- Calculate payouts and end round
Utility Tools
blackjack.get_game_state- Retrieve current game stateblackjack.get_basic_strategy- Get strategy recommendationblackjack.save_game/blackjack.load_game- Persistence operationsblackjack.get_statistics- Player and game analytics
📊 MCP Resources
Access game data through structured resources:
Game Resources
blackjack://game/{gameId}/state- Complete game stateblackjack://game/{gameId}/public-state- Public view (no hole card)blackjack://game/{gameId}/rules- Game rules configurationblackjack://game/{gameId}/summary- High-level game status
Player Resources
blackjack://game/{gameId}/player/{playerId}- Player informationblackjack://game/{gameId}/player/{playerId}/statistics- Player statsblackjack://game/{gameId}/player/{playerId}/transactions- Transaction history
Transaction Resources
blackjack://game/{gameId}/transactions- All game transactionsblackjack://game/{gameId}/transactions/audit- Audit trail
Strategy Resources
blackjack://strategy/basic- Basic strategy chartblackjack://strategy/house-edge-calculator- House edge analysis
🎮 Usage Examples
Creating and Starting a Game
// Create a game with custom rules
const createResult = await mcpClient.callTool('blackjack.create_game', {
gameId: 'my-game-001',
rules: {
decks: 6,
minBet: 5,
maxBet: 500,
dealerHitsSoft17: true,
blackjackPayout: 1.5, // 3:2 payout
allowSurrender: true,
maxSplits: 3
}
});
// Add players
await mcpClient.callTool('blackjack.join_game', {
gameId: 'my-game-001',
playerId: 'player1',
playerName: 'Alice',
initialBalance: 1000
});
await mcpClient.callTool('blackjack.join_game', {
gameId: 'my-game-001',
playerId: 'player2',
playerName: 'Bob',
initialBalance: 500
});
// Start the game
await mcpClient.callTool('blackjack.start_game', {
gameId: 'my-game-001'
});Playing a Round
// Place bets
await mcpClient.callTool('blackjack.place_bet', {
gameId: 'my-game-001',
playerId: 'player1',
amount: 25
});
await mcpClient.callTool('blackjack.place_bet', {
gameId: 'my-game-001',
playerId: 'player2',
amount: 10
});
// Deal initial cards
await mcpClient.callTool('blackjack.deal_cards', {
gameId: 'my-game-001'
});
// Player actions (example)
await mcpClient.callTool('blackjack.hit', {
gameId: 'my-game-001',
playerId: 'player1',
handId: 'hand-id-from-game-state'
});
await mcpClient.callTool('blackjack.stand', {
gameId: 'my-game-001',
playerId: 'player2',
handId: 'hand-id-from-game-state'
});
// Dealer plays automatically when all players are done
await mcpClient.callTool('blackjack.dealer_play', {
gameId: 'my-game-001'
});Accessing Game Data
// Get current game state
const gameState = await mcpClient.readResource('blackjack://game/my-game-001/state');
// Get player statistics
const playerStats = await mcpClient.readResource('blackjack://game/my-game-001/player/player1/statistics');
// Get basic strategy recommendation
const strategy = await mcpClient.callTool('blackjack.get_basic_strategy', {
playerCards: [
{ suit: 'hearts', rank: 'A' },
{ suit: 'spades', rank: '6' }
],
dealerUpCard: { suit: 'diamonds', rank: '10' }
});Save and Load Games
// Save game
await mcpClient.callTool('blackjack.save_game', {
gameId: 'my-game-001',
filename: 'weekend-game',
includeTransactionHistory: true
});
// Load game
await mcpClient.callTool('blackjack.load_game', {
filename: 'weekend-game',
newGameId: 'restored-game-001'
});⚙️ Configuration
Environment Variables
BLACKJACK_LOG_LEVEL- Logging level (debug, info, warn, error)BLACKJACK_SAVES_PATH- Directory for saved games
Game Rules Configuration
interface GameRules {
decks: number; // 1-8 decks
minBet: number; // Minimum bet amount
maxBet: number; // Maximum bet amount
dealerHitsSoft17: boolean; // Dealer hits soft 17
blackjackPayout: number; // 1.5 for 3:2, 1.2 for 6:5
maxPlayers: number; // 1-7 players
allowSurrender: boolean; // Allow surrender option
allowDoubleAfterSplit: boolean; // Allow double down after split
allowResplitAces: boolean; // Allow resplitting aces
maxSplits: number; // Maximum splits allowed (1-4)
insurancePayout: number; // Insurance payout ratio (typically 2:1)
doubleDownRules: string; // 'any', 'hard9-11', 'hard10-11'
splitRules: string; // 'any', 'pairs-only'
penetration: number; // Deck penetration (0.1-0.9)
}Claude Desktop Integration
To use with Claude Desktop, add this configuration to your claude_desktop_config.json file (typically located at ~/.config/claude-desktop/claude_desktop_config.json):
{
"mcpServers": {
"blackjack-mcp-server": {
"display": {
"name": "Blackjack MCP Server",
"description": "Play professional blackjack, manage multi-player games, track statistics, save game states",
"default": true
},
"guidelines": [
"Use for realistic blackjack gameplay with advanced rule variations",
"Supports up to 7 players per table with persistent game states",
"Includes transaction tracking and statistical analysis"
],
"config": {
"command": "npx",
"args": ["@accounts_mgk/blackjack-mcp-server"],
"env": {
"BLACKJACK_LOG_LEVEL": "info",
"BLACKJACK_SAVES_PATH": "./blackjack-saves"
}
}
}
}
}Alternative for Global Installation:
If you've installed the package globally (npm install -g @accounts_mgk/blackjack-mcp-server), you can use:
{
"mcpServers": {
"blackjack-mcp-server": {
"display": {
"name": "Blackjack MCP Server",
"description": "Play professional blackjack, manage multi-player games, track statistics, save game states",
"default": true
},
"guidelines": [
"Use for realistic blackjack gameplay with advanced rule variations",
"Supports up to 7 players per table with persistent game states",
"Includes transaction tracking and statistical analysis"
],
"config": {
"command": "blackjack-mcp-server",
"args": []
}
}
}
}📈 Advanced Features
Transaction System
Complete audit trail with rollback capability:
// Get transaction history
const transactions = await mcpClient.readResource('blackjack://game/my-game-001/transactions');
// Get audit report
const auditReport = await mcpClient.callTool('blackjack.get_statistics', {
gameId: 'my-game-001',
includeHistory: true
});Event System
Real-time game flow coordination:
// Events are automatically emitted for all game actions
// GAME_CREATED, PLAYER_JOINED, BET_PLACED, CARDS_DEALT,
// PLAYER_ACTION, HAND_COMPLETED, DEALER_REVEAL, ROUND_COMPLETEDPersistence Layer
Automatic save/load with versioning:
// List all saved games
const savedGames = await mcpClient.callTool('blackjack.list_saved_games');
// Export multiple games
await mcpClient.callTool('blackjack.export_games', {
gameIds: ['game1', 'game2'],
exportPath: './backup.json'
});🔒 Security Features
- Input Validation - Comprehensive validation of all inputs
- Rate Limiting - Configurable rate limiting per user
- Audit Trails - Complete transaction and action logging
- Cryptographic Randomness - Secure card shuffling
- Balance Verification - Continuous balance reconciliation
🧪 Testing
# Install dependencies
npm install
# Run tests
npm test
# Build project
npm run build
# Development mode
npm run dev📚 API Reference
Core Classes
BlackjackMCPServer
Main server class that orchestrates all components.
BlackjackGameEngine
Complete blackjack game logic and rule enforcement.
TransactionManager
Financial transaction handling with audit trails.
EventSystem
Real-time event coordination and subscriptions.
GamePersistence
Save/load functionality with versioning.
HandCalculator
Advanced hand value calculations with Ace optimization.
DeckManager
Cryptographically secure deck management.
Error Codes
The server provides structured error codes for different scenarios:
INVALID_INPUT- Invalid input parametersGAME_NOT_FOUND- Game does not existPLAYER_NOT_FOUND- Player not in gameINSUFFICIENT_BALANCE- Not enough fundsINVALID_GAME_PHASE- Action not allowed in current phaseNOT_PLAYER_TURN- Not the player's turn
🤝 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.
🎯 Roadmap
- [ ] Tournament mode support
- [ ] Side bets (21+3, Perfect Pairs)
- [ ] Multi-hand per player
- [ ] Real-time WebSocket notifications
- [ ] Progressive jackpots
- [ ] Advanced analytics and reporting
- [ ] Mobile-optimized interfaces
- [ ] Internationalization support
💡 Use Cases
- Game Development - Integration into casino applications
- Educational Tools - Blackjack strategy learning
- Simulation - Monte Carlo analysis and testing
- Entertainment - Multi-player blackjack experiences
- Research - Game theory and probability studies
🔗 Links
📞 Support
For support, questions, or contributions:
- Create an issue on GitHub
- Check the documentation
- Review examples
Made with ♠️ by accounts_mgk
