Skip to main content
Glama
24mlight

A Share MCP

get_stock_basic_info

Retrieve basic Chinese A-share stock details including code, name, industry, and listing date using Baostock format 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 for 'get_stock_basic_info': decorated with @app.tool(), logs invocation, wraps use case execution with standardized error handling.
    @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}",
        )
  • mcp_server.py:51-51 (registration)
    Invocation of register_stock_market_tools which defines and registers the stock market tools including 'get_stock_basic_info' to the FastMCP app.
    register_stock_market_tools(app, active_data_source)
  • Helper use case function: validates format, fetches raw data from FinancialDataSource, formats output as markdown/JSON/CSV table.
    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)
  • BaostockDataSource implementation: performs the actual Baostock query_stock_basic API call, handles errors, supports field selection, returns DataFrame.
    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}")
  • Abstract base class method defining the interface contract for stock basic info retrieval across data sources.
    @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
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions the data source (Baostock) and optional field selection, but doesn't cover important aspects like rate limits, authentication requirements, error conditions, or whether this is a read-only operation. The description doesn't contradict annotations (none exist), but leaves significant behavioral gaps.

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 well-structured and appropriately sized. It begins with a clear purpose statement, then provides detailed parameter documentation in a readable format, and ends with return information. Every sentence adds value with no redundancy or 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 3-parameter tool with no annotations and no output schema, the description does a good job explaining parameters but leaves gaps in behavioral context. It doesn't describe the return structure beyond 'basic stock information in the requested format,' which is insufficient given the lack of output schema. The description covers the 'what' but not the 'how' of tool behavior.

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

Parameters5/5

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

Given 0% schema description coverage, the description provides excellent parameter semantics. It clearly explains the 'code' parameter format (Baostock format with examples), details the 'fields' parameter behavior (optional list, default returns all columns, with examples), and mentions the return format. This fully compensates for the schema's lack of descriptions.

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

Purpose4/5

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

The description clearly states the tool's purpose: 'Fetches basic information for a given Chinese A-share stock.' It specifies the resource (stock) and action (fetch basic info), distinguishing it from siblings like get_historical_k_data or get_balance_data which fetch different data types. However, it doesn't explicitly differentiate from get_stock_industry or get_stock_analysis which might overlap in scope.

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

Usage Guidelines3/5

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

The description implies usage through the context of fetching 'basic information' for stocks, suggesting it's for fundamental data rather than price or technical analysis. However, it doesn't explicitly state when to use this tool versus alternatives like get_stock_industry or get_fina_indicator, nor does it mention any prerequisites or exclusions.

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