Skip to main content
Glama
aahl

MCP Server for stock and crypto

by aahl

查找股票代码

search

Find stock codes by entering company name, stock name, or keyword for Shanghai, Shenzhen, Hong Kong, or US markets. Does not support cryptocurrency.

Instructions

根据股票名称、公司名称等关键词查找股票代码, 不支持加密货币。该工具比较耗时,当你知道股票代码或用户已指定股票代码时,建议直接通过股票代码使用其他工具

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
keywordYes搜索关键词,公司名称、股票名称、股票代码、证券简称
marketNo股票市场,仅支持: sh(上证), sz(深证), hk(港股), us(美股), 不支持加密货币sh

Implementation Reference

  • Main handler function for the 'search' MCP tool. Decorated with @mcp.tool, accepts keyword and market parameters, delegates to ak_search() helper, and formats the result.
    @mcp.tool(
        title="查找股票代码",
        description="根据股票名称、公司名称等关键词查找股票代码, 不支持加密货币。"
                    "该工具比较耗时,当你知道股票代码或用户已指定股票代码时,建议直接通过股票代码使用其他工具",
    )
    def search(
        keyword: str = Field(description="搜索关键词,公司名称、股票名称、股票代码、证券简称"),
        market: str = field_market,
    ):
        info = ak_search(None, keyword, market)
        if info is not None:
            suffix = f"交易市场: {market}"
            return "\n".join([info.to_string(), suffix])
        return f"Not Found for {keyword}"
  • Input schema for the search tool: keyword (required string) and market (optional, defaults to 'sh').
    keyword: str = Field(description="搜索关键词,公司名称、股票名称、股票代码、证券简称"),
    market: str = field_market,
  • Helper function that searches across multiple markets (SH, SZ, HK, US) using akshare APIs. Supports exact code match, keyword match (code or name), substring match (keyword length >= 4), and prefix match.
    def ak_search(symbol=None, keyword=None, market=None):
        markets = [
            ["sh", ak.stock_info_a_code_name, "code", "name"],
            ["sh", ak.stock_info_sh_name_code, "证券代码", "证券简称"],
            ["sz", ak.stock_info_sz_name_code, "A股代码", "A股简称"],
            ["hk", ak.stock_hk_spot, "代码", "中文名称"],
            ["hk", ak.stock_hk_spot_em, "代码", "名称"],
            ["us", ak.get_us_stock_name, "symbol", "cname"],
            ["us", ak.get_us_stock_name, "symbol", "name"],
            ["sh", ak.fund_etf_spot_ths, "基金代码", "基金名称"],
            ["sz", ak.fund_etf_spot_ths, "基金代码", "基金名称"],
            ["sh", ak.fund_info_index_em, "基金代码", "基金名称"],
            ["sz", ak.fund_info_index_em, "基金代码", "基金名称"],
            ["sh", ak.fund_etf_spot_em, "代码", "名称"],
            ["sz", ak.fund_etf_spot_em, "代码", "名称"],
        ]
        for m in markets:
            if market and market != m[0]:
                continue
            all = ak_cache(m[1], ttl=86400, ttl2=86400*7)
            if all is None or all.empty:
                continue
            for _, v in all.iterrows():
                code, name = str(v[m[2]]).upper(), str(v[m[3]]).upper()
                if symbol and symbol.upper() == code:
                    return v
                if keyword and keyword.upper() in [code, name]:
                    return v
            for _, v in all.iterrows() if keyword else []:
                name = str(v[m[3]])
                if len(keyword) >= 4 and keyword in name:
                    return v
                if name.startswith(keyword):
                    return v
        return None
  • Caching helper that wraps akshare API calls with a two-level cache (in-memory TTL cache + disk cache) to avoid redundant network requests.
    def ak_cache(fun, *args, **kwargs) -> pd.DataFrame | None:
        key = kwargs.pop("key", None)
        if not key:
            key = f"{fun.__name__}-{args}-{kwargs}"
        ttl1 = kwargs.pop("ttl", 86400)
        ttl2 = kwargs.pop("ttl2", None)
        cache = CacheKey.init(key, ttl1, ttl2)
        all = cache.get()
        if all is None:
            try:
                _LOGGER.info("Request akshare: %s", [key, args, kwargs])
                all = fun(*args, **kwargs)
                cache.set(all)
            except Exception as exc:
                _LOGGER.exception(str(exc))
        return all
  • Registration of the 'search' tool via the @mcp.tool decorator on the FastMCP instance, with title '查找股票代码'.
    @mcp.tool(
        title="查找股票代码",
        description="根据股票名称、公司名称等关键词查找股票代码, 不支持加密货币。"
                    "该工具比较耗时,当你知道股票代码或用户已指定股票代码时,建议直接通过股票代码使用其他工具",

Schema Changelog

Changes observed during successful MCP inspections.

  1. Changed1 schema field changedv1.0.0
    • changedInput schema / properties / market / description
      Previous value: -"股票市场,如: sh(上证), sz(深证), hk(港股), us(美股) 等"New value: +"股票市场,仅支持: sh(上证), sz(深证), hk(港股), us(美股), 不支持加密货币"
  2. First observed

TDQS

A4.2/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It adds valuable context: '不支持加密货币' (cryptocurrencies not supported) and '比较耗时' (relatively time-consuming). However, it does not disclose the return format or how results are presented (e.g., single code vs. list), which is important for a search tool without an output schema. No annotation contradiction exists.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is exceptionally concise: two sentences that front-load the core purpose and immediately follow with actionable usage guidance. Every clause adds value—the first sentence states function and limitation, the second explains when to avoid the tool. No wasted words or redundant information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's simplicity (2 params, 1 required, no output schema), the description covers the key aspects: purpose, scope (no crypto), performance, and selection guidance. The only notable omission is an explicit statement of what the tool returns (e.g., a list of matching stock codes), but this is strongly implied by the title and purpose. Overall, near-complete for this low-complexity tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema already covers both parameters with 100% coverage: 'keyword' is described as requiring company/stock names or codes, and 'market' is fully documented with allowed values. The tool description restates '股票名称、公司名称等关键词', duplicating the keyword schema. It adds no new parameter-specific meaning, so the baseline score of 3 applies.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's function: '根据股票名称、公司名称等关键词查找股票代码' (find stock codes based on keywords such as stock/company names). It uses the specific verb '查找' (find) and names the resource '股票代码', distinguishing it from sibling tools that operate on already-known codes. The explicit exclusion of cryptocurrencies further clarifies its scope relative to crypto-related siblings.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit usage guidance: '该工具比较耗时,当你知道股票代码或用户已指定股票代码时,建议直接通过股票代码使用其他工具' (This tool is time-consuming; when you know the code or user has specified one, directly use other tools with the code). This tells the agent when to avoid the tool and to prefer alternatives, making the decision clear, even though it doesn't name specific sibling tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.