kiwoom_mcp

gejyn14/kiwoom_mcp

3.3

If you are the rightful owner of kiwoom_mcp 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.

Kiwoom MCP Server is a modular and extensible server designed to interact with the Kiwoom Open API using a RESTful approach.

Tools
  1. set_credentials

    Set API credentials

  2. get_access_token

    Get access token from Kiwoom

  3. set_access_token

    Set access token directly

  4. check_token_status

    Check token status and expiration

  5. stock_buy_order

    Place buy orders

  6. stock_sell_order

    Place sell orders

  7. get_trade_types

    Get available trade types

Kiwoom MCP Server

킀움 OPEN API(REST)λ₯Ό ν™œμš©ν•œ .

πŸ—οΈ Project Structure

kiwoom_mcp/                       # Project root
β”œβ”€β”€ __init__.py                   # Package initialization
β”œβ”€β”€ main.py                       # Entry point (clean & simple)
β”œβ”€β”€ server.py                     # Main MCP server class
β”œβ”€β”€ pyproject.toml                # Project configuration
β”œβ”€β”€ README.md                     # This file
β”œβ”€β”€ config/                       # Configuration management
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ constants.py              # API constants and mappings
β”‚   └── settings.py               # Configuration classes
β”œβ”€β”€ models/                       # Data models and types
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ exceptions.py             # Custom exceptions
β”‚   └── types.py                  # Request/Response models
β”œβ”€β”€ kiwoom/                       # Kiwoom API client
β”‚   β”œβ”€β”€ __init__.py
β”‚   └── client.py                 # HTTP client for Kiwoom API
β”œβ”€β”€ handlers/                     # MCP tool handlers
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ base.py                   # Base handler class
β”‚   β”œβ”€β”€ auth.py                   # Authentication handlers
β”‚   └── orders.py                 # Order management handlers
└── utils/                        # Utilities and helpers
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ datetime_utils.py         # Date/time utilities
    └── logging.py                # Logging configuration

πŸš€ νŠΉμ§•μ§•

  • λͺ¨λ“ˆλŸ¬ μ•„ν‚€ν…μ²˜: Clean separation of concerns
  • Type Safety: Full TypeScript-like typing with Python
  • Error Handling: Comprehensive exception handling
  • Configuration: Environment-based configuration
  • Logging: Structured logging with multiple levels
  • Extensible: Easy to add new features and handlers

πŸ“¦ Available Tools

Authentication

  • set_credentials - Set API credentials
  • get_access_token - Get access token from Kiwoom
  • set_access_token - Set access token directly
  • check_token_status - Check token status and expiration

Trading

  • stock_buy_order - Place buy orders
  • stock_sell_order - Place sell orders
  • get_trade_types - Get available trade types

πŸ”§ Configuration

Environment Variables

# Kiwoom API Configuration
KIWOOM_APPKEY=your_app_key
KIWOOM_SECRETKEY=your_secret_key
KIWOOM_IS_MOCK=false
KIWOOM_ACCESS_TOKEN=your_token
KIWOOM_TOKEN_EXPIRES_DT=20241231235959

# Server Configuration
MCP_SERVER_NAME=kiwoom-stock-mcp
MCP_SERVER_VERSION=1.0.0
LOG_LEVEL=INFO

Programmatic Configuration

from config.settings import KiwoomConfig, ServerConfig

# Create configurations
kiwoom_config = KiwoomConfig(
    appkey="your_app_key",
    secretkey="your_secret_key",
    is_mock=False
)

server_config = ServerConfig(
    name="custom-server-name",
    version="1.0.0",
    log_level="DEBUG"
)

πŸƒ Running the Server

Basic Usage

python main.py

With Environment Variables

export KIWOOM_APPKEY=your_app_key
export KIWOOM_SECRETKEY=your_secret_key
export KIWOOM_IS_MOCK=true
python main.py

πŸ”Œ Extending the Server

Adding New Handlers

  1. Create a new handler in handlers/:
# handlers/portfolio.py
from .base import BaseHandler
from ..models.types import PortfolioRequest, PortfolioResponse

class PortfolioHandler(BaseHandler):
    async def get_portfolio(self, arguments: Dict[str, Any]) -> List[types.TextContent]:
        # Implementation here
        return self.create_success_response("Portfolio retrieved")
  1. Register in server.py:
# In KiwoomMCPServer.__init__()
self.portfolio_handler = PortfolioHandler(self.kiwoom_config)

# In _setup_handlers()
elif name == "get_portfolio":
    return await self.portfolio_handler.get_portfolio(arguments)

Adding New API Endpoints

  1. Add constants in config/constants.py:
ENDPOINTS = {
    "TOKEN": "/oauth2/token",
    "STOCK_ORDER": "/api/dostk/ordr",
    "PORTFOLIO": "/api/portfolio",  # New endpoint
}
  1. Extend the client in kiwoom/client.py:
def get_portfolio(self, access_token: str) -> PortfolioResponse:
    # Implementation here
    pass

Adding New Models

  1. Define in models/types.py:
@dataclass
class PortfolioRequest:
    account_number: str
    include_positions: bool = True

@dataclass  
class PortfolioResponse:
    success: bool
    positions: List[Position]
    total_value: float

πŸ” Benefits of This Structure

  1. Maintainability: Each component has a single responsibility
  2. Testability: Easy to unit test individual components
  3. Scalability: Simple to add new features without affecting existing code
  4. Reusability: Components can be reused across different parts
  5. Type Safety: Full typing for better IDE support and error catching
  6. Configuration Management: Centralized and flexible configuration
  7. Error Handling: Consistent error handling across all components

🚦 Migration from Monolithic Structure

The old 489-line main.py has been refactored into:

  • 12 focused modules with clear responsibilities
  • Type-safe interfaces between components
  • Proper separation of configuration, business logic, and presentation
  • Extensible architecture for future enhancements

This structure follows Python best practices and makes the codebase much more professional and maintainable.