Metadata-Version: 2.1
Name: akshare-mcp-service
Version: 0.1.0
Summary: MCP server exposing akshare financial data library — access Chinese stocks, futures, funds, bonds, options, indices, macroeconomics, forex, and more
Author: AKShare MCP Contributors
License: Apache-2.0
Keywords: akshare,mcp,finance,stock,china,financial-data
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: akshare>=1.18.0
Requires-Dist: mcp>=1.8.0
Requires-Dist: pandas>=1.3.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
Requires-Dist: pytest-mock>=3.14; extra == "dev"

<p align="center">
  <img src="https://akshare.akfamily.xyz/_static/akshare.svg" alt="akshare" width="200"/>
</p>

<h1 align="center">akshare-mcp</h1>

<p align="center">
  <strong>MCP (Model Context Protocol) Server for AKShare Financial Data</strong>
</p>

<p align="center">
  <a href="https://pypi.org/project/akshare-mcp-service/" target="_blank">
    <img src="https://img.shields.io/pypi/v/akshare-mcp-service" alt="PyPI">
  </a>
  <a href="https://github.com/xiaozhozho/akshare-mcp/blob/main/LICENSE" target="_blank">
    <img src="https://img.shields.io/github/license/xiaozhozho/akshare-mcp" alt="License">
  </a>
  <a href="https://www.python.org/" target="_blank">
    <img src="https://img.shields.io/badge/python-≥3.10-blue" alt="Python">
  </a>
</p>

<p align="center">
  <a href="#overview">Overview</a> •
  <a href="#quick-start">Quick Start</a> •
  <a href="#tools">Tools</a> •
  <a href="#usage-examples">Usage</a> •
  <a href="#development">Development</a> •
  <a href="#architecture">Architecture</a>
</p>

---

## Overview

