How to build a LangChain tool that reads web pages and searches Google

Checked on 2026-11-24.

A LangChain tool is a Python function with type hints and a docstring under the @tool decorator, and an agent from create_agent decides when to call it. Two tools cover most of what an agent needs from the web: one that reads a page as Markdown, and one that runs a search. Here are both, first on free libraries, then on an API, following LangChain's documentation as it reads today.

How a tool is defined today

LangChain's tools page imports the decorator with from langchain.tools import tool. It says type hints "are required as they define the tool's input schema", and that "the function's docstring becomes the tool's description that helps the model understand when to use it". It also asks for snake_case names, because some model providers reject names with spaces or special characters. A tool can return a string or a dictionary; either way the agent wraps it in a ToolMessage for the model.

The agent comes from create_agent in langchain.agents, with a model named as "provider:model". The examples here use "anthropic:claude-sonnet-5", the Anthropic model LangChain's agents page uses, installed with pip install -U "langchain[anthropic]". Another chat model with tool calling can take its place.

A page tool on free libraries

For ordinary pages, requests and trafilatura are enough. trafilatura picks the main content of the page and can write it as Markdown, as its documentation shows; include_links=True keeps the links.

Python
# pip install -U "langchain[anthropic]" requests trafilatura
import requests
from langchain.tools import tool
from trafilatura import extract


@tool
def read_page(url: str) -> str:
    """Read one public web page and return its main content as Markdown.

    Args:
        url: The full address of the page, such as https://docs.apify.com/academy
    """
    res = requests.get(url, timeout=20)
    res.raise_for_status()
    markdown = extract(res.text, output_format="markdown", include_links=True)
    return markdown or "No main text was found on this page."

Where it stops: it runs no JavaScript, so a page that builds its text in the browser gives next to nothing; sites that refuse requests from servers answer with an error page or a 403; and whether a site's robots.txt allows the request is for you to check. The Python guide to pages as Markdown compares trafilatura with html2text and markdownify and shows the browser route.

Search: what is official, and what is free

Search is harder to get for free. Three routes are worth knowing:

  • Your model provider's search tool. LangChain's Anthropic integration passes Anthropic's server-side web search through as a dictionary in tools, next to your own tools. Anthropic runs the searches and charges $10 per 1,000 of them, plus tokens, according to its web search tool page, which does not name the search engine behind it.
  • LangChain's Google Search integration. Its page builds the tool on GoogleSearchAPIWrapper with a GOOGLE_CSE_ID from a Programmable Search Engine, which is Google's Custom Search JSON API. Google's overview now says that API "is closed to new customers", and existing customers have until January 1, 2027.
  • Search APIs with free tiers. LangChain's tool integrations page has a long table of search providers, many with a monthly free allowance, each with its own key and terms.
Python
from langchain.agents import create_agent

web_search = {"type": "web_search_20260209", "name": "web_search", "max_uses": 3}

agent = create_agent(model="anthropic:claude-sonnet-5", tools=[web_search, read_page])

Where it stops: with the provider's tool you get the model's answer with citations, not a list of results your code can store, and Anthropic's page says citations must be shown to end users who see the output.

Both tools on an HTTP API

With Pipefetch each tool is one HTTPS request: page content returns a page as Markdown without its menus, and Google search returns the first page of organic results. A 404 means nothing was found and costs nothing, so the tools turn it into a sentence the model can read.

Python
# pip install -U "langchain[anthropic]" requests
import os

import requests
from langchain.tools import tool


def pipefetch(path: str, params: dict) -> dict | None:
    res = requests.get(
        f"https://pipefetch.com{path}",
        params=params,
        headers={"x-api-key": os.environ["PIPEFETCH_API_KEY"]},
        timeout=90,
    )
    if res.status_code == 404:
        return None  # nothing found: not charged
    res.raise_for_status()
    return res.json()["data"]


@tool
def read_page(url: str) -> str:
    """Read one public web page and return its main content as Markdown, without its menus.

    Args:
        url: The full address of the page, such as https://docs.apify.com/academy
    """
    page = pipefetch("/v1/web/content", {"url": url})
    if page is None:
        return "This page could not be read: it does not exist, robots.txt closes it, or it is built in the browser."
    return f"# {page['title'] or url}\n\n{page['content']}"


