Skip to main content
Glama
kookmin-stock

kookmin-stock

Kookmin MCP Stock Agent

国民大学課題 · 「Hermes + MCP自作サーバーでインパクトを引き上げる」

前回の課題で作成した国内株式推奨Hermesエージェントに自作MCPサーバーを接続し、 作業の質がどのように変化するかを3つの実験で証明する。

🎯 含まれているもの

成果物

パス

説明

MCPサーバー (正常)

src/mcp_stock/server.py

FastMCP stdio、ツール6種

MCPサーバー (壊したバージョン)

src/mcp_stock/server_broken.py

間違ったdescription / タイムアウト / 空の応答

30秒動作デモ

src/experiments/exp1_demo.py

録画用シーケンス出力

実験② 結果比較

src/experiments/exp2_quality.py

NO MCP / GOOD / BROKEN 比較

実験③ パターン比較

src/experiments/exp3_orchestration.py

Single / Planner+Executor / Parallel

発表資料(spec)

slides/slides.md

他のAIにそのまま貼り付けてPPT生成

結果成果物

results/exp2_*, results/exp3_*

自動生成された表・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種)

ツール

入力

出力

get_market_overview(date)

'today' / YYYY-MM-DD

{kospi:{close, changePct, tradingValueKrw}, kosdaq:{...}}

get_top_gainers(market, top_n)

KOSPI/KOSDAQ, 1..50

上位N銘柄

get_stock_quote(ticker)

コードまたは韓国語名

close / changePct / volume / per / pbr

get_recent_news(query, top_n)

キーワードまたは銘柄名

ヘッドライン + positivityScore

get_fundamentals(ticker)

コードまたは韓国語名

per / pbr / eps / bps / roe

recommend_buys(market, top_n, criteria)

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 CSV

  • results/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 はスライドノート領域に入れてください。

📤 提出フロー

  1. python -m experiments.exp2_quality && python -m experiments.exp3_orchestration で結果を更新

  2. ./demo/record_demo.sh で30秒デモ録画 → demo/demo.mov

  3. GitHub push (リポジトリURLをREADMEとslide 6に記録)

  4. メール 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 detail fetch failed for XXXXXX

Naverページに該当銘柄がないか構造変更

自動fallbackスナップショットを使用 — 正常動作

httpx.ConnectError

ネットワークオフライン

全てのツールがfallbackスナップショットで安全に動作

韓国語が文字化け

ターミナルフォント

D2 Coding / Pretendard / SF Mono を推奨

休場日/週末の呼び出し

営業日ではない

ポーリングAPIは最終終値をそのまま返却

Available Tools

6 tools
get_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

    A3.8/5.0

    Scored across 6 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose: fundamentals, market overview, news, stock quote, top gainers, and a composite recommendation. No overlap or ambiguity.

    Naming Consistency4/5

    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.

    Tool Count5/5

    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.

    Completeness4/5

    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

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables 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 npm
      1
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides 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 PyPI
      3
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      Provides 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.
      9
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      An 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