Skip to main content
Glama
Evilran

Baidu Search MCP Server

by Evilran

search

Search Baidu and retrieve formatted results with options to control the number of outputs and enable deep content analysis for enhanced web data 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
deep_modeNo
max_resultsNo
queryYes

Implementation Reference

  • Primary MCP tool handler for 'search'. Registers the tool and executes Baidu search via BaiduSearcher, formats results as string for LLM.
    @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)}"
  • Dataclass schema for individual search results returned by the internal search logic.
    @dataclass
    class SearchResult:
        title: str
        link: str
        snippet: str
        position: int
  • Core helper function in BaiduSearcher class that invokes the search performance logic.
    @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,
        )
  • Main helper implementing the search logic: fetches Baidu pages using browser or curl_cffi, parses results, optionally deep-fetches content.
    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?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions 'return formatted results,' which gives some output context, but lacks details on rate limits, authentication needs, error handling, or what 'deep search' entails beyond the parameter name. For a search tool with zero annotation coverage, this is insufficient to fully inform the agent about behavioral traits.

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 appropriately sized and front-loaded, starting with the core purpose in the first sentence. The parameter list is organized but includes 'ctx: MCP context for logging,' which may be extraneous if not part of the input schema. Overall, it's efficient with minimal waste, though not perfectly structured.

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 complexity of a search tool with 3 parameters, 0% schema description coverage, no annotations, and no output schema, the description is incomplete. It lacks details on output format, error cases, behavioral constraints, and deeper parameter meanings. This makes it inadequate for fully guiding an AI agent in 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 0%, so the description must compensate. It lists parameters with brief explanations (e.g., 'query: The search query string'), adding basic semantics beyond the schema's titles. However, it doesn't fully explain 'deep_mode' or provide format details for 'formatted results,' leaving gaps. This partial compensation justifies a baseline score of 3.

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: 'Search Baidu and return formatted results.' This specifies the verb ('search'), resource ('Baidu'), and outcome ('formatted results'), making it easy to understand what the tool does. However, since there are no sibling tools mentioned, it cannot differentiate from alternatives, which prevents a perfect score of 5.

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, prerequisites, or specific contexts. It simply states what the tool does without indicating scenarios where it's appropriate or inappropriate. This lack of usage context limits its helpfulness for an AI agent in decision-making.

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

Related 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