Skip to main content
Glama

google_search

Execute Google searches to retrieve web content, news, or data in text, JSON, HTML, or markdown formats for research and information gathering.

Instructions

Execute a Google search and return results in various formats

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesThe search query to execute
responseTypeNoExpected response typejson
maxResultsNoMaximum number of results to return
topicNoType of search to performweb

Implementation Reference

  • The core handler function for the 'google_search' tool. It constructs the search URL, fetches initial search results, extracts URLs, fetches content from those URLs, formats the output according to the specified responseType (json, markdown, html, text), and returns structured content with metadata.
    async (params) => {
      try {
        // First, get the search results
        const searchUrl = buildGoogleSearchUrl({
          query: params.query,
          maxResults: params.maxResults,
          topic: params.topic
        });
    
        // Get search results in JSON format to extract URLs
        const searchResults = await fetchUrl(searchUrl, 'json');
        const urls = await extractSearchUrls(searchResults);
    
        // Now fetch the full content of each URL
        const fullResults = await Promise.all(
          urls.map(async (url) => {
            try {
              const content = await fetchUrl(url, params.responseType);
              return {
                url,
                content,
                error: null
              };
            } catch (error) {
              return {
                url,
                content: null,
                error: error instanceof Error ? error.message : 'Unknown error'
              };
            }
          })
        );
    
        // Format the results based on response type
        let formattedResults;
        switch (params.responseType) {
          case 'markdown':
            formattedResults = fullResults
              .map(r => r.error
                ? `## [Failed to fetch: ${r.url}]\nError: ${r.error}`
                : `## [${r.url}]\n\n${r.content}`)
              .join('\n\n---\n\n');
            break;
          case 'html':
            formattedResults = fullResults
              .map(r => r.error
                ? `<div class="search-result error"><h2><a href="${r.url}">Failed to fetch</a></h2><p class="error">${r.error}</p></div>`
                : `<div class="search-result"><h2><a href="${r.url}">${r.url}</a></h2>${r.content}</div>`)
              .join('\n');
            break;
          case 'text':
            formattedResults = fullResults
              .map(r => r.error
                ? `### ${r.url}\nError: ${r.error}`
                : `### ${r.url}\n\n${r.content}`)
              .join('\n\n==========\n\n');
            break;
          case 'json':
          default:
            formattedResults = JSON.stringify(fullResults, null, 2);
            break;
        }
    
        return {
          content: [{
            type: "text",
            text: formattedResults,
            mimeType: params.responseType === 'json' ? 'application/json' :
              params.responseType === 'markdown' ? 'text/markdown' :
                params.responseType === 'html' ? 'text/html' : 'text/plain'
          }],
          metadata: {
            query: params.query,
            topic: params.topic,
            maxResults: params.maxResults,
            responseType: params.responseType,
            resultsCount: fullResults.length,
            successCount: fullResults.filter(r => !r.error).length
          }
        };
      } catch (error) {
        return {
          content: [{
            type: "text",
            text: `Failed to execute Google search: ${error instanceof Error ? error.message : 'Unknown error'}`
          }],
          isError: true
        };
      }
    }
  • Zod schema defining the input parameters for the google_search tool: query (required string), responseType (enum with default 'json'), maxResults (number 1-100 default 10), topic (web/news default web).
    const GoogleSearchSchema = z.object({
      query: z.string()
        .min(1)
        .describe("The search query to execute"),
      responseType: z.enum(['text', 'json', 'html', 'markdown'])
        .default('json')
        .describe("Expected response type"),
      maxResults: z.number()
        .min(1)
        .max(100)
        .default(10)
        .describe("Maximum number of results to return"),
      topic: z.enum(['web', 'news'])
        .default('web')
        .describe("Type of search to perform")
    });
  • The registration function that adds the 'google_search' tool to the MCP server using server.tool(), specifying name, description, schema, and handler.
    export function registerGoogleSearchTool(server: McpServer) {
      server.tool(
        "google_search",
        "Execute a Google search and return results in various formats",
        GoogleSearchSchema.shape,
        async (params) => {
          try {
            // First, get the search results
            const searchUrl = buildGoogleSearchUrl({
              query: params.query,
              maxResults: params.maxResults,
              topic: params.topic
            });
    
            // Get search results in JSON format to extract URLs
            const searchResults = await fetchUrl(searchUrl, 'json');
            const urls = await extractSearchUrls(searchResults);
    
            // Now fetch the full content of each URL
            const fullResults = await Promise.all(
              urls.map(async (url) => {
                try {
                  const content = await fetchUrl(url, params.responseType);
                  return {
                    url,
                    content,
                    error: null
                  };
                } catch (error) {
                  return {
                    url,
                    content: null,
                    error: error instanceof Error ? error.message : 'Unknown error'
                  };
                }
              })
            );
    
            // Format the results based on response type
            let formattedResults;
            switch (params.responseType) {
              case 'markdown':
                formattedResults = fullResults
                  .map(r => r.error
                    ? `## [Failed to fetch: ${r.url}]\nError: ${r.error}`
                    : `## [${r.url}]\n\n${r.content}`)
                  .join('\n\n---\n\n');
                break;
              case 'html':
                formattedResults = fullResults
                  .map(r => r.error
                    ? `<div class="search-result error"><h2><a href="${r.url}">Failed to fetch</a></h2><p class="error">${r.error}</p></div>`
                    : `<div class="search-result"><h2><a href="${r.url}">${r.url}</a></h2>${r.content}</div>`)
                  .join('\n');
                break;
              case 'text':
                formattedResults = fullResults
                  .map(r => r.error
                    ? `### ${r.url}\nError: ${r.error}`
                    : `### ${r.url}\n\n${r.content}`)
                  .join('\n\n==========\n\n');
                break;
              case 'json':
              default:
                formattedResults = JSON.stringify(fullResults, null, 2);
                break;
            }
    
            return {
              content: [{
                type: "text",
                text: formattedResults,
                mimeType: params.responseType === 'json' ? 'application/json' :
                  params.responseType === 'markdown' ? 'text/markdown' :
                    params.responseType === 'html' ? 'text/html' : 'text/plain'
              }],
              metadata: {
                query: params.query,
                topic: params.topic,
                maxResults: params.maxResults,
                responseType: params.responseType,
                resultsCount: fullResults.length,
                successCount: fullResults.filter(r => !r.error).length
              }
            };
          } catch (error) {
            return {
              content: [{
                type: "text",
                text: `Failed to execute Google search: ${error instanceof Error ? error.message : 'Unknown error'}`
              }],
              isError: true
            };
          }
        }
      );
    }
  • Helper function to construct the Google search URL with query, num results, and topic-specific parameters (tbm=nws for news, udm=14 for web).
    /**
     * Build a Google search URL with proper parameters
     */
    function buildGoogleSearchUrl(options: {
      query: string;
      maxResults?: number;
      topic?: 'web' | 'news';
    }): string {
      const searchParams = new URLSearchParams({
        q: options.query,
        num: `${options.maxResults || 10}`
      });
    
      if (options.topic === 'news') {
        // News tab
        searchParams.set("tbm", "nws");
      } else {
        // Web tab
        searchParams.set("udm", "14");
      }
    
      return `https://www.google.com/search?${searchParams.toString()}`;
    }
  • Helper function to extract list of URLs from either markdown or JSON formatted search results.
    /**
     * Extract URLs from search results
     */
    async function extractSearchUrls(searchResults: string | object[]): Promise<string[]> {
      if (typeof searchResults === 'string') {
        // Parse markdown links
        const urlMatches = searchResults.matchAll(/\[.*?\]\((.*?)\)/g);
        return Array.from(urlMatches).map(match => match[1]);
      } else {
        // Extract URLs from JSON results
        return (searchResults as any[]).map(result => result.url);
      }
    }
