npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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

Readme

Blackjack MCP Server

npm version License: 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

# 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

# Start the server
blackjack-mcp-server

# With custom configuration
BLACKJACK_LOG_LEVEL=debug BLACKJACK_SAVES_PATH=./my-saves blackjack-mcp-server

Programmatic 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 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

// 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_COMPLETED

Persistence 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 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 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:


Made with ♠️ by accounts_mgk