kabusapi-mcp-server

zakuzakuzaki/kabusapi-mcp-server

3.1

If you are the rightful owner of kabusapi-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.

Kabu Station API MCP Server is a secure, production-ready server that integrates AI assistants with Japanese securities trading via the Kabu Station API.

Kabu Station API MCP Server

A secure, production-ready MCP (Model Context Protocol) server that provides AI assistants with access to Japanese securities trading through the Kabu Station API.

๐Ÿš€ Features

Core Functionality

  • Secure Authentication - Token management with encryption and auto-reauthentication
  • Trading Operations - Place, cancel, and track stock orders with risk management
  • Market Data - Real-time price data, market analysis, and ranking information
  • Portfolio Management - Position tracking, performance analytics, and risk assessment
  • Rate Limiting - Built-in request throttling to respect API limits

Security Features

  • Encrypted Token Storage - AES-256-CBC encryption for sensitive data
  • Input Validation - Comprehensive parameter validation and sanitization
  • Request Rate Limiting - Token bucket algorithm for API protection
  • Connection Pooling - Efficient HTTP connection management
  • Automatic Retry - Exponential backoff for transient failures

๐Ÿ“‹ Prerequisites

  • Node.js 18+
  • TypeScript 4.9+
  • Kabu Station API account and credentials
  • Jest for testing (included in dev dependencies)

๐Ÿ›  Installation

# Clone the repository
git clone <repository-url>
cd kabusapi-mcp-server

# Install dependencies
npm install

# Build the project
npm run build

โš™๏ธ Configuration

Environment Variables

Create a .env file in the project root:

# Kabu Station API Configuration
KABUS_HOST=localhost
KABUS_PORT=18080
KABUS_PASSWORD=your_api_password

# Server Configuration  
MCP_SERVER_PORT=3000
LOG_LEVEL=info

# Security Configuration
ENCRYPTION_KEY=your_32_byte_encryption_key
TOKEN_REFRESH_THRESHOLD=300000

# Rate Limiting
REQUESTS_PER_SECOND=10
BURST_LIMIT=20

Configuration File

Alternatively, create config/config.json:

{
  "kabustation": {
    "host": "localhost",
    "port": 18080,
    "timeout": 10000
  },
  "mcp": {
    "serverPort": 3000,
    "toolTimeout": 30000
  },
  "security": {
    "tokenRefreshThreshold": 300000,
    "maxRetries": 3
  },
  "logging": {
    "level": "info",
    "format": "json"
  }
}

๐Ÿš€ Usage

Starting the Server

# Development mode
npm run dev

# Production mode
npm start

Basic API Usage

import { 
  TradingService, 
  MarketDataService, 
  PositionService,
  KabusapiClient 
} from './src/index.js';

// Initialize API client
const client = new KabusapiClient({
  host: 'localhost',
  port: 18080,
  timeout: 10000
});

// Initialize services
const tradingService = new TradingService(client);
const marketDataService = new MarketDataService(client);
const positionService = new PositionService(client);

// Authenticate
await client.authenticate('your_password');

// Place a buy order
const orderResult = await tradingService.placeBuyOrder({
  symbol: '9984',
  exchange: 1,
  side: 'buy',
  quantity: 100,
  price: 9500,
  orderType: 'limit'
});

// Get market data
const boardData = await marketDataService.getBoardData('9984');
console.log(`Current price: ${boardData.currentPrice}`);

// Check portfolio
const portfolio = await positionService.getPortfolioSummary();
console.log(`Total P&L: ${portfolio.totalUnrealizedPL}`);

๐Ÿงช Testing

# Run all tests
npm test

# Run tests with coverage
npm run test:coverage

# Run specific test suites
npm test -- tests/business/
npm test -- tests/security/
npm test -- tests/api/

# Run tests in watch mode
npm run test:watch

Test Coverage

The project maintains comprehensive test coverage:

  • Business Logic: 41 tests covering trading, market data, and positions
  • Security Layer: 42 tests covering encryption, validation, and storage
  • API Integration: 12 tests covering HTTP clients and rate limiting
  • Configuration: 9 tests covering config management
  • Total: 145+ passing tests

๐Ÿ“š API Documentation

Trading Service

// Place buy/sell orders
await tradingService.placeBuyOrder(orderParams);
await tradingService.placeSellOrder(orderParams);

// Cancel orders
await tradingService.cancelOrder('ORDER_ID');

// Get order status
const activeOrders = await tradingService.getActiveOrders();
const orderHistory = await tradingService.getOrderHistory();

// Portfolio management
const positions = await tradingService.getCurrentPositions();
const summary = await tradingService.getPortfolioSummary();

// Risk management
const riskCheck = await tradingService.checkPositionLimits(orderParams);

Market Data Service

// Get real-time market data
const boardData = await marketDataService.getBoardData('9984');
const multipleBoards = await marketDataService.getMultipleBoardData(['9984', '7203']);

// Symbol information
const symbolInfo = await marketDataService.getSymbolInfo('9984');

// Market analysis
const priceChange = await marketDataService.getPriceChangeSummary('9984');
const orderBook = await marketDataService.getOrderBookAnalysis('9984');

