Skip to main content
Glama

search_news_info

Search news articles using Brave News API to find relevant information based on specific keywords, returning titles, sources, dates, and descriptions.

Instructions

使用Brave新闻API搜索新闻

参数:
    query (str): 新闻搜索关键词
    
返回:
    str: 新闻搜索结果,包含标题、来源、日期和描述

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes

Implementation Reference

  • The handler function for the "search_news_info" MCP tool. Registered with @mcp.tool() decorator. Defines input schema via function signature and docstring (query: str -> str). Delegates execution to the _do_news_search helper.
    def search_news_info(query: str) -> str:
        """使用Brave新闻API搜索新闻
        
        参数:
            query (str): 新闻搜索关键词
            
        返回:
            str: 新闻搜索结果,包含标题、来源、日期和描述
        """
        return _do_news_search(query)
  • Core helper implementing the news search logic: detects language with _detect_language, calls Brave News API, processes results into formatted list with title, source, date, URL, description.
    def _do_news_search(query: str, country: str = "all", search_lang: str = None) -> str:
        """Internal function to handle news search using Brave News API"""
        try:
            query = query.encode('utf-8').decode('utf-8')
            
            # 如果未指定语言,自动检测
            if search_lang is None:
                search_lang = _detect_language(query)
                logger.debug(f"Detected language: {search_lang} for query: {query}")
            
            url = "https://api.search.brave.com/res/v1/news/search"
            
            headers = {
                "Accept": "application/json",
                "Accept-Encoding": "gzip",
                "X-Subscription-Token": API_KEY
            }
            
            params = {
                "q": query,
                "count": 10,
                "country": country,
                "search_lang": search_lang,
                "spellcheck": 1
            }
            
            logger.debug(f"Searching news for query: {query}")
            response = requests.get(url, headers=headers, params=params)
            response.raise_for_status()
            data = response.json()
            
            # 处理新闻搜索结果
            results = []
            if 'results' in data:
                for news in data['results']:
                    title = news.get('title', 'No title').encode('utf-8').decode('utf-8')
                    url = news.get('url', 'No URL')
                    description = news.get('description', 'No description').encode('utf-8').decode('utf-8')
                    date = news.get('published_time', 'Unknown date')
                    source = news.get('source', {}).get('name', 'Unknown source')
                    
                    news_item = [
                        f"- {title}",
                        f"  Source: {source}",
                        f"  Date: {date}",
                        f"  URL: {url}",
                        f"  Description: {description}\n"
                    ]
                    results.append("\n".join(news_item))
            
            if not results:
                return "No news found for your query."
                
            return "News Results:\n\n" + "\n".join(results)
            
        except requests.exceptions.RequestException as e:
            logger.error(f"News API request error: {str(e)}")
            return f"Error searching news: {str(e)}"
        except Exception as e:
            logger.error(f"News search error: {str(e)}")
            logger.exception("Detailed error trace:")
            return f"Error searching news: {str(e)}"
    @mcp.tool()
  • Supporting helper for language detection used in news search to set search_lang parameter automatically.
    def _detect_language(text: str) -> str:
        """检测文本语言并返回对应的语言代码"""
        # 定义语言检测规则
        LANGUAGE_PATTERNS = {
            # 中文 (简体和繁体)
            'zh-hans': ('\u4e00', '\u9fff'),  # 简体中文
            'zh-hant': ('\u4e00', '\u9fff'),  # 繁体中文
            # 日文
            'jp': ('\u3040', '\u309f', '\u30a0', '\u30ff'),  # 平假名和片假名
            # 韩文
            'ko': ('\uac00', '\ud7af'),  # 谚文
            # 俄文
            'ru': ('\u0400', '\u04ff'),  # 西里尔字母
            # 阿拉伯文
            'ar': ('\u0600', '\u06ff'),
            # 希伯来文
            'he': ('\u0590', '\u05ff'),
            # 泰文
            'th': ('\u0e00', '\u0e7f'),
            # 越南文 (使用扩展拉丁字母)
            'vi': ('àáạảãâầấậẩẫăằắặẳẵèéẹẻẽêềếệểễìíịỉĩòóọỏõôồốộổỗơờớợởỡùúụủũưừứựửữỳýỵỷỹđ'),
            # 印地文
            'hi': ('\u0900', '\u097f'),
            # 泰米尔文
            'ta': ('\u0b80', '\u0bff'),
            # 特卢固文
            'te': ('\u0c00', '\u0c7f'),
        }
    
        def contains_chars_in_range(text, *ranges):
            """检查文本是否包含指定Unicode范围内的字符"""
            if len(ranges) % 2 == 0:  # 范围对
                for i in range(0, len(ranges), 2):
                    start, end = ranges[i:i+2]
                    if any(start <= char <= end for char in text):
                        return True
            else:  # 字符列表
                return any(char in ranges[0] for char in text)
            return False
    
        # 检测常见的非拉丁文字系统
        for lang, pattern in LANGUAGE_PATTERNS.items():
            if contains_chars_in_range(text, *pattern):
                # 对中文进行简繁体识别(这里使用简单规则,实际应用可能需要更复杂的逻辑)
                if lang in ['zh-hans', 'zh-hant']:
                    # 这里可以添加更复杂的简繁体识别逻辑
                    return 'zh-hans'  # 默认返回简体中文
                return lang
    
        # 检测拉丁字母语言(简单示例)
        # 注意:这是一个非常简化的实现,实际应用可能需要更复杂的语言检测
        LATIN_PATTERNS = {
            'es': ['ñ', 'á', 'é', 'í', 'ó', 'ú', '¿', '¡'],
            'fr': ['é', 'è', 'ê', 'à', 'ç', 'ù', 'û', 'ï'],
            'de': ['ä', 'ö', 'ü', 'ß'],
            'pt-pt': ['ã', 'õ', 'á', 'é', 'í', 'ó', 'ú', 'â', 'ê', 'ô'],
            'it': ['à', 'è', 'é', 'ì', 'ò', 'ó', 'ù'],
        }
    
        for lang, patterns in LATIN_PATTERNS.items():
            if any(pattern in text.lower() for pattern in patterns):
                return lang
    
        # 默认返回英语
        return "en"
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 the API source (Brave News API) and return format, but lacks details on rate limits, authentication needs, error handling, or pagination. This is insufficient for a tool with no annotation coverage.

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

Conciseness4/5

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

The description is concise and well-structured with clear sections for parameters and returns, using minimal sentences. However, it could be more front-loaded by integrating the purpose with usage context, and some information (like the return format) might be better suited for an output schema.

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 (single parameter, no output schema, no annotations), the description covers the basic purpose and return format but misses key contextual elements like usage guidelines, behavioral traits, and differentiation from siblings. It's adequate but has clear gaps.

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 description adds basic semantic context for the single parameter ('query' as a news search keyword), but with 0% schema description coverage, it doesn't fully compensate by providing examples, constraints, or formatting details. The baseline is 3 since it adds some value beyond the minimal schema.

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 as '使用Brave新闻API搜索新闻' (search for news using the Brave News API), which specifies the verb (search), resource (news), and method (Brave News API). However, it doesn't explicitly differentiate from sibling tools like 'search_news' or 'search_brave_with_summary', which likely have overlapping functionality.

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. With sibling tools such as 'search_news' and 'search_brave_with_summary' available, there is no indication of specific contexts, prerequisites, or exclusions that would help an agent choose appropriately.

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/mcp2everything/mcp2brave'

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