Skip to main content
Glama

get_news

Retrieve recent news headlines for a specific stock symbol to support trading decisions and portfolio analysis.

Instructions

Retrieves recent news headlines for a given symbol.

Args:
    symbol: Ticker symbol.
    max_items: Maximum number of news items to return.

Returns:
    JSON string of news articles with titles and publishers.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolYes
max_itemsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The core handler function for the 'get_news' tool. Fetches recent news headlines for a given stock symbol using yfinance, with fallbacks to NewsAPI and Google News if no results. Returns formatted JSON with title, publisher, and link.
    def get_news(symbol: str, max_items: int = 10) -> str:
        """
        Retrieves recent news headlines for a given symbol.
        
        Args:
            symbol: Ticker symbol.
            max_items: Maximum number of news items to return.
        
        Returns:
            JSON string of news articles with titles and publishers.
        """
        try:
            ticker = yf.Ticker(symbol)
            news = ticker.news
            
            if not news:
                # Try NewsAPI first if available
                if NEWSAPI_KEY:
                    logger.info(f"yfinance news empty for {symbol}, trying NewsAPI")
                    newsapi_results = get_newsapi_articles(symbol, max_items)
                    if newsapi_results:
                        import json
                        return json.dumps(newsapi_results, indent=2)
                
                # Fallback to Google News
                logger.info(f"Trying GNews fallback for {symbol}")
                gnews_results = get_google_news(symbol, max_items)
                if gnews_results:
                    import json
                    return json.dumps(gnews_results, indent=2)
                
                logger.warning(f"No news found for {symbol} from any source")
                return f"No news found for {symbol}"
            
            # Limit results
            news = news[:max_items]
            
            # Extract relevant fields (handle nested yfinance structure)
            results = []
            for item in news:
                # yfinance returns nested structure with 'content' key
                content = item.get("content", item)  # fallback to item if no content key
                title = content.get("title", "")
                
                # Publisher info is in 'provider' dict
                provider = content.get("provider", {})
                publisher = provider.get("displayName", "") if isinstance(provider, dict) else item.get("publisher", "")
                
                link = content.get("canonicalUrl", {}).get("url", "")
                if not link:
                    link = item.get("link", "")
                
                results.append({
                    "title": title,
                    "publisher": publisher,
                    "link": link,
                })
            
            logger.info(f"Fetched {len(results)} news items for {symbol} from yfinance")
            import json
            return json.dumps(results, indent=2)
            
        except Exception as e:
            logger.error(f"Error fetching news for {symbol}: {e}", exc_info=True)
            return f"Error fetching news for {symbol}: {str(e)}"
  • server.py:405-408 (registration)
    Registers the get_news function as an MCP tool in the FastMCP server, along with related sentiment analysis tools.
    register_tools(
        [get_news, analyze_sentiment, get_symbol_sentiment],
        "News & Sentiment"
    )
  • Helper function called by get_news as fallback when yfinance returns no news. Fetches articles from NewsAPI.org.
    def get_newsapi_articles(symbol: str, max_items: int = 5) -> List[Dict]:
        """
        Fetches news from NewsAPI.org using the company name or symbol.
        """
        if not NEWSAPI_KEY:
            logger.warning("NewsAPI key not configured")
            return []
            
        try:
            newsapi = NewsApiClient(api_key=NEWSAPI_KEY)
            
            # Search for the symbol (NewsAPI works better with company names, but symbols can work)
            # We'll search in business category for relevance
            response = newsapi.get_everything(
                q=symbol,
                language='en',
                sort_by='publishedAt',
                page_size=max_items
            )
            
            articles = response.get('articles', [])
            cleaned = []
            for article in articles:
                cleaned.append({
                    "title": article.get("title", ""),
                    "publisher": article.get("source", {}).get("name", "Unknown"),
                    "link": article.get("url", ""),
                    "published": article.get("publishedAt", ""),
                    "description": article.get("description", "")
                })
            return cleaned
        except Exception as e:
            logger.error(f"NewsAPI error for {symbol}: {e}")
            return []
  • Secondary fallback helper for fetching news from Google News using GNews library.
    def get_google_news(symbol: str, max_items: int = 5) -> List[Dict]:
        """
        Fetches news from Google News via GNews library.
        """
        try:
            google_news = GNews(max_results=max_items)
            # Search for the symbol
            results = google_news.get_news(symbol)
            
            cleaned = []
            for item in results:
                cleaned.append({
                    "title": item.get("title", ""),
                    "publisher": item.get("publisher", {}).get("title", "Unknown"),
                    "link": item.get("url", ""),
                    "published": item.get("published date", "")
                })
            return cleaned
        except Exception as e:
            logger.error(f"GNews error for {symbol}: {e}")
            return []
  • server.py:19-19 (registration)
    Import statement that brings the get_news handler into the server module for registration.
    from tools.news_intelligence import get_news, analyze_sentiment, get_symbol_sentiment
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions retrieval and the return format ('JSON string of news articles with titles and publishers'), but lacks details on rate limits, authentication needs, error handling, or data freshness (e.g., how 'recent' is defined). For a tool with no annotation coverage, this leaves significant gaps in understanding its operational behavior.

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 front-loaded with the core purpose, followed by clear sections for arguments and returns. Every sentence adds value without redundancy, making it efficient and easy to parse.

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?

Given the tool's moderate complexity (2 parameters, no annotations, but has an output schema), the description is partially complete. It covers the purpose and parameters adequately, and the output schema likely details the return structure, reducing the need for return value explanation. However, it lacks behavioral details and usage guidelines, leaving room for improvement in overall context.

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?

The description adds meaningful context beyond the input schema, which has 0% description coverage. It explains that 'symbol' is a 'Ticker symbol' and 'max_items' controls the 'Maximum number of news items to return', clarifying their roles. However, it does not specify constraints like valid symbol formats or max_items range, so it doesn't fully compensate 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: 'Retrieves recent news headlines for a given symbol.' This specifies the verb ('retrieves'), resource ('news headlines'), and scope ('for a given symbol'). However, it does not explicitly differentiate from sibling tools like 'get_symbol_sentiment' or 'get_fundamentals', which might also involve news or data retrieval, so it falls short of a perfect score.

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 sibling tools like 'get_symbol_sentiment' (which might analyze news sentiment) or 'search_crypto' (which could include news), nor does it specify prerequisites or exclusions. Usage is implied only by the purpose statement.

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/N-lia/MonteWalk'

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