blackjack-mcp-server
Version: 
Professional-grade Blackjack MCP server with multi-player support, advanced rule variations, and comprehensive game management
480 lines (374 loc) โข 14 kB
Markdown
# Blackjack MCP Server
[](https://badge.fury.io/js/%40accounts_mgk%2Fblackjack-mcp-server)
[](https://opensource.org/licenses/MIT)
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
```bash
# 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-server
```
### Basic Usage
#### As a Standalone Server
```bash
# Start the server
blackjack-mcp-server
# With custom configuration
BLACKJACK_LOG_LEVEL=debug BLACKJACK_SAVES_PATH=./my-saves blackjack-mcp-server
```
#### Programmatic Usage
```typescript
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 game
- `blackjack.join_game` - Join an existing game
- `blackjack.leave_game` - Leave a game
- `blackjack.start_game` - Start the betting phase
- `blackjack.end_game` - End a game
### Betting Tools
- `blackjack.place_bet` - Place a bet for the current round
### Player Action Tools
- `blackjack.hit` - Request another card
- `blackjack.stand` - Keep current hand value
- `blackjack.double_down` - Double bet and receive one card
- `blackjack.split` - Split a pair into two hands
- `blackjack.surrender` - Forfeit hand for half bet back
- `blackjack.insurance` - Place insurance bet when dealer shows Ace
### Game Flow Tools
- `blackjack.deal_cards` - Deal initial cards to all players
- `blackjack.dealer_play` - Execute dealer's turn
- `blackjack.resolve_round` - Calculate payouts and end round
### Utility Tools
- `blackjack.get_game_state` - Retrieve current game state
- `blackjack.get_basic_strategy` - Get strategy recommendation
- `blackjack.save_game` / `blackjack.load_game` - Persistence operations
- `blackjack.get_statistics` - Player and game analytics
## ๐ MCP Resources
Access game data through structured resources:
### Game Resources
- `blackjack://game/{gameId}/state` - Complete game state
- `blackjack://game/{gameId}/public-state` - Public view (no hole card)
- `blackjack://game/{gameId}/rules` - Game rules configuration
- `blackjack://game/{gameId}/summary` - High-level game status
### Player Resources
- `blackjack://game/{gameId}/player/{playerId}` - Player information
- `blackjack://game/{gameId}/player/{playerId}/statistics` - Player stats
- `blackjack://game/{gameId}/player/{playerId}/transactions` - Transaction history
### Transaction Resources
- `blackjack://game/{gameId}/transactions` - All game transactions
- `blackjack://game/{gameId}/transactions/audit` - Audit trail
### Strategy Resources
- `blackjack://strategy/basic` - Basic strategy chart
- `blackjack://strategy/house-edge-calculator` - House edge analysis
## ๐ฎ Usage Examples
### Creating and Starting a Game
```javascript
// 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
```javascript
// 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
```javascript
// 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
```javascript
// 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
```typescript
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`):
```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:
```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": "blackjack-mcp-server",
        "args": []
      }
    }
  }
}
```
## ๐ Advanced Features
### Transaction System
Complete audit trail with rollback capability:
```javascript
// 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:
```javascript
// Events are automatically emitted for all game actions
// GAME_CREATED, PLAYER_JOINED, BET_PLACED, CARDS_DEALT, 
// PLAYER_ACTION, HAND_COMPLETED, DEALER_REVEAL, ROUND_COMPLETED
```
### Persistence Layer
Automatic save/load with versioning:
```javascript
// 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
```bash
# 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 parameters
- `GAME_NOT_FOUND` - Game does not exist  
- `PLAYER_NOT_FOUND` - Player not in game
- `INSUFFICIENT_BALANCE` - Not enough funds
- `INVALID_GAME_PHASE` - Action not allowed in current phase
- `NOT_PLAYER_TURN` - Not the player's turn
## ๐ค Contributing
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## ๐ License
This project is licensed under the MIT License - see the [LICENSE](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
- [npm package](https://www.npmjs.com/package/@accounts_mgk/blackjack-mcp-server)
- [GitHub repository](https://github.com/accounts_mgk/blackjack-mcp-server)
- [MCP Protocol Documentation](https://modelcontextprotocol.io/)
- [Basic Blackjack Strategy](https://en.wikipedia.org/wiki/Blackjack_basic_strategy)
## ๐ Support
For support, questions, or contributions:
- Create an issue on [GitHub](https://github.com/accounts_mgk/blackjack-mcp-server/issues)
- Check the [documentation](https://github.com/accounts_mgk/blackjack-mcp-server/wiki)
- Review [examples](https://github.com/accounts_mgk/blackjack-mcp-server/tree/main/examples)
---
**Made with โ ๏ธ by accounts_mgk**