Skip to main content
Glama
marckwei

MCP Yahoo Finance

by marckwei

get_recommendations

Retrieve analyst recommendations for stocks to inform investment decisions using Yahoo Finance data.

Instructions

Get analyst recommendations for a given symbol.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolYesStock symbol in Yahoo Finance format.

Implementation Reference

  • The primary handler function implementing the tool logic: fetches analyst recommendations using yfinance's Ticker.get_recommendations(), formats as JSON if DataFrame.
    def get_recommendations(self, symbol: str) -> str:
        """Get analyst recommendations for a given symbol.
    
        Args:
            symbol (str): Stock symbol in Yahoo Finance format.
        """
        stock = Ticker(ticker=symbol, session=self.session)
        recommendations = stock.get_recommendations()
        print(recommendations)
        if isinstance(recommendations, pd.DataFrame):
            return f"{recommendations.to_json(orient='records', indent=2)}"
        return f"{recommendations}"
  • Tool registration in the MCP server's list_tools() method, where generate_tool(yf.get_recommendations) creates and returns the Tool instance with schema.
    @server.list_tools()
    async def list_tools() -> list[Tool]:
        return [            
            generate_tool(yf.cmd_run),
            generate_tool(yf.get_recommendations),
            generate_tool(yf.get_news),
            generate_tool(yf.get_current_stock_price),
            generate_tool(yf.get_stock_price_by_date),
            generate_tool(yf.get_stock_price_date_range),
            generate_tool(yf.get_historical_stock_prices),
            generate_tool(yf.get_dividends),
            generate_tool(yf.get_income_statement),
            generate_tool(yf.get_cashflow),
            generate_tool(yf.get_earning_dates),
        ]
  • MCP server call_tool dispatcher case that invokes the get_recommendations handler and returns the result as TextContent.
    case "get_recommendations":
        recommendations = yf.get_recommendations(**args)
        return [TextContent(type="text", text=recommendations)]
  • Dynamic schema generation for all tools, including get_recommendations, based on function signature, type annotations, and Google-style docstring.
    def generate_tool(func: Any) -> Tool:
        """Generates a tool schema from a Python function."""
        signature = inspect.signature(func)
        docstring = inspect.getdoc(func) or ""
        param_descriptions = parse_docstring(docstring)
    
        schema = {
            "name": func.__name__,
            "description": docstring.split("Args:")[0].strip(),
            "inputSchema": {
                "type": "object",
                "properties": {},
            },
        }
    
        for param_name, param in signature.parameters.items():
            param_type = (
                "number"
                if param.annotation is float
                else "string"
                if param.annotation is str
                else "string"
            )
            schema["inputSchema"]["properties"][param_name] = {
                "type": param_type,
                "description": param_descriptions.get(param_name, ""),
            }
    
            if "required" not in schema["inputSchema"]:
                schema["inputSchema"]["required"] = [param_name]
            else:
                if "=" not in str(param):
                    schema["inputSchema"]["required"].append(param_name)
    
        return Tool(**schema)
  • Helper function used by generate_tool to parse docstrings for parameter descriptions in the tool schema.
    def parse_docstring(docstring: str) -> dict[str, str]:
        """Parses a Google-style docstring to extract parameter descriptions."""
        descriptions = {}
        if not docstring:
            return descriptions
    
        lines = docstring.split("\n")
        current_param = None
    
        for line in lines:
            line = line.strip()
            if line.startswith("Args:"):
                continue
            elif line and "(" in line and ")" in line and ":" in line:
                param = line.split("(")[0].strip()
                desc = line.split("):")[1].strip()
                descriptions[param] = desc
                current_param = param
            elif current_param and line:
                descriptions[current_param] += " " + line.strip()
    
        return descriptions
Behavior2/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 states the tool retrieves recommendations but does not cover critical aspects like data freshness, rate limits, authentication needs, error handling, or response format. For a tool that likely involves external data sources, this omission is significant and leaves the agent unprepared for operational nuances.

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 a single, clear sentence: 'Get analyst recommendations for a given symbol.' It is front-loaded with the core action and resource, with no redundant or verbose language. Every word earns its place, making it highly efficient and easy to parse for an AI agent.

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

Completeness2/5

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

Given the lack of annotations and output schema, the description is incomplete for a tool that likely involves complex financial data retrieval. It does not address behavioral traits, response structure, or usage context, which are crucial for an agent to operate effectively. While the purpose is clear, the overall context is insufficient for reliable tool invocation.

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 schema description coverage is 100%, with the 'symbol' parameter fully documented in the input schema as 'Stock symbol in Yahoo Finance format.' The description adds no additional semantic context beyond this, such as examples or constraints. Given the high schema coverage, the baseline score of 3 is appropriate, as the description does not enhance parameter understanding but also does not detract from it.

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: 'Get analyst recommendations for a given symbol.' It specifies the verb ('Get') and resource ('analyst recommendations') with the target ('symbol'). However, it does not distinguish this from sibling tools like 'get_news' or 'get_current_stock_price' that also retrieve financial data for symbols, leaving some ambiguity about its unique role.

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?

The description provides no guidance on when to use this tool versus alternatives. It does not mention prerequisites, exclusions, or comparisons to sibling tools such as 'get_news' or 'get_earning_dates', which might offer related financial insights. This lack of context could lead to misuse in scenarios where other tools are more appropriate.

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/marckwei/no-use-tools'

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