Skip to main content
Glama
Evilran

Baidu Search MCP Server

by Evilran

search

Get formatted search results from Baidu for any query. Retrieve titles, URLs, and snippets, with optional deep content extraction.

Instructions

Search Baidu and return formatted results.

Args:
    query: The search query string
    max_results: Maximum number of results to return (default: 6)
    deep_mode: Deep search the web content (default: False)
    ctx: MCP context for logging

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
max_resultsNo
deep_modeNo

Implementation Reference

  • The MCP tool handler function for 'search', decorated with @mcp.tool(), which calls the BaiduSearcher.search method and formats results for LLM consumption.
    @mcp.tool()
    async def search(query: str, ctx: Context, max_results: int = 6, deep_mode: bool = False) -> str:
        """
        Search Baidu and return formatted results.
    
        Args:
            query: The search query string
            max_results: Maximum number of results to return (default: 6)
            deep_mode: Deep search the web content (default: False)
            ctx: MCP context for logging
        """
        try:
            results = await searcher.search(query, ctx, max_results, deep_mode)
            return searcher.format_results_for_llm(results)
        except Exception as e:
            traceback.print_exc(file=sys.stderr)
            return f"An error occurred while searching: {str(e)}"
  • The @mcp.tool() decorator registers the 'search' function as an MCP tool on the FastMCP server instance.
    @mcp.tool()
    async def search(query: str, ctx: Context, max_results: int = 6, deep_mode: bool = False) -> str:
  • The BaiduSearcher.search() method — the core search logic invoked by the MCP tool handler. Delegates to _perform_search() with error handling via @handle_errors.
    @handle_errors
    async def search(
        self, query: str, ctx: Context, max_results: int = 10, deep_mode: bool = False, max_retries: int = 2,
    ) -> List[SearchResult]:
        return await self._perform_search(
            query=query,
            max_results=max_results,
            deep_mode=deep_mode,
            max_retries=max_retries,
            ctx=ctx,
        )
  • The SearchResult dataclass schema defining the output structure (title, link, snippet, position).
    @dataclass
    class SearchResult:
        title: str
        link: str
        snippet: str
        position: int
  • The _perform_search() helper method that handles the actual Baidu search logic: pagination, retries, parsing, and optional deep mode content fetching.
    async def _perform_search(
        self,
        query: str,
        max_results: int,
        deep_mode: bool,
        max_retries: int,
        ctx: Optional[Context] = None,
    ) -> List[SearchResult]:
        await self._log_ctx(ctx, "info", f"Searching Baidu for: {query}")
    
        params = {"word": query}
        results: List[Dict[str, Any]] = []
        seen_urls: Set[str] = set()
        page = 0
    
        user_agent = self.HEADERS.get("User-Agent")
        extra_headers = {
            key: value
            for key, value in self.HEADERS.items()
            if key.lower() != "user-agent"
        }
        _, browser_context = await _ensure_browser(
            user_agent=user_agent, extra_headers=extra_headers or None
        )
    
        if browser_context is None:
            if CurlAsyncSession is None:
                await self._log_ctx(
                    ctx,
                    "error",
                    "Playwright is unavailable and curl_cffi is not installed; unable to execute search.",
                )
                return []
    
            await self._log_ctx(
                ctx,
                "warning",
                "Playwright unavailable; using curl_cffi fallback HTTP client.",
            )
    
        while len(results) < max_results:
            params["pn"] = page * 10
            page += 1
    
            html = await self._request_with_retries(browser_context, params, max_retries)
            if html is None:
                await self._log_ctx(
                    ctx, "error", "Failed to fetch search results from Baidu"
                )
                break
    
            page_results = self._parse_search_page(html, seen_urls)
            if not page_results:
                break
    
            results.extend(page_results)
    
        limited_results = results[:max_results]
        if deep_mode and limited_results:
            tasks = [self.process_result(result, idx + 1) for idx, result in enumerate(limited_results)]
            enriched_results = await asyncio.gather(*tasks, return_exceptions=True)
            search_results: List[SearchResult] = []
            for item in enriched_results:
                if isinstance(item, Exception):
                    logger.error("Deep fetch failed for a result: %s", item, exc_info=True)
                    continue
                if isinstance(item, SearchResult):
                    search_results.append(item)
        else:
            search_results = [
                self._create_search_result(result, idx + 1)
                for idx, result in enumerate(limited_results)
            ]
    
        await self._log_ctx(ctx, "info", f"Successfully found {len(search_results)} results")
        return search_results
Behavior2/5

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

The description does not disclose behavioral traits such as authentication requirements, rate limits, pagination behavior, or the nature of 'deep_mode.' With no annotations, the description carries full burden but fails to provide sufficient context beyond the basic function.

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

Conciseness2/5

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

The description is short but poorly structured. It includes unnecessary notation like 'Args:' and references a 'ctx' parameter not in the schema, which is misleading. It mixes parameter docs with the main description, reducing clarity.

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 tool has three parameters, no output schema, and no annotations, the description is incomplete. It fails to explain output format, error handling, or advanced usage. A search tool typically requires more documentation to be used correctly.

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

Parameters2/5

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

The parameter descriptions in 'Args' merely restate the schema field names and defaults (e.g., 'query: The search query string') without adding meaningful semantics. 'Deep search the web content' is vague. Schema coverage is 0%, and the description adds only trivial value.

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 states 'Search Baidu and return formatted results,' which clearly identifies the tool's action (search) and resource (Baidu), and implies output formatting. No sibling tools exist, so differentiation is not needed. However, it could be more specific about the result format (e.g., titles, URLs, snippets).

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 guidance is provided on when to use this tool or its limitations. For a search tool, one would expect notes on query syntax, rate limits, or alternatives, but none are given.

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/Evilran/baidu-mcp-server'

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