Skip to main content
Glama

rag_search_google

Search Google, rank results by RAG similarity, and return context for LLMs in markdown format with optional URLs.

Instructions

Search on Google for a given query using ddgs. Give back context to the LLM with a RAG-like similarity sort.

Args: query (str): The query to search for. num_results (int): Number of results to return. top_k (int): Use top "k" results for content. include_urls (bool): Whether to include URLs in the results. If True, the results will be a list of dictionaries with the following keys: - type: "text" - text: The content of the result - url: The URL of the result

Returns: Dict of strings containing best search based on input query. Formatted in markdown.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
num_resultsNo
top_kNo
include_urlsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Handler function for the rag_search_google tool. Uses ddgs library with Google backend to search, scores results by semantic similarity via text embeddings, fetches content from top URLs, and returns markdown-formatted content.
    @mcp.tool()
    def rag_search_google(query: str, num_results:int=10, top_k:int=5, include_urls:bool=True) -> Dict:
        """
        Search on Google for a given query using ddgs. Give back context to the LLM
        with a RAG-like similarity sort.
    
        Args:
            query (str): The query to search for.
            num_results (int): Number of results to return.
            top_k (int): Use top "k" results for content.
            include_urls (bool): Whether to include URLs in the results.
            If True, the results will be a list of dictionaries with the following keys:
                - type: "text"
                - text: The content of the result
                - url: The URL of the result
            
        Returns:
            Dict of strings containing best search based on input query. Formatted in markdown.
        """
        # Import heavy dependencies only when tool is invoked
        from ddgs import DDGS
        from .utils.fetch import fetch_all_content
        from .utils.tools import sort_by_score
        
        ddgs = DDGS()
        results = ddgs.text(query, max_results=num_results, backend="google") 
        scored_results = sort_by_score(add_score_to_dict(query, results))
        top_results = scored_results[0:top_k]
    
        # fetch content using thread pool
        md_content = fetch_all_content(top_results, include_urls)
    
        # formatted as dict
        return {
            "content": md_content
                }
  • Tool registration via the @mcp.tool() decorator on the rag_search_google function, using FastMCP.
    @mcp.tool()
  • Helper function that embeds the query and each result, computing cosine similarity scores for RAG relevance ranking.
    def add_score_to_dict(query: str, results: List[Dict]) -> List[Dict]:
        """Add similarity scores to search results."""
        # Import heavy dependencies only when needed (slow import!)
        from importlib.resources import files
        from mediapipe.tasks.python import text
        from .utils.fetch import fetch_embedder, get_path_str
        
        path = get_path_str(files('mcp_local_rag.embedder').joinpath('embedder.tflite'))
        embedder = fetch_embedder(path)
        query_embedding = embedder.embed(query)
    
        for i in results:
            i['score'] = text.TextEmbedder.cosine_similarity(
                            embedder.embed(i['body']).embeddings[0],
                            query_embedding.embeddings[0])
    
        return results
  • Utility function that fetches content from result URLs in parallel using a thread pool, returning text content with optional URLs.
    def fetch_all_content(results: List[Dict], include_urls:bool=True) -> List[str]:
        """Fetch content from all URLs using a thread pool."""
        urls = [site['href'] for site in results if site.get('href')]
        
        # parallelize requests
        with ThreadPoolExecutor(max_workers=5) as executor:
            # submit fetch tasks to executor
            future_to_url = {executor.submit(fetch_content, url): url for url in urls}
            
            content_list = []
            for future, url in future_to_url.items():
                try:
                    content = future.result()
                    if content:
                        result = {
                            "type": "text",
                            "text": content,
                        }
                        if include_urls:
                            result["url"] = url
                        content_list.append(result)
                except Exception as e:
                    print(f"Request failed with exception: {e}")
            
        return content_list
  • Utility function that sorts search results by their cosine similarity score in descending order.
    def sort_by_score(results: List[Dict]) -> List[Dict]:
        """Sort results by similarity score."""
        return sorted(results, key=lambda x: x['score'], reverse=True)
Behavior3/5

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

Describes the RAG-like similarity sort and return format, but lacks disclosures on rate limits, authentication, or side effects. With no annotations, the description carries the burden but only partially meets it.

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?

Well-structured with a clear first sentence, followed by Args and Returns sections. Slightly verbose but front-loads the core purpose. Every sentence contributes.

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

Completeness4/5

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

Covers purpose, parameters, and return format adequately. Given no annotations and an output schema mentioned, it is fairly complete. However, could elaborate on the RAG mechanism and provide more context on when to use this tool.

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?

Schema description coverage is 0%, but the description provides explanations for all four parameters in the Args block. Adds meaning beyond the schema, though explanations are brief.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Clearly states it searches Google using ddgs and applies RAG-like similarity sorting. The verb 'search' and resource 'Google' are specific. Differentiates from siblings like 'rag_search_ddgs' which likely searches DuckDuckGo.

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 explicit guidance on when to use this tool versus alternatives like 'rag_search_ddgs' or 'deep_research' variants. Usage context is implied but not clarified with exclusions.

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/nkapila6/mcp-local-rag'

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