**akshare-mcp** wraps [AKShare](https://akshare.akfamily.xyz/) — an open-source Chinese financial data library with **1000+ data functions** — as a **Model Context Protocol (MCP) server**, enabling LLMs (Claude, etc.) to query Chinese financial data through standardized tool interfaces.

### What you can query

| Category | Examples |
|----------|----------|
| **Stocks** | Real-time quotes, historical bars, financial statements, board/industry indices, fund flow, margin trading, IPO data, LHB |
| **Macroeconomics** | GDP, CPI, PMI, money supply, interest rates — China, US, EU, Japan, etc. |
| **Futures** | Real-time/daily bars, settlement prices, open interest, warehouse receipts, basis analysis |
| **Funds** | Mutual fund NAV, ETF quotes & holdings, fund manager info, performance rankings |
| **Bonds** | Convertible bonds, treasury yields, corporate bonds, repo rates, NAFMII data |
| **Options** | CFFEX index options, SSE/SZSE ETF options, commodity options, Greeks, margin |
| **Forex & Commodities** | Exchange rates, gold/silver spot, crude oil, carbon emissions, hog prices |
| **Indices** | CSI/Shenwan/global indices, industry indices, index constituents |
| **Alternative Data** | Weather, news sentiment, migration, box office, wealth rankings, game rankings |

---

## Quick Start

### Installation

```bash
pip install akshare-mcp
```

> **Note:** AKShare requires Python ≥ 3.10 and uses the `numpy`, `pandas`, and `requests` packages. These will be installed automatically.

### Usage

Run the server:

```bash
akshare-mcp
```

You should see:

```
[akshare-mcp] Loaded 13 tools covering 1086 akshare functions
```

### Integrating with Claude Desktop

Add to your `claude_desktop_config.json`:

**macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
**Windows:** `%APPDATA%\Claude\claude_desktop_config.json`

```json
{
  "mcpServers": {
    "akshare": {
      "command": "uvx",
      "args": ["akshare-mcp"]
    }
  }
}
```

If `uvx` is not available, use `pip` directly:

```json
{
  "mcpServers": {
    "akshare": {
      "command": "python",
      "args": ["-m", "akshare_mcp.server"]
    }
  }
}
```

### Integration with other MCP clients

Any MCP-compatible client can connect via stdio. The server listens on stdin/stdout and responds to the standard `list_tools` / `call_tool` requests.

---

## Tools

akshare-mcp groups its 1000+ data functions into **13 category tools** plus a **discovery tool**:

### Category Tools

| Tool | Functions | Category | Key Data |
|------|:---------:|----------|----------|
| `akshare_stock_a` | 226 | A股行情 | Real-time/historical quotes, IPO, LHB, technical indicators, market summaries |
| `akshare_stock_fundamental` | 56 | A股基本面 | Financial statements, profit forecasts, ESG ratings, shareholders, dividends |
| `akshare_stock_hk_us` | 36 | 港股美股 | HK/US stock profiles, financials, quotes, exchange info |
| `akshare_stock_board_flow` | 38 | 板块/资金流向 | Concept & industry board indices, constituents, capital flow, north/south-bound connect |
| `akshare_stock_margin_other` | 40 | 融资融券/其他 | Margin trading, block trades, stock pledging, suspension/resumption, chip distribution |
| `akshare_macro` | 225 | 宏观经济 | China macro (GDP, CPI, PMI, M2, etc.), global macro (US, EU, JP, UK, AU, etc.) |
| `akshare_futures` | 91 | 期货 | Futures quotes, holdings, warehouse receipts, settlement, COT reports |
| `akshare_fund` | 88 | 基金 | Fund NAV, ETF quotes, manager profiles, performance rankings, AMAC stats |
| `akshare_bond` | 46 | 债券 | Convertible bonds, treasury yields, corporate bonds, repo, NAFMII |
| `akshare_index` | 91 | 指数 | CSI/Shenwan/global indices, sector analysis, index constituents |
| `akshare_option` | 46 | 期权 | Index/ETF/commodity options, Greeks, margin, option chains |
| `akshare_fx_commodity` | 40 | 外汇/商品 | Forex rates, energy, spot commodities, carbon emissions, crypto |
| `akshare_other` | 63 | 其他数据 | Air quality, movies, games, news, wealth rankings, QDII, REITs |

### Discovery Tool

| Tool | Purpose |
|------|---------|
| `akshare_discover` | Search functions by keyword across all categories |

### Common Tool Parameters

Every category tool accepts the same parameter interface:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `method` | `str` | **Yes** | The exact akshare function name to call (e.g. `stock_zh_a_hist`) |
| `params_json` | `str` | No | JSON-encoded keyword arguments for the function (default: `"{}"`) |
| `symbol` | `str` | No | Convenience shortcut; forwarded as keyword argument |
| `start_date` | `str` | No | Convenience shortcut (format: `YYYYMMDD`) |
| `end_date` | `str` | No | Convenience shortcut (format: `YYYYMMDD`) |
| `period` | `str` | No | Convenience shortcut (e.g. `daily`, `weekly`, `monthly`) |
| `adjust` | `str` | No | Convenience shortcut for stock price adjustment (`qfq`, `hfq`) |
| `date` | `str` | No | Convenience shortcut for single-date parameters |

> **Tip:** Use `akshare_discover` first to find the right `method` name, then call the parent tool with `method=function_name`.

---

## Usage Examples

### Query real-time A-share stock quotes

```python
# Via akshare_discover:
#   query="spot_em" → found in akshare_stock_a
# Then:
call_tool("akshare_stock_a", {
  "method": "stock_zh_a_spot_em"
})
```

### Query historical stock data

```python
call_tool("akshare_stock_a", {
  "method": "stock_zh_a_hist",
  "symbol": "300693",
  "period": "daily",
  "start_date": "20250101",
  "end_date": "20250708"
})
```

### Query macroeconomic GDP data

```python
call_tool("akshare_macro", {
  "method": "macro_china_gdp_yearly"
})
```

### Search for a function

```python
call_tool("akshare_discover", {
  "query": "gdp"
})
# Returns matching functions grouped by tool
```

### Convertible bond market

```python
call_tool("akshare_bond", {
  "method": "bond_zh_hs_cov_spot"
})
```

### Fund flow by stock

```python
call_tool("akshare_stock_board_flow", {
  "method": "stock_fund_flow_individual",
  "symbol": "300693"
})
```

---

## Development

### Setup

```bash
git clone https://github.com/xiaozhozho/akshare-mcp.git
cd akshare-mcp
pip install -e ".[dev]"
```

### Run tests

```bash
python -m pytest tests/ -v
```

**51 tests** covering:
- DataFrame serialization (NaN/NaT/inf handling, datetime conversion, truncation)
- CategoryDispatcher (function dispatch, parameter merging, error wrapping)
- Error handling (akshare exception hierarchy, decorator pattern)
- ToolRegistry (auto-discovery, function assignment, cross-tool search)

### Project structure

```
akshare-mcp/
├── pyproject.toml              # Build config (hatchling)
├── src/
│   └── akshare_mcp/
│       ├── server.py           # FastMCP entry point
│       ├── tools/
│       │   ├── base.py         # CategoryDispatcher base class
│       │   └── registry.py     # ToolRegistry + auto discovery
│       └── utils/
│           ├── dataframe.py    # DataFrame → JSON serialization
│           └── errors.py       # Error handling & wrapping
└── tests/                      # 51 pytest tests
```

### How it works

1. **Auto-discovery:** `ToolRegistry` scans all public akshare callables at import time using `inspect.getfile()`, determines each function's source module, and assigns it to the appropriate category tool
2. **Dispatch:** Each category tool accepts a `method` parameter. The dispatcher resolves the function, merges convenience params with JSON params, calls akshare via `asyncio.to_thread()`, and serializes the resulting DataFrame
3. **Error handling:** All akshare exceptions (NetworkError, RateLimitError, InvalidParameterError, etc.) are caught and returned as structured error dicts — never raw exceptions
4. **Serialization:** DataFrames are converted to JSON with column metadata, row count, truncation handling, and proper NaN/NaT/inf → null conversion

### Configuration

| Environment Variable | Default | Description |
|---------------------|---------|-------------|
| `AKSHARE_MCP_MAX_ROWS` | `500` | Maximum rows returned per response |

---

## Architecture

```
┌─────────────────────────────────────────────────┐
│                   MCP Client                     │
│           (Claude Desktop, etc.)                 │
└──────────────┬──────────────────────┬────────────┘
               │  list_tools          │  call_tool
               ▼                      ▼
┌─────────────────────────────────────────────────┐
│              FastMCP (stdio transport)           │
├─────────────────────────────────────────────────┤
│  ToolRegistry (13 category dispatchers)          │
│  ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │
│  │ stock_a  │ │ macro    │ │ discover         │ │
│  │ 226 funcs│ │ 225 funcs│ │ search + index    │ │
│  └──────────┘ └──────────┘ └──────────────────┘ │
├─────────────────────────────────────────────────┤
│  CategoryDispatcher                              │
│  ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │
│  │ method → │ │ params →  │ │ asyncio.to_thread│ │
│  │ func     │ │ merge     │ │ → akshare call   │ │
│  └──────────┘ └──────────┘ └──────────────────┘ │
├─────────────────────────────────────────────────┤
│  Utils                                            │
│  ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │
│  │dataframe │ │ errors   │ │ akshare library  │ │
│  │serialize │ │ wrap     │ │ ~1086 functions  │ │
│  └──────────┘ └──────────┘ └──────────────────┘ │
└─────────────────────────────────────────────────┘
```

---

## License

Apache License 2.0

See [LICENSE](LICENSE) for the full license text.

---

## Related Projects

- [AKShare](https://github.com/akfamily/akshare) — The underlying financial data library
- [AKTools](https://github.com/akfamily/aktools) — HTTP API wrapper for AKShare
- [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) — The MCP framework used
