Skip to main content
Glama
24mlight

A-Share MCP Server

get_stock_basic_info

Retrieve fundamental data for Chinese A-share stocks including company details, industry classification, and listing information using stock codes.

Instructions

    Fetches basic information for a given Chinese A-share stock.

    Args:
        code: The stock code in Baostock format (e.g., 'sh.600000', 'sz.000001').
        fields: Optional list to select specific columns from the available basic info
                (e.g., ['code', 'code_name', 'industry', 'listingDate']).
                If None or empty, returns all available basic info columns from Baostock.

    Returns:
        Basic stock information in the requested format.
    

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYes
fieldsNo
formatNomarkdown

Implementation Reference

  • MCP tool handler decorated with @app.tool(). Logs invocation, delegates to use case fetch_stock_basic_info via run_tool_with_handling for shared error handling and formatting, returns str output.
    @app.tool()
    def get_stock_basic_info(code: str, fields: Optional[List[str]] = None, format: str = "markdown") -> str:
        """
        Fetches basic information for a given Chinese A-share stock.
    
        Args:
            code: The stock code in Baostock format (e.g., 'sh.600000', 'sz.000001').
            fields: Optional list to select specific columns from the available basic info
                    (e.g., ['code', 'code_name', 'industry', 'listingDate']).
                    If None or empty, returns all available basic info columns from Baostock.
    
        Returns:
            Basic stock information in the requested format.
        """
        logger.info(f"Tool 'get_stock_basic_info' called for {code} (fields={fields})")
        return run_tool_with_handling(
            lambda: fetch_stock_basic_info(
                active_data_source, code=code, fields=fields, format=format
            ),
            context=f"get_stock_basic_info:{code}",
        )
  • Abstract base class method defining the input/output schema (code: str -> pd.DataFrame) and expected behavior/raises for data source implementations.
    @abstractmethod
    def get_stock_basic_info(self, code: str) -> pd.DataFrame:
        """
        Fetches basic information for a given stock code.
    
        Args:
            code: The stock code (e.g., 'sh.600000', 'sz.000001').
    
        Returns:
            A pandas DataFrame containing the basic stock information.
            The structure and columns depend on the underlying data source.
            Typically contains info like name, industry, listing date, etc.
    
        Raises:
            LoginError: If login to the data source fails.
            NoDataFoundError: If no data is found for the query.
            DataSourceError: For other data source related errors.
            ValueError: If the input code is invalid.
        """
        pass
  • mcp_server.py:51-51 (registration)
    Invocation of the registration function that adds the get_stock_basic_info tool (and others) to the FastMCP app instance.
    register_stock_market_tools(app, active_data_source)
  • Orchestrates fetching raw DataFrame from data_source, applies output formatting via format_table_output, handles validation.
    def fetch_stock_basic_info(
        data_source: FinancialDataSource,
        *,
        code: str,
        fields: Optional[List[str]] = None,
        format: str = "markdown",
    ) -> str:
        validate_output_format(format)
        df = data_source.get_stock_basic_info(code=code, fields=fields)
        meta = {"code": code}
        return format_table_output(df, format=format, max_rows=df.shape[0] if df is not None else 0, meta=meta)
  • Concrete Baostock implementation: calls bs.query_stock_basic, handles login/context/errors/pagination, builds DataFrame, supports field selection.
    def get_stock_basic_info(self, code: str, fields: Optional[List[str]] = None) -> pd.DataFrame:
        """Fetches basic stock information using Baostock."""
        logger.info(f"Fetching basic info for {code}")
        try:
            # Note: query_stock_basic doesn't seem to have a fields parameter in docs,
            # but we keep the signature consistent. It returns a fixed set.
            # We will use the `fields` argument post-query to select columns if needed.
            logger.debug(
                f"Requesting basic info for {code}. Optional fields requested: {fields}")
    
            with baostock_login_context():
                # Example: Fetch basic info; adjust API call if needed based on baostock docs
                # rs = bs.query_stock_basic(code=code, code_name=code_name) # If supporting name lookup
                rs = bs.query_stock_basic(code=code)
    
                if rs.error_code != '0':
                    logger.error(
                        f"Baostock API error (Basic Info) for {code}: {rs.error_msg} (code: {rs.error_code})")
                    if "no record found" in rs.error_msg.lower() or rs.error_code == '10002':
                        raise NoDataFoundError(
                            f"No basic info found for {code}. Baostock msg: {rs.error_msg}")
                    else:
                        raise DataSourceError(
                            f"Baostock API error fetching basic info: {rs.error_msg} (code: {rs.error_code})")
    
                data_list = []
                while rs.next():
                    data_list.append(rs.get_row_data())
    
                if not data_list:
                    logger.warning(
                        f"No basic info found for {code} (empty result set from Baostock).")
                    raise NoDataFoundError(
                        f"No basic info found for {code} (empty result set).")
    
                # Crucial: Use rs.fields for column names
                result_df = pd.DataFrame(data_list, columns=rs.fields)
                logger.info(
                    f"Retrieved basic info for {code}. Columns: {result_df.columns.tolist()}")
    
                # Optional: Select subset of columns if `fields` argument was provided
                if fields:
                    available_cols = [
                        col for col in fields if col in result_df.columns]
                    if not available_cols:
                        raise ValueError(
                            f"None of the requested fields {fields} are available in the basic info result.")
                    logger.debug(
                        f"Selecting columns: {available_cols} from basic info for {code}")
                    result_df = result_df[available_cols]
    
                return result_df
    
        except (LoginError, NoDataFoundError, DataSourceError, ValueError) as e:
            logger.warning(
                f"Caught known error fetching basic info for {code}: {type(e).__name__}")
            raise e
        except Exception as e:
            logger.exception(
                f"Unexpected error fetching basic info for {code}: {e}")
            raise DataSourceError(
                f"Unexpected error fetching basic info for {code}: {e}")
Behavior2/5

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

With no annotations, the description carries full burden but lacks behavioral details. It doesn't disclose rate limits, authentication needs, error handling, or data freshness. The mention of Baostock format hints at an external source but doesn't explain implications like availability or latency.

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 front-loaded with the core purpose, followed by structured Args and Returns sections. Each sentence adds value: the first defines scope, the next two clarify parameters, and the last summarizes output. No wasted words.

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

Completeness3/5

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

For a read-only tool with no output schema and low schema coverage, the description is moderately complete. It covers purpose and most parameters but lacks behavioral context, output details, and sibling differentiation, leaving gaps for an AI agent to infer usage.

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

Parameters4/5

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

Schema description coverage is 0%, so the description compensates well by explaining 'code' format with examples and 'fields' behavior with defaults and examples. However, it omits the 'format' parameter entirely, leaving one of three parameters undocumented.

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 verb 'fetches' and the resource 'basic information for a given Chinese A-share stock', specifying the exact scope. It distinguishes itself from siblings like get_historical_k_data (price data) or get_balance_data (financials) by focusing on static metadata.

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

Usage Guidelines2/5

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

No explicit guidance on when to use this tool versus alternatives is provided. The description doesn't mention prerequisites, compare with get_stock_industry or get_all_stock, or specify use cases like initial stock research versus detailed analysis.

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

Install Server

Other Tools

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/24mlight/a-share-mcp-is-just-i-need'

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