Skip to main content
Glama
Vaskka

ak-mcp

by Vaskka

ak-mcp: AKShare Financial Data MCP Server

ak-mcp is a financial data query service based on the Model Context Protocol (MCP), using AKShare as the data source. It automatically registers the 1000+ data interfaces included in the official data dictionary as MCP tools, allowing Agents such as Claude, Codex, and Cursor to discover and call them directly. Query results are written to a MySQL local cache by default; when the cache is hit, the remote data source is not accessed, significantly reducing network dependency and latency.

Features

  • Follows the latest MCP protocol: Based on the official Python SDK v2 (mcp>=2.0), implements the 2026-07-28 revision of the protocol, and is automatically compatible with clients from 2025-11-25 and earlier; the same service supports both stdio and Streamable HTTP transports simultaneously.

  • Full interface coverage: The interface list is generated directly from the official documentation (https://akshare.akfamily.xyz/data/ ), currently covering 1019 interfaces, spanning stocks, futures, bonds, options, forex, currencies, spot markets, interest rates, private/public funds, indices, macroeconomics, cryptocurrencies, banking, energy, alternative data, toolkits, indicator calculations, and all other major categories.

  • Cache-first: A MySQL cache hit returns immediately; only on a miss does it fall back to AKShare and write back to the cache; if the fallback fails, it automatically returns stale data and marks it with stale: true.

  • Per-category TTL: Real-time quotes, daily-frequency history, macroeconomic indicators, and static dictionaries each use different cache expiration periods, with support for per-function overrides.

  • Native parameter Schema: Each tool's parameters are automatically generated from the AKShare function signature (required/optional, type, default value), so Agents can call them directly with documented parameters without learning an additional wrapper format.

  • Operations-friendly: Includes built-in meta-tools for interface search, cache statistics, cache clearing, health checks, and bypassing the cache for direct queries.

Architecture

flowchart LR
    A[Agent 客户端<br/>Claude / Codex / Cursor] -->|stdio 或 Streamable HTTP| M[MCP Server<br/>mcp>=2, 2026-07-28]
    M --> T[1000+ 个数据工具<br/>工具名 = AKShare 函数名]
    T --> E[执行器<br/>超时 / 参数过滤 / 结果规范化]
    E --> C{MySQL 缓存<br/>ak_cache}
    C -->|命中且未过期| R[返回 JSON]
    C -->|未命中或过期| K[AKShare]
    K --> C
    K --> D[新浪 / 东财 / 交易所等数据源]
    M --> Meta[元工具<br/>检索 / 统计 / 清理 / 健康]

Directory Structure

ak-mcp/
├── src/ak_mcp/               # 服务端核心代码
│   ├── server.py             # MCP 服务装配与工具注册
│   ├── registry.py           # 文档接口清单加载与安装包匹配
│   ├── schema.py             # 函数签名 -> JSON Schema
│   ├── executor.py           # 线程池调用、超时、参数过滤
│   ├── normalize.py          # DataFrame -> JSON 规范化
│   ├── cache.py              # MySQL 缓存(SQLAlchemy)
│   ├── ttl.py                # TTL 规则引擎
│   ├── config.py             # 环境变量配置
│   └── cli.py                # 命令行入口
├── scripts/
│   ├── build_registry.py     # 抓取官方文档生成接口清单
│   └── init_db.sql           # MySQL 初始化 SQL
├── config/
│   ├── akshare_registry.json # 官方文档接口清单(已生成,1019 个)
│   └── ttl_rules.yaml        # 缓存 TTL 规则
├── tests/                    # 单元与集成测试
├── docker-compose.yml        # MySQL 8 本地环境
├── pyproject.toml
└── Makefile

Environment Requirements

  • Python 3.11+ (3.11/3.12/3.13 recommended)

  • MySQL 8.0+ (the project's bundled Docker Compose can be used)

  • AKShare officially requires a 64-bit operating system

Quick Start

1. Installation

make install          # 创建 .venv 并安装依赖(等价于 pip install -e ".[dev]")

2. Start MySQL

Option 1 (recommended): Use the project's bundled Docker Compose:

make mysql-up         # docker compose up -d mysql,映射标准 3306 端口

Option 2: Use an existing MySQL and run the initialization manually:

mysql -uroot -p < scripts/init_db.sql

3. Configuration

cp .env.example .env

Modify .env as needed. The default configuration corresponds to the project's bundled MySQL container:

MYSQL_HOST=127.0.0.1
MYSQL_PORT=3306
MYSQL_USER=ak_mcp
MYSQL_PASSWORD=ak_mcp_password
MYSQL_DB=ak_mcp

All configuration items are listed in .env.example.

4. Generate the Interface List (optional)

The repository already includes config/akshare_registry.json (corresponding to official documentation 1.18.94), so regeneration is usually unnecessary. To sync with the latest documentation:

make registry

5. Start the Service

stdio mode (for local calls from desktop clients):

ak-mcp
# 或 .venv/bin/ak-mcp

Streamable HTTP mode (for remote/multi-client calls):

ak-mcp --transport http --host 127.0.0.1 --port 8765

Other commands:

ak-mcp --list-functions          # 打印全部文档接口
ak-mcp --refresh-registry        # 重新抓取官方文档并更新清单
ak-mcp --verbose                 # 调试日志

QuickStart: Agent Integration

Claude Desktop

Edit claude_desktop_config.json (Claude Desktop's MCP configuration):

{
  "mcpServers": {
    "ak-mcp": {
      "command": "/absolute/path/to/ak-mcp/.venv/bin/ak-mcp",
      "env": {
        "MYSQL_HOST": "127.0.0.1",
        "MYSQL_PORT": "3306",
        "MYSQL_USER": "ak_mcp",
        "MYSQL_PASSWORD": "ak_mcp_password",
        "MYSQL_DB": "ak_mcp"
      }
    }
  }
}

After saving, restart Claude Desktop to use all data tools such as stock_zh_a_hist, fund_open_fund_info_em, and macro_china_cpi_yearly directly in conversations.

Codex

Append to ~/.codex/config.toml:

[mcp_servers.ak-mcp]
command = "/absolute/path/to/ak-mcp/.venv/bin/ak-mcp"
env = { MYSQL_HOST = "127.0.0.1", MYSQL_PORT = "3306", MYSQL_USER = "ak_mcp", MYSQL_PASSWORD = "ak_mcp_password", MYSQL_DB = "ak_mcp" }

You can also use the Codex CLI's MCP add command (refer to codex mcp --help for the exact syntax for your current Codex version).

Generic MCP Client (HTTP)

First start HTTP mode:

ak-mcp --transport http --host 127.0.0.1 --port 8765

Then configure it in an MCP client that supports URLs:

{
  "mcpServers": {
    "ak-mcp": {
      "url": "http://127.0.0.1:8765/mcp"
    }
  }
}

Usage Examples

Query A-Share Historical Quotes

The Agent directly calls the tool stock_zh_a_hist, with parameters identical to the AKShare official documentation:

stock_zh_a_hist(symbol="000001", period="daily", start_date="20260801", end_date="20260826", adjust="")

Returns JSON:

{
  "data": [
    {
      "日期": "2026-08-03",
      "开盘": 10.38,
      "收盘": 10.47,
      "最高": 10.59,
      "最低": 10.32,
      "成交量": 886273
    }
  ],
  "meta": {
    "function": "stock_zh_a_hist",
    "params": { "symbol": "000001", "period": "daily" },
    "cached": true,
    "stale": false,
    "rows": 18,
    "elapsed_ms": 2,
    "truncated": false
  }
}

Locating Interfaces

If you are unsure of the interface name, first call ak_search_functions:

ak_search_functions(query="可转债 实时行情")
ak_search_functions(category="macro")

Operations Meta-Tools

Tool

Description

ak_search_functions

Search the interface list by keyword/category

ak_cache_stats

Cache statistics: entry count, expired count, row count, byte count, Top functions

ak_cache_clear

Clear cache for specific functions/parameters or all cache

ak_health

Service health, protocol version, interface count, cache status

ak_execute_raw

Bypass the cache and query AKShare directly (for forced refresh)

Interface List Mechanism

  1. scripts/build_registry.py fetches the Markdown source files of all pages under the data/ directory of the official documentation, parses 接口:xxx, 描述:xxx, and the input parameter tables, and generates config/akshare_registry.json.

  2. At service startup, this list is the single source of truth: interfaces included in the list that also exist in the installed akshare are registered one by one as MCP tools.

  3. Interfaces in the list but missing from the installed package are skipped with a warning (e.g., when documentation is released ahead of the version); use AKSHARE_REQUIRE_VERSION_MATCH=true to enforce version consistency.

Cache Mechanism

Cache-First Flow

  1. Compute a SHA-256 cache key from function name + normalized parameters + akshare version.

  2. On a hit that has not expired: return the cached JSON directly (meta.cached = true).

  3. On a miss or expiration: call AKShare to fetch the source data, normalize it, and write it back to MySQL.

  4. If the fallback fails: if stale data exists, return the old data and mark meta.stale = true; otherwise return an error message.

Table Structure (ak_cache)

The table is created automatically via SQLAlchemy at service startup; you can also create it manually by referring to scripts/init_db.sql:

Field

Description

cache_key

SHA-256 cache key (unique)

function_name

AKShare function name

params_json

Normalized parameters

result_json

Result data (LONGTEXT)

row_count

Number of data rows

ttl_seconds

Cache expiration for this entry

created_at / expires_at / last_fetched_at

Timestamps

fetch_ms

Fallback fetch duration

akshare_version

Data version

TTL Rules

Rules are defined in config/ttl_rules.yaml, matched in order, first match wins:

Rule

Match

Default TTL

Real-time quotes

spot/realtime/minute/分时/实时 etc.

60s

Daily-frequency history

hist/history/kline/daily/财务/净值 etc.

6h

Macro/interest rates

Category macro/interest_rate

12h

Static dictionaries

list/calendar/info/简介/日历 etc.

7d

Other

Fallback

1h (modifiable with AK_CACHE_TTL_DEFAULT)

Configuration Items

Environment Variable

Default Value

Description

AK_MYSQL_DSN

Assembled from split variables

Full SQLAlchemy DSN, highest priority

MYSQL_HOST/PORT/USER/PASSWORD/DB

See .env.example

MySQL connection split variables

AK_CACHE_ENABLED

true

When disabled, connects directly to AKShare without caching

AK_CACHE_ALLOW_DEGRADED

false

Degrades to cache-less operation when MySQL is unavailable

AK_CACHE_TTL_DEFAULT

3600

Fallback TTL (seconds)

AK_CACHE_TTL_RULES

config/ttl_rules.yaml

TTL rules file

AK_MAX_ROWS

100000

Maximum rows returned per call, truncated if exceeded

AK_CALL_TIMEOUT

60

Timeout for a single AKShare call (seconds)

AKSHARE_REGISTRY

config/akshare_registry.json

Interface list path

AKSHARE_REQUIRE_VERSION_MATCH

false

Fails startup on version mismatch

AKSHARE_FUNCTION_EXCLUDE

Empty

Regex of interface names to exclude (comma-separated)

Development and Testing

make test          # 运行全部测试(单元 + MCP 内存集成)
make lint          # ruff 检查
make fmt           # ruff 格式化

Test coverage: documentation parsing, Schema generation, TTL classification, parameter normalization, cache keys, SQLite cache behavior, and tool registration/calling/error handling in MCP in-memory mode. Integration verification with real network and MySQL can be performed manually via the local Docker Compose (see "End-to-End Verification" above).

Frequently Asked Questions

Prompt says an interface was not found at startup: Registry function not found in installed akshare: xxx means the official documentation was released ahead of the currently installed akshare version. That interface will be skipped without affecting other interfaces; upgrade akshare or regenerate the list to resolve it.

MySQL connection failure: Confirm that the .env port matches what docker compose ps shows (this project's container maps directly to the standard port 3306); you can also set AK_CACHE_ALLOW_DEGRADED=true to start temporarily in cache-less mode.

Data source interface errors: Some AKShare interfaces depend on third-party websites (Sina, East Money, etc.) and may be affected by network conditions, rate limiting, or field changes; you can reproduce the issue by bypassing the cache with ak_execute_raw, or upgrade the akshare version.

Timezone and encoding: Cache times are uniformly in UTC; data is written and read using UTF-8/utf8mb4, and Chinese column names can be returned directly.

Security and Production Recommendations

  • v1 is intended for local and intranet use and does not include built-in authentication or rate limiting; for production, it is recommended to place it behind a gateway (OAuth/API Key, rate limiting).

  • The cache is shared by all Agents and does not distinguish between users; add your own isolation for sensitive scenarios.

  • When HTTP mode is exposed externally, it is recommended to listen only on intranet addresses, or add TLS via a reverse proxy.

License

MIT

-
license - not tested
Not graded
quality - not tested
C
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Vaskka/akmcp-local'

If you have feedback or need assistance with the MCP directory API, please join our Discord server