kookmin-stock
Kookmin MCP Stock Agent
国民大学課題 · 「Hermes + MCP自作サーバーでインパクトを引き上げる」
前回の課題で作成した国内株式推奨Hermesエージェントに自作MCPサーバーを接続し、 作業の質がどのように変化するかを3つの実験で証明する。
🎯 含まれているもの
成果物 | パス | 説明 |
MCPサーバー (正常) |
| FastMCP stdio、ツール6種 |
MCPサーバー (壊したバージョン) |
| 間違ったdescription / タイムアウト / 空の応答 |
30秒動作デモ |
| 録画用シーケンス出力 |
実験② 結果比較 |
| NO MCP / GOOD / BROKEN 比較 |
実験③ パターン比較 |
| Single / Planner+Executor / Parallel |
発表資料(spec) |
| 他のAIにそのまま貼り付けてPPT生成 |
結果成果物 |
| 自動生成された表・CSV・ログ |
Related MCP server: pykrx-mcp
⚙️ インストール
Python 3.10+ (テスト環境 3.13)。
python -m venv .venv
source .venv/bin/activate
pip install -e .▶️ 実行
# 1) MCP 서버 검증 (서버는 stdio라 호스트가 붙어야 의미 있음 — Ctrl+C로 종료)
python -m mcp_stock.server
# 2) 30초 동작 데모 (실제로 돌려서 녹화)
python -m experiments.exp1_demo
# 또는 ./demo/record_demo.sh
# 3) 실험 ② 성공/실패 비교 → results/exp2_* 자동 생성
python -m experiments.exp2_quality
# 4) 실험 ③ Orchestration 토큰 비교 → results/exp3_* 자동 생성
python -m experiments.exp3_orchestration🎥 30秒デモ録画
demo/demo_script.mdにタイムコード別の行動がまとめられている。
最も単純なパス:
./demo/record_demo.sh # QuickTime/Cmd+Shift+5 로 화면 녹화하면서 실행
./demo/record_demo.sh --asciinema # 텍스트 캡처 (asciinema 필요)🧪 実験① — MCPサーバー (ツール6種)
ツール | 入力 | 出力 |
| 'today' / YYYY-MM-DD |
|
| KOSPI/KOSDAQ, 1..50 | 上位N銘柄 |
| コードまたは韓国語名 | close / changePct / volume / per / pbr |
| キーワードまたは銘柄名 | ヘッドライン + |
| コードまたは韓国語名 | per / pbr / eps / bps / roe |
| KOSPI/KOSDAQ | scoreBreakdown + rationale |
データ: Naver Finance クローリング 単一ソース (src/mcp_stock/sources/naver.py)。無料・キー不要。
指数:
polling.finance.naver.com/api/realtime/domestic/index/{KOSPI|KOSDAQ}JSON上昇率上位:
finance.naver.com/sise/sise_rise.naver?sosok={0|1}HTML銘柄詳細 / PER・EPS・PBR・配当:
finance.naver.com/item/main.naver?code=...(安定したid="_per"などのemphasisタグ)銘柄別ニュース:
finance.naver.com/item/news_news.naver?code=...休場日 / Naverページ変更時に自動fallbackスナップショットで安全に動作。
🧪 実験② — Tool成功/失敗結果の品質比較
exp2_quality.pyが同じユーザーの質問を3つの環境で実行し、表・失敗ログを自動生成する。
(a) NO MCP — ツール0個。LLMが学習データのみで回答 → ハルシネーション・根拠欠如。
(b) GOOD MCP — 正常な自作サーバー。ツール12回呼び出し、4つの好材料キーワードを引用。
(c) BROKEN MCP —
server_broken.pyの定義通り:get_top_gainersのdescriptionを「下落率上位」と誤記 → モデルが誤選択get_recent_newsがtime.sleep(5)後にTimeoutError発生get_fundamentalsが空のdictを返却
結果:
results/exp2_quality_table.md— 比較表results/exp2_failure_logs.md— 失敗呼び出しトレース + 回答本文results/exp2_summary.json— 元の統計
🧪 実験③ — Orchestration 3パターン
パターン | 説明 | トークン特性 | 応答時間特性 |
Single | 1ループ内でツール結果を蓄積 | 入力トークン ↑↑ | 最も遅い |
Planner + Executor | plannerが呼び出しシーケンスのみ作成し、executorは結果要約のみ | 入力トークン ↓ | 中間 |
Parallel sub-agents | KOSPI / KOSDAQ / NEWS sub-agentを同時実行 | 入力トークン ↓↓ | 最も速い |
結果:
results/exp3_benchmark.csv— 棒グラフ作成用wide CSVresults/exp3_pattern_table.md— 表 + 回顧results/exp3_summary.json— パターン別フルトレース
🤖 LLM連携 — Hermes / 他のホスト
このリポジトリは、LLM APIキーなしでも決定論的なシミュレーションでトークン・トレースが出るように作成した。 実際のHermes / Claude Desktop / Cursorに接続するには:
1) Hermesホストとして使用 (実験②③を実際のLLMで実行する)
src/experiments/runner/hermes_runner.pyの _callHermes() を埋めるだけでよい。
# TODO(user): replace this body with the real Hermes call.
import httpx
response = httpx.post(self.endpoint, headers=..., json=...)
return response.json()環境変数 HERMES_ENDPOINT, HERMES_API_KEY を設定後、
AgentRunner インスタンスを HermesRunner() に置き換える。
2) Claude Desktop / Cursorでツールのみ使用
Claude Desktopの claude_desktop_config.json または Cursor MCP設定に追加:
{
"mcpServers": {
"kookmin-stock": {
"command": "python",
"args": ["-m", "mcp_stock.server"],
"cwd": "/path/to/Kookmin-University-MCP",
"env": { "PYTHONPATH": "/path/to/Kookmin-University-MCP/src" }
}
}
}📑 PPT作成
slides/slides.mdを他のAIにそのまま貼り付ければよい。例示プロンプト:
次のmarkdownは5分発表用12枚のスライドspecです。
# Slide Nヘッダー単位でPowerPointスライドを作成してください。### Visualブロックは可能な限りmermaidダイアグラムや表をそのまま表現し、### Speaker Notesはスライドノート領域に入れてください。
📤 提出フロー
python -m experiments.exp2_quality && python -m experiments.exp3_orchestrationで結果を更新./demo/record_demo.shで30秒デモ録画 →demo/demo.movGitHub push (リポジトリURLをREADMEとslide 6に記録)
メール
kts123@kookmin.ac.krへ GitHub URL + slides + demo動画を送信 (締切 5/14 23:59:59)
📁 ディレクトリツリー
.
├── README.md
├── pyproject.toml / requirements.txt
├── demo/
│ ├── demo_script.md
│ └── record_demo.sh
├── results/ # 자동 생성
├── slides/slides.md
└── src/
├── mcp_stock/
│ ├── server.py
│ ├── server_broken.py
│ ├── data/ticker_map.py
│ ├── sources/naver.py # 네이버 금융 크롤러 (단일 데이터 소스)
│ └── tools/{market, quote, news, fundamentals, recommend}.py
├── experiments/
│ ├── exp1_demo.py
│ ├── exp2_quality.py
│ ├── exp3_orchestration.py
│ └── runner/{agent_base, mock_runner, hermes_runner}.py
└── utils/{logger, token_counter}.py🛟 トラブルシューティング
症状 | 原因 | 対応 |
| Naverページに該当銘柄がないか構造変更 | 自動fallbackスナップショットを使用 — 正常動作 |
| ネットワークオフライン | 全てのツールがfallbackスナップショットで安全に動作 |
韓国語が文字化け | ターミナルフォント | D2 Coding / Pretendard / SF Mono を推奨 |
休場日/週末の呼び出し | 営業日ではない | ポーリングAPIは最終終値をそのまま返却 |
Available Tools
6 toolsget_fundamentalsB
Return PER, PBR, EPS, BPS, ROE and dividend yield for a ticker.
Inputs: ticker (required).
get_market_overviewA
Return KOSPI and KOSDAQ index close, daily change percent, and trading value.
Args: date: 'today' or YYYY-MM-DD. Non-business days fall back to the most recent trading day automatically. Returns: {asOf, kospi:{close, changePct, tradingValueKrw}, kosdaq:{...}, source}
Inputs: date.
get_recent_newsA
Return recent Naver finance news headlines about a ticker or keyword.
Each item carries a positivityScore (sum of catalyst-keyword matches
minus negative-keyword matches) plus the matched keywords.
Args: query: ticker code, Korean stock name, or free-text keyword. top_n: 1..20.
Inputs: query (required), top_n. Returns: result
get_stock_quoteB
Return the most recent close, change percent, volume, PER and PBR for a ticker.
Args: ticker: 6-digit code (e.g. '005930') or Korean name (e.g. '삼성전자').
Inputs: ticker (required).
get_top_gainersA
Return the top N stocks ranked by daily change percent (descending).
Args: market: 'KOSPI' or 'KOSDAQ'. top_n: 1..50. Returns: List of {ticker, name, changePct, close, asOf}.
Inputs: market, top_n. Returns: result
recommend_buysA
Composite buy-recommendation tool.
Combines top gainers + per-ticker quote, news positivity, and fundamentals
into a ranked list. Each entry includes a transparent scoreBreakdown and
a Korean-language rationale so the LLM can quote the reasoning.
Args: market: 'KOSPI' or 'KOSDAQ'. top_n: 1..10. criteria: optional override of {minPositivityScore, maxPer, minRoe}.
Inputs: market, top_n, criteria. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 6 tools
Each tool has a clearly distinct purpose: fundamentals, market overview, news, stock quote, top gainers, and a composite recommendation. No overlap or ambiguity.
Most tools follow a 'get_' prefix verb_noun pattern (e.g., get_fundamentals, get_market_overview). The exception is recommend_buys, which is still verb_noun but lacks the prefix, creating a minor inconsistency.
With 6 tools covering fundamental data, market overview, news, quotes, top gainers, and a recommend feature, the count is well-scoped for a stock information server.
The tool surface covers core stock information needs (fundamentals, quotes, news, top gainers, overview, and a composite recommendation). Minor gaps like historical prices or sector data are not critical for the stated purpose.
Related MCP Connectors
A Model Context Protocol server exposing real-time and historical Colombo Stock Exchange (CSE) data to AI agents and LLM applications. Provides quotes and OHLCV price history, full financial statements (income, balance sheet, cash flow), pre-computed technicals (moving averages, RS ratings, volume signals), macroeconomic indicators, corporate actions, and rule-based screening across CSE stocks and sector indices, everything needed to build CSE-aware trading assistants, research tools, and market-analysis agents. This is the official MCP server of www.ceyloncharts.com
Official Intrinio MCP server. US stock prices, options and fundamentals for AI agents.
Financial data MCP server for Claude, ChatGPT, Cursor and Codex. Real-time stock quotes, financial statements, options flow, SEC filings, insider trades, 13F holdings, macro data and market news from gloom.sh, the open-source Bloomberg Terminal alternative.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to query real-time and historical Korean stock market data from KRX (Korea Exchange) including indices, stocks, ETFs, bonds, derivatives, and commodities via MCP tools and resources.12 npm1MIT

pykrx-mcpofficial
AlicenseNot gradedqualityDmaintenanceProvides Korean stock market data (KOSPI, KOSDAQ, KONEX) including prices, fundamentals, investor trading, short selling, and indices via MCP protocol, enabling natural language queries from AI agents like ChatGPT and Claude.62 PyPI3MIT- AlicenseAqualityDmaintenanceProvides Korean stock market data, including DART electronic disclosures and KRX trading information, enabling users to query company profiles, financial statements, and stock trade details via MCP clients.9MIT
- AlicenseNot gradedqualityDmaintenanceAn MCP server that retrieves Korean stock fundamentals and financial data from OpenDART, enabling LLMs to access corporate disclosures, financial statements, and dividend information.Apache 2.0