Use case

Google Search API for AI agents

An agent works better with a narrow search tool than with direct access to a browser or a secret. gsearch.dev provides a stable JSON contract that your server can expose as one controlled tool.

Keep the tool contract narrow

Let the agent choose a query, country, language, and page. Keep authentication, credit rules, retry logic, and request logging in your application.

Return only the public response fields the agent needs. A small contract is easier to validate and reduces accidental calls with unsupported input.

Example tool definition · javascript

const googleSearchTool = {
  name: "search_google",
  description: "Find current public web pages with Google text search.",
  inputSchema: {
    type: "object",
    additionalProperties: false,
    required: ["q"],
    properties: {
      q: { type: "string", minLength: 1 },
      gl: { type: "string", default: "us" },
      hl: { type: "string", default: "en" },
      page: { type: "integer", minimum: 1, maximum: 10, default: 1 }
    }
  }
};

Call the API from your server

Resolve the tool call inside trusted server code. Read the key from an environment secret, set a deadline, and reject a response that does not match the expected shape.

The organic array is already ordered. Preserve that order unless your product has a clear, tested reason to rank the results again.

Tool handler · javascript

async function runGoogleSearch(input) {
  const apiKey = process.env.GSEARCH_API_KEY;
  if (!apiKey) throw new Error("GSEARCH_API_KEY is not set");

  const response = await fetch("https://gsearch.dev/api/v1/search", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-API-Key": apiKey
    },
    body: JSON.stringify(input),
    signal: AbortSignal.timeout(10_000)
  });

  const body = await response.json().catch(() => null);
  if (!response.ok) {
    throw new Error([
      body?.error?.code ?? "SEARCH_FAILED",
      body?.error?.message ?? "Search request failed",
      body?.error?.requestId ?? "no request ID"
    ].join(" "));
  }
  if (!body || !Array.isArray(body.organic)) {
    throw new Error("Search API returned an invalid JSON response");
  }
  return body.organic;
}

Set useful limits around the agent

Limit searches per task and stop repeated versions of the same query. A result snippet is a search summary, not proof that every claim on the linked page is correct.

For answers that need sources, keep the result URLs and show them to the user. Fetch and check the source page separately when the full text matters.

  • Allow only the supported country, language, and page values.
  • Cap tool calls per task and respect HTTP 429 responses.
  • Keep source URLs beside any extracted claim.
  • Do not send private user data as a search query unless your product has a valid reason and clear user approval.

Next steps