Behavior2/5

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

With no annotations provided, the description carries full burden but only mentions the action and output formats. It fails to disclose critical behavioral traits such as rate limits, authentication needs, network dependencies, or error handling. The description is minimal and doesn't compensate for the lack of annotations.

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 a single, efficient sentence that front-loads the core action and outcome with zero waste. Every word earns its place, making it highly concise and well-structured for quick understanding.

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's complexity (search with multiple parameters) and lack of annotations and output schema, the description is incomplete. It doesn't explain result formats, error cases, or operational constraints, leaving significant gaps for an AI agent to use the tool effectively.

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?

Schema description coverage is 100%, so the schema fully documents all parameters. The description adds no additional meaning beyond what's in the schema, such as explaining the impact of 'responseType' choices or 'topic' differences. Baseline 3 is appropriate as the schema does the heavy lifting.

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 verb ('execute') and resource ('Google search') with the outcome ('return results in various formats'). It distinguishes from the sibling 'fetch_url' by focusing on search rather than URL retrieval. However, it doesn't specify what 'various formats' means beyond the schema's enum values, keeping it from 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 like 'fetch_url' or other search methods. It lacks context about use cases, prerequisites, or exclusions, leaving the agent to infer usage from the tool name alone.

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/TheSethRose/Fetch-Browser'

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