zakuzakuzaki/kabusapi-mcp-server
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
- MCP Server Layer - Handles MCP protocol communication
- Business Logic Layer - Core trading/market operations
- API Integration Layer - HTTP client with pooling/retry
- Security Layer - Authentication and encryption
- 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
- Initial authentication with API password
- Token encryption and secure storage
- Automatic token refresh before expiration
- 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
-
Connection Timeout
# Check Kabu Station API server status curl http://localhost:18080/kabusapi/token
-
Authentication Failure
# Verify API password in environment echo $KABUS_PASSWORD
-
Rate Limiting
# Check current rate limit settings npm run config:check
๐ค Contributing
Development Workflow
- Fork the repository
- Create feature branch:
git checkout -b feature/new-feature
- Write tests: Follow TDD methodology
- Implement feature: Ensure all tests pass
- Run linting:
npm run lint
- 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
- Kabu Station API Documentation
- Model Context Protocol Specification
- TypeScript Documentation
- Jest Testing Framework
๐ Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- API Documentation: See
docs/
directory
โ ๏ธ Important: This software is for educational and development purposes. Always test thoroughly before using with real trading accounts. Trading involves financial risk.