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.
# 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
GoogleSearchAPIWrapperwith aGOOGLE_CSE_IDfrom 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.
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.
# 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.
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.
# 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 need | Use |
|---|---|
| Articles and documentation pages, no budget | The trafilatura tool |
| Answers with citations, and your model has a search tool | The provider's search tool |
| Google's results as text the agent can read and your code can log | A search API, such as Pipefetch |
| Many sources without writing a tool for each | The 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.
APIs used in this guide
-
1 credit
Google Search API
The first page of Google results for a search: rank, title, link, domain, snippet and date of each result, plus related searches.
GET /v1/google/search -
1 credit
Web Page to Markdown API
The content of one web page as Markdown or text, without its menus, with title, headings and word and token counts.
GET /v1/web/content
More Websites guides
- Clearbit Logo API alternatives: get a company logo from its domain
- How to extract email addresses from a website in Python
- How to turn a web page into Markdown in Python
- How to detect what a website is built with, in Python
- How to get the contact emails and phone numbers of websites in Google Sheets
- How to turn a web page into Markdown in JavaScript for RAG
- How to extract social media links from a website in Python
- How to get a website's favicon in Python
- How to check robots.txt in Python before you fetch a page
Guides for other sources
Every source
YouTube
- How to get a YouTube transcript in Python
- How to get a YouTube transcript in Node.js
- YouTube API quota exceeded: what the error means and how to fix it
- How to find a YouTube channel ID from a handle or URL
- How to download YouTube subtitles as SRT or VTT
- youtube-transcript-api RequestBlocked or IpBlocked: why it happens and how to fix it
- How to get YouTube comments in Python
- How to search YouTube from Python
- How to list a YouTube channel's videos in Python
- How to summarize a YouTube video with an LLM in Python
- How to get YouTube transcripts and video stats in Google Sheets
- How to get YouTube video views and likes in Python
- How to get YouTube transcripts in n8n, Make and Zapier
- LangChain YoutubeLoader fails on a server: why, and a loader that works
- How to get a YouTube channel's subscriber count in Python
- How to give Claude or Cursor access to YouTube (MCP server)
- How to get YouTube comments in Node.js
- How to analyze YouTube comments with an LLM in Python
- How to list a YouTube channel's Shorts in Python
- How to search YouTube from JavaScript
- How to get an Instagram follower count in Python
- Instagram Basic Display API alternatives: what to use after the shutdown
- Instaloader 401 Unauthorized, 429 and "Login required": what to do
- How to calculate an Instagram engagement rate in Python
- How to get an Instagram follower count in Node.js
- How to get Instagram follower counts in Google Sheets
- How to get Instagram Reel views in Python
TikTok
- How to get a TikTok video's views and likes in Python
- How to get the comments of a TikTok video in Python
- How to get a TikTok follower count in Python
- TikTok Research API: who can get access, and what to do if you cannot
- How to get TikTok video views, likes and shares in Node.js
- How to get TikTok views, likes and follower counts in Google Sheets
- How to get a Facebook Page's posts without app review
- Is there a Facebook Marketplace API?
- Facebook Groups API alternatives after its removal in 2024
- How to get a Facebook Page's follower count and contact details in Python
- How to get Google search results in Python
- pytrends 429 TooManyRequestsError: what it means and what to do
- How to get Google Trends data in Python
- Why is Wyoming first in Google Trends?
- How to get Google search results in Node.js
- How to get Google search results into Google Sheets
- How to give an LLM live Google results with tool calling
Threads
- How to get LinkedIn company data in Python
- How to search LinkedIn jobs from Python
- How to get a LinkedIn company page's latest posts in Python