# Tw Stock Agent

> A Model Context Protocol (MCP) server for Taiwan stock data.

- **Type:** MCP server
- **Install:** `agentstack add mcp-clsung-tw-stock-agent`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [clsung](https://agentstack.voostack.com/s/clsung)
- **Installs:** 0
- **Category:** [Integrations](https://agentstack.voostack.com/c/integrations)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [clsung](https://github.com/clsung)
- **Source:** https://github.com/clsung/tw-stock-agent

## Install

```sh
agentstack add mcp-clsung-tw-stock-agent
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# tw-stock-agent: 台灣股市資料 MCP 服務器

[](TODO.md)
[](https://python.org)
[](https://modelcontextprotocol.io)

## 簡介

**tw-stock-agent** 是一個基於 Model Context Protocol (MCP) 的服務器，提供台灣股市資料查詢與分析功能。項目目前處於開發階段，正在進行架構重構以實現生產就緒的狀態。

### 核心功能
* 台灣上市上櫃股票基本資料（公司概況、產業別、市值等）
* 股票歷史價格走勢和技術分析
* 即時股票資訊和市場概況
* 四大買賣點技術分析
* Taiwan Stock Exchange (TWSE) 和 Taipei Exchange (TPEx) 數據

### 技術特色
* 基於 FastMCP 框架的 MCP 協議實現
* 異步 I/O 處理和高效能快取
* 結構化輸出與 Pydantic 數據驗證
* 完整的錯誤處理和日誌記錄
* 支援多種 MCP 傳輸協議

## 開發狀態

⚠️ **重要提示**: 本專案目前正在進行架構重構，請參考 [TODO.md](TODO.md) 了解開發路線圖。

**當前架構狀態:**
- ✅ 基本 MCP 工具實現
- 🔄 正在整合雙架構（FastAPI + FastMCP）
- 🔄 實現完整異步 I/O 模式
- ⏳ 待實現結構化輸出和資源模式
- ⏳ 待添加資料庫持久化層

## 系統需求

* **Python:** 3.11 或更高版本
* **套件管理:** 僅支援 uv（依照 [CLAUDE.md](CLAUDE.md) 開發規範）

## 安裝與設置

### 開發環境設置

1. **克隆專案**：
```bash
git clone https://github.com/clsung/tw-stock-agent.git
cd tw-stock-agent
```

2. **安裝依賴**（僅使用 uv）：
```bash
uv sync
```

3. **設置 pre-commit hooks**：
```bash
uv run pre-commit install
```

4. **環境配置**：
```bash
# 複製環境變數模板（如果存在）
cp .env.example .env
```

## 運行 MCP 服務器

### 開發模式
```bash
# 使用 FastMCP 服務器（推薦）
uv run python mcp_server.py

# 使用 MCP 開發工具
uv run mcp dev mcp_server.py
```

### MCP 客戶端整合

**當前實現方式**（FastMCP stdio 模式）：
```json
{
  "mcpServers": {
    "tw-stock-agent": {
      "command": "uv",
      "args": ["run", "python", "mcp_server.py"],
      "cwd": "/path/to/tw-stock-agent"
    }
  }
}
```

**未來支援**（HTTP 傳輸）：
```json
{
  "mcpServers": {
    "tw-stock-agent": {
      "command": "uvicorn",
      "args": ["tw_stock_agent.main:app", "--host", "127.0.0.1", "--port", "8000"]
    }
  }
}
```

⚠️ **注意**: HTTP 傳輸配置將在架構重構完成後可用。

## MCP 工具與功能

### 可用 MCP 工具

| 工具名稱 | 參數 | 功能描述 |
|---------|------|---------|
| `get_stock_data` | `stock_code: str` | 獲取股票基本資料（公司概況、產業別、市值等） |
| `get_price_history` | `stock_code: str`, `period: str` | 獲取歷史價格數據（OHLCV、成交量） |
| `get_realtime_data` | `stock_code: str` | 獲取即時股票資訊（當前價格、成交量） |
| `get_best_four_points` | `stock_code: str` | 四大買賣點技術分析 |
| `get_market_overview` | 無 | 大盤指數和市場概況 |

### MCP 資源（規劃中）
- `stock://info/{stock_code}` - 股票基本資訊
- `stock://price/{stock_code}` - 價格歷史
- `stock://realtime/{stock_code}` - 即時數據

### 資料來源
- **TWSE** (台灣證券交易所): 上市股票、TAIEX 指數
- **TPEx** (證券櫃檯買賣中心): 上櫃股票、興櫃市場
- 使用 `twstock` 函式庫進行資料擷取

### 效能特性
- 即時資料快取：1分鐘 TTL
- 歷史資料快取：30分鐘 TTL
- API 速率限制：每5秒最多3個請求（符合 TWSE 限制）

## 項目架構

### 當前架構狀態
```
tw-stock-agent/
├── CLAUDE.md                 # 開發規範與指導原則
├── TODO.md                   # 開發路線圖與改進計劃
├── README.md
├── pyproject.toml
├── mcp_server.py            # 🔄 FastMCP 伺服器實現
├── tw_stock_agent/
│   ├── main.py              # ⚠️  FastAPI 實現（將移除）
│   ├── services/
│   │   ├── stock_service.py  # 股票資料服務
│   │   └── cache_service.py  # 快取服務
│   ├── tools/
│   │   ├── stock_tools.py   # MCP 工具定義
│   │   ├── stock_code.py    # 股票代碼工具
│   │   └── *.csv           # 股票交易所資料
│   └── utils/
│       ├── config.py        # 配置管理
│       ├── data_fetcher.py  # 資料擷取工具
│       ├── error_handler.py # 錯誤處理
│       └── rate_limiter.py  # 速率限制
├── scripts/                 # 獨立資料收集腳本
│   ├── download_twse.py     # TWSE 資料下載
│   ├── download_tpex.py     # TPEx 資料下載
│   └── ...
└── tests/
    ├── unit/
    └── integration/
```

### 架構重構計劃

**目標架構** (參考 [TODO.md](TODO.md)):
- 🎯 整合為純 FastMCP 架構
- 🎯 完整異步 I/O 實現
- 🎯 結構化資料輸出
- 🎯 資料庫持久化層
- 🎯 全面錯誤處理和監控

**技術棧**:
- **MCP 框架**: FastMCP (代替雙重架構)
- **資料驗證**: Pydantic v2
- **HTTP 客戶端**: aiohttp (異步)
- **資料庫**: SQLAlchemy + SQLite/PostgreSQL
- **快取**: Redis (生產) / 記憶體快取 (開發)
- **測試**: pytest + anyio

## 開發指南

詳細的開發規範請參考 [CLAUDE.md](CLAUDE.md)。

### 快速開始
```bash
# 安裝依賴
uv sync

# 執行程式碼品質檢查
uv run ruff check --fix       # 程式碼檢查與格式化
uv run ruff format           # 程式碼格式化
uv run mypy tw_stock_agent/  # 型別檢查

# 執行測試
uv run pytest --cov=tw_stock_agent

# 執行 MCP 伺服器
uv run python mcp_server.py
```

### 開發規範
- **套件管理**: 僅使用 `uv`，禁止使用 `pip`
- **程式碼風格**: 遵循 PEP 8，使用 `ruff` 進行檢查
- **型別標註**: 所有函數必須有完整的型別標註
- **文檔字串**: 使用 Google 風格，公開 API 必須有文檔
- **測試**: 使用 `pytest` + `anyio` 進行異步測試
- **行長度**: 最大 88 字元

### 貢獻流程
1. 查看 [TODO.md](TODO.md) 了解當前優先事項
2. 遵循 [CLAUDE.md](CLAUDE.md) 開發規範
3. 執行所有品質檢查工具
4. 確保測試覆蓋率 >90%
5. 提交 Pull Request

## 重要限制與注意事項

### API 限制
- **TWSE API**: 每5秒最多3個請求
- **資料更新頻率**: 交易時間內每分鐘更新
- **快取策略**: 即時資料1分鐘，歷史資料30分鐘

### 開發限制
- **市場交易時間**: 週一至週五 09:00-13:30 (台灣時間)
- **假日處理**: 遵循台灣股市交易日曆
- **資料完整性**: 部分歷史資料可能有缺漏

### 已知問題
- 目前存在雙架構實現 (FastAPI + FastMCP)
- 混合同步/異步程式設計模式
- 參數命名不一致 (`stock_code` vs `stock_id`)
- 缺乏結構化輸出和完整錯誤處理

請參考 [TODO.md](TODO.md) 了解改進計劃。

## 使用範例

### 基本工具調用
```python
# 通過 MCP 客戶端調用工具範例
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def example_usage():
    server_params = StdioServerParameters(
        command="uv",
        args=["run", "python", "mcp_server.py"],
        cwd="/path/to/tw-stock-agent"
    )
    
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            
            # 獲取台積電 (2330) 股票資料
            result = await session.call_tool("get_stock_data", {
                "stock_code": "2330"
            })
            print(f"股票資料: {result.content}")
            
            # 獲取歷史價格
            result = await session.call_tool("get_price_history", {
                "stock_code": "2330",
                "period": "1mo"
            })
            print(f"歷史價格: {result.content}")
```

### 常用股票代碼
- **2330**: 台積電 (TSMC)
- **2317**: 鴻海 (Foxconn)  
- **2454**: 聯發科 (MediaTek)
- **2891**: 中信金 (CTBC Financial)
- **3008**: 大立光 (Largan Precision)

## 相關資源

- [Model Context Protocol 官方文檔](https://modelcontextprotocol.io)
- [FastMCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)
- [台灣證券交易所 API](https://www.twse.com.tw)
- [證券櫃檯買賣中心](https://www.tpex.org.tw)

## 授權條款

本專案採用 MIT 授權條款 - 詳見 [LICENSE](LICENSE) 文件。

## 貢獻與回饋

歡迎貢獻程式碼、回報問題或提出改進建議：

1. 查看 [TODO.md](TODO.md) 了解開發優先事項
2. 遵循 [CLAUDE.md](CLAUDE.md) 開發規範  
3. 提交 Issue 回報問題或建議功能
4. 提交 Pull Request 貢獻程式碼

**開發者**: 本專案正在積極開發中，歡迎參與貢獻！

## Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [clsung](https://github.com/clsung)
- **Source:** [clsung/tw-stock-agent](https://github.com/clsung/tw-stock-agent)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** yes
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/mcp-clsung-tw-stock-agent
- Seller: https://agentstack.voostack.com/s/clsung
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