@tool
def search_google(query: str, country: str = "US") -> str:
    """Search Google and return the first page of organic results: title, URL and snippet of each.

    Args:
        query: The search as a person would type it, such as best crm software
        country: Two-letter code of the country whose results you want, such as US or DE
    """
    data = pipefetch("/v1/google/search", {"q": query, "country": country})
    if data is None:
        return "Google has no results for this search."
    return "\n\n".join(
        f"{r['position']}. {r['title']}\n{r['url']}\n{r['description'] or ''}"
        for r in data["results"]
    )

Wire them into an agent

LangChain's tools page handles tool errors in middleware: wrap_tool_call catches an exception from a tool and hands the model a ToolMessage it can act on. The middleware below is the page's own example.

Python
from collections.abc import Callable

from langchain.agents import create_agent
from langchain.agents.middleware import wrap_tool_call
from langchain.messages import ToolMessage
from langchain.tools.tool_node import ToolCallRequest


@wrap_tool_call
def handle_tool_errors(
    request: ToolCallRequest,
    handler: Callable[[ToolCallRequest], ToolMessage],
) -> ToolMessage:
    """Convert tool exceptions into ToolMessages the model can handle."""
    try:
        return handler(request)
    except Exception as e:
        return ToolMessage(
            content=f"Tool error: Please check your input and try again. ({e})",
            tool_call_id=request.tool_call["id"],
        )


agent = create_agent(
    model="anthropic:claude-sonnet-5",
    tools=[search_google, read_page],
    system_prompt="Search before you answer anything current. Read a page before you rely on it, and name its address.",
    middleware=[handle_tool_errors],
)

result = agent.invoke(
    {"messages": [{"role": "user", "content": "Compare what the first three Google results for 'best crm software' recommend."}]}
)
print(result["messages"][-1].text)

A refused Google search, which Pipefetch answers with a 502 and does not charge, reaches the model this way as a tool error it can retry.

Where it stops: the page tool does not run JavaScript either. A page built in the browser comes back with needsJavaScript true and the little text its HTML holds, or as a 404 needs_javascript. One request reads one page and follows no links, and robots.txt is respected. A search is the first page of results, about 10, with no further pages and without ads, AI Overview or People also ask. These are not official APIs of the sites read, and Pipefetch is not affiliated with them.

Every endpoint as a tool, through MCP

LangChain can also load tools from an MCP server with MCPAdapter, which its MCP page marks as beta and which needs langchain[mcp] 1.4.0 or newer. Its authentication page passes a token as auth on a FastMCP Client, which sends it as a bearer token. Pipefetch's hosted server accepts the key that way and offers 45 tools, one for every endpoint.

Python
# pip install "langchain[anthropic,mcp]"
import asyncio
import os

from fastmcp.client import Client
from langchain.agents import create_agent
from langchain.mcp import MCPAdapter


async def main():
    client = Client("https://pipefetch.com/mcp", auth=os.environ["PIPEFETCH_API_KEY"])  # sent as a bearer token
    async with MCPAdapter(client) as adapter:
        tools = await adapter.list_tools()
        agent = create_agent("anthropic:claude-sonnet-5", tools)
        result = await agent.ainvoke({"messages": [{"role": "user", "content": "How many followers does @nasa have on Instagram?"}]})
        print(result["messages"][-1].text)


asyncio.run(main())

Each tool call is one request and costs what the endpoint costs. For Claude Code, Cursor and other assistants, the MCP guide has the setup.

Which one should you use?

You needUse
Articles and documentation pages, no budgetThe trafilatura tool
Answers with citations, and your model has a search toolThe provider's search tool
Google's results as text the agent can read and your code can logA search API, such as Pipefetch
Many sources without writing a tool for eachThe MCP server through MCPAdapter

What it costs

Every page and every search is 1 credit, and an agent may make several calls for one question: a search, then two or three pages. Anything that finds nothing costs nothing. A new account has 100 free credits and needs no card, and most requests take 2 to 9 seconds. Long pages are also long tool messages, which the model reads as input tokens; the page endpoint's tokenCount estimates the size before you pass a page on.

Try it with 100 free credits. No card needed. No scraper to build or maintain. Get an API key or read the docs.

Every source

YouTube

Instagram

TikTok

Facebook

Google

Threads

LinkedIn

App stores

Steam

X

Pinterest

Airbnb

Real estate

Keywords

Job boards

Eventbrite

Shopify stores

Public tenders

All guides