// Rankings
const gainers = await marketDataService.getRankingData('price-gain');

// Real-time monitoring
marketDataService.startPriceMonitoring('9984', (data) => {
  console.log(`Price update: ${data.currentPrice}`);
}, 5000);

Position Service

// Position management
const allPositions = await positionService.getAllPositions();
const position = await positionService.getPositionBySymbol('9984');

// Portfolio analysis
const portfolio = await positionService.getPortfolioSummary();
const performance = await positionService.getPerformanceMetrics();

// Risk assessment
const riskMetrics = await positionService.getRiskMetrics('9984');
const portfolioRisk = await positionService.getPortfolioRisk();

// Position tracking
const history = await positionService.getPositionHistory('9984');

// Alerts
const alerts = await positionService.checkPositionAlerts();

๐Ÿ— Architecture

Project Structure

src/
โ”œโ”€โ”€ api/                    # API Integration Layer
โ”‚   โ”œโ”€โ”€ kabusapi-client.ts     # Main HTTP client
โ”‚   โ”œโ”€โ”€ connection-pool.ts     # Connection management
โ”‚   โ”œโ”€โ”€ rate-limiter.ts        # Request rate limiting
โ”‚   โ”œโ”€โ”€ retry-handler.ts       # Retry logic
โ”‚   โ””โ”€โ”€ response-parser.ts     # Response parsing
โ”œโ”€โ”€ business/               # Business Logic Layer
โ”‚   โ”œโ”€โ”€ trading-service.ts     # Trading operations
โ”‚   โ”œโ”€โ”€ market-data-service.ts # Market data operations
โ”‚   โ””โ”€โ”€ position-service.ts    # Position management
โ”œโ”€โ”€ config/                 # Configuration Management
โ”‚   โ””โ”€โ”€ config-manager.ts      # Environment/file config
โ”œโ”€โ”€ logging/               # Logging System
โ”‚   โ”œโ”€โ”€ logger.ts              # Structured logging
โ”‚   โ””โ”€โ”€ log-masker.ts          # Sensitive data masking
โ”œโ”€โ”€ mcp/                   # MCP Server Framework
โ”‚   โ”œโ”€โ”€ kabusapi-mcp-server.ts # Main MCP server
โ”‚   โ”œโ”€โ”€ tool-registry.ts       # Tool registration
โ”‚   โ”œโ”€โ”€ request-handler.ts     # Request handling
โ”‚   โ””โ”€โ”€ response-formatter.ts  # Response formatting
โ”œโ”€โ”€ security/              # Security Layer
โ”‚   โ”œโ”€โ”€ token-manager.ts       # Token management
โ”‚   โ”œโ”€โ”€ crypto-service.ts      # Encryption/decryption
โ”‚   โ”œโ”€โ”€ input-validator.ts     # Input validation
โ”‚   โ””โ”€โ”€ secure-storage.ts      # Secure data storage
โ””โ”€โ”€ index.ts               # Main exports

Layer Architecture

  1. MCP Server Layer - Handles MCP protocol communication
  2. Business Logic Layer - Core trading/market operations
  3. API Integration Layer - HTTP client with pooling/retry
  4. Security Layer - Authentication and encryption
  5. Infrastructure Layer - Logging and configuration

๐Ÿ”’ Security Considerations

Data Protection

  • Encryption at Rest: AES-256-CBC for stored tokens
  • Memory Security: Automatic token cleanup
  • Input Sanitization: SQL injection and XSS protection
  • Request Validation: Comprehensive parameter checking

API Security

  • Rate Limiting: Token bucket algorithm
  • Connection Pooling: Efficient resource usage
  • Retry Logic: Exponential backoff with jitter
  • Error Handling: No sensitive data in error messages

Authentication Flow

  1. Initial authentication with API password
  2. Token encryption and secure storage
  3. Automatic token refresh before expiration
  4. Fallback reauthentication on token failure

๐Ÿ› Debugging

Logging Configuration

// Set log level
process.env.LOG_LEVEL = 'debug';

// Enable specific component logging
const logger = new Logger('TradingService');
logger.setLevel('debug');

Common Issues

  1. Connection Timeout

    # Check Kabu Station API server status
    curl http://localhost:18080/kabusapi/token
    
  2. Authentication Failure

    # Verify API password in environment
    echo $KABUS_PASSWORD
    
  3. Rate Limiting

    # Check current rate limit settings
    npm run config:check
    

๐Ÿค Contributing

Development Workflow

  1. Fork the repository
  2. Create feature branch: git checkout -b feature/new-feature
  3. Write tests: Follow TDD methodology
  4. Implement feature: Ensure all tests pass
  5. Run linting: npm run lint
  6. Submit pull request: With comprehensive description

Code Standards

  • TypeScript: Strict mode enabled
  • Testing: Minimum 80% coverage required
  • Linting: ESLint with strict rules
  • Documentation: TSDoc comments for public APIs
  • Git: Conventional commit messages

๐Ÿ“„ License

This project is licensed under the MIT License - see the file for details.

๐Ÿ”— Resources

๐Ÿ“ž Support


โš ๏ธ Important: This software is for educational and development purposes. Always test thoroughly before using with real trading accounts. Trading involves financial risk.