CrewAI Tools: Build a Custom Tool for Live Web Data
CrewAI tools are the functions a CrewAI agent can call: built-in ones from the crewai-tools package, tools loaded from an MCP server, or your own, written by subclassing BaseTool with a name, a description, a Pydantic argument schema and a _run method. This tutorial builds a custom tool that gives an agent live Google results through one API call, caps it at 5 searches per run with max_usage_count, and then shows the MCP route, which loads tools from a server instead of writing them. All the tool code below was tested; the crew itself wasn't run against a model.
What are CrewAI tools?
A CrewAI tool is anything an agent can call to act or fetch information: search the web, read a file, query a database. You give tools to an Agent in its tools list, and during a task the model decides which to call and with which arguments. CrewAI offers three ways to get them: the ready-made tools in the crewai-tools package, tools adapted from an MCP server with MCPServerAdapter, and custom tools you write.
CrewAI's docs describe the custom route as subclassing BaseTool with a Pydantic args_schema, which gives the agent validated inputs and clear error messages (CrewAI: Create custom tools, 2026). Write a custom tool when you want control over what the agent sees. A raw API response can be long; a tool that returns five results with four fields each keeps the agent's context small and its behaviour predictable. It's also where you put limits, error messages written for a model, and the API key, so the key never appears in a prompt.
We used crewai 1.15.30 and crewai-tools 1.15.30 on Python 3.13. CrewAI's API moves quickly, so check the version you install against its docs. If you use LangChain instead, LangChain Custom Tool for Live Web Data builds the same tool there.
How do you build a custom CrewAI tool, step by step?
The tool takes a search query, calls the Google Search endpoint, and returns the top five organic results as compact JSON. It has four parts: an input schema, the tool class, the HTTP call, and error handling the model can read. The five steps below install the packages, write and test the tool, and hand it to an agent in a one-task crew.
Step 1: install CrewAI and set your keys
pip install crewai crewai-tools requests
export PERCEPTLAYER_API_KEY=sk_live_...
CrewAI also needs a model: it reads the model name from the MODEL environment variable and the provider's key from that provider's variable, as its LLM docs describe. Get a Perceptlayer key free at /signup; keys start with sk_live_.
Step 2: write the tool
Save this as web_search_tool.py:
import json
import os
from typing import Type
import requests
from crewai.tools import BaseTool
from pydantic import BaseModel, Field
API = "https://api.perceptlayer.com"
class WebSearchInput(BaseModel):
query: str = Field(..., description="What to search for, as a person would type it into Google.")
gl: str | None = Field(None, description="Optional two-letter country code, such as 'us' or 'de'.")
hl: str | None = Field(None, description="Optional two-letter language code, such as 'en'.")
class WebSearchTool(BaseTool):
name: str = "web_search"
description: str = (
"Search Google and return the top organic results as JSON: position, title, link and snippet. "
"Use it for current facts, recent events and sources you can cite."
)
args_schema: Type[BaseModel] = WebSearchInput
max_usage_count: int | None = 5 # at most 5 searches (5 credits) per run
def _run(self, query: str, gl: str | None = None, hl: str | None = None) -> str:
params = {"query": query}
if gl:
params["gl"] = gl
if hl:
params["hl"] = hl
resp = requests.get(
f"{API}/v1/google-search/search",
params=params,
headers={"X-API-Key": os.environ["PERCEPTLAYER_API_KEY"]},
timeout=90,
)
if resp.status_code != 200:
error = resp.json().get("error", {}) if resp.content else {}
wait = resp.headers.get("Retry-After")
hint = f" Retry after {wait} seconds." if wait else ""
return f"Search failed ({resp.status_code} {error.get('code', 'error')}): {error.get('message', '')}{hint}"
results = [
{k: r.get(k) for k in ("position", "title", "link", "snippet")}
for r in resp.json().get("organic_results", [])[:5]
]
return json.dumps({"query": query, "results": results, "credits_used": resp.headers.get("X-Credits-Used")})
The description and the Field descriptions are the tool's documentation for the model, so write them as instructions. The optional gl and hl map to the endpoint's country and language parameters; the Google Search API page lists the others, such as location and device. The 90-second timeout sits above the 60 seconds after which the API gives up on a slow source with a timeout error.
Step 3: return errors the agent can act on
A failed call returns a short sentence rather than raising, because an exception would end the agent's step while a sentence lets it decide what to do. Every error from the API has an HTTP status and a JSON body with a code and message, and a 429 carries Retry-After. Failed calls cost nothing: they return X-Credits-Used: 0. MCP Tool Call Error Handling covers which errors an agent should retry.
Step 4: test the tool without a model
You can run a tool directly with tool.run(...), which is the fastest way to check it. We ran it with requests.get mocked to return the recorded response for best restaurants in Berlin:
from web_search_tool import WebSearchTool
tool = WebSearchTool()
print(tool.run(query="best restaurants in Berlin", hl="en"))
The output began:
{"query": "best restaurants in Berlin", "results": [{"position": 1, "title": "The Best Restaurants in Berlin - Food Guide & Map", "link": "https://andershusa.com/best-restaurants-berlin-germany-guide/", "snippet": "Dec 3, 2025 — Tim Raue is the most internationally renowned restaurant in Berlin. …"}, …
A mocked 429 returned Search failed (429 rate_limited): Too many requests. Retry after 12 seconds. After five calls, the sixth didn't reach the API at all and returned the usage-limit message. Note that the cap counts attempts, failed ones included, so it's a ceiling on spend rather than an exact count.
Step 5: give the tool to an agent
from crewai import Agent, Crew, Process, Task
from web_search_tool import WebSearchTool
researcher = Agent(
role="Market researcher",
goal="Answer questions with current, sourced facts from the web",
backstory="You check claims against live search results and cite the links you used.",
tools=[WebSearchTool()],
max_iter=6,
verbose=True,
)
task = Task(
description="Find three independent sources on {topic} published this year and summarise what they agree on.",
expected_output="A short summary with a bulleted list of the three source links.",
agent=researcher,
)
crew = Crew(agents=[researcher], tasks=[task], process=Process.sequential)
result = crew.kickoff(inputs={"topic": "heat pump adoption in Germany"})
print(result)
We built this crew to check that it constructs with the tool attached, but didn't run kickoff(), which needs a model key. max_iter limits the agent's reasoning steps; max_usage_count limits the paid tool; you want both.
How do you load tools from an MCP server instead?
Load them with MCPServerAdapter when you want the agent to reach more than one endpoint without writing a tool for each. Perceptlayer's MCP server at https://perceptlayer.com/mcp exposes three tools: search_endpoints and get_endpoint look up the catalogue for free, and call_endpoint runs any of its 3,834 endpoints, spending credits only on success.
import os
from crewai import Agent
from crewai_tools import MCPServerAdapter
server = {
"url": "https://perceptlayer.com/mcp",
"transport": "streamable-http",
"headers": {"Authorization": f"Bearer {os.environ['PERCEPTLAYER_API_KEY']}"},
}
with MCPServerAdapter(server, "search_endpoints", "get_endpoint", "call_endpoint") as tools:
for tool in tools:
if tool.name == "call_endpoint":
tool.max_usage_count = 10 # cap paid calls per run
analyst = Agent(
role="Web data analyst",
goal="Answer questions with data from the right website",
backstory="You find the endpoint for a question before you call it.",
tools=tools,
)
# build the Task and Crew as above, then kickoff() inside this block
Install the extra with pip install 'crewai-tools[mcp]'. CrewAI's MCP docs recommend the context manager, as here, because it opens and closes the server connection for you (CrewAI: MCP servers as tools, 2026). We tested the adapter against a local run of the server's code: it listed the three tools, get_endpoint returned the parameters for google-search.search, and call_endpoint with an invalid key returned Error invalid_api_key: Missing, unknown or revoked API key. without charging anything. One finding from that test: the adapter sent vertical: null to search_endpoints when it wasn't set, and the server rejected the null, so for now tell the agent to pass a vertical (such as search or real-estate) or rely on get_endpoint with an endpoint ID you name in the task.
The trade-off is reach versus control. The custom tool returns exactly the five fields you chose; call_endpoint returns the endpoint's full JSON, up to 100,000 characters, which costs more context. Trim API Responses for LLM Context covers keeping that down, and MCP vs Function Calling for Live Web Data compares the two approaches.
What does a crew run cost?
Each successful search costs 1 credit, and with max_usage_count = 5 a run can't make more than 5 paid calls. So the bill has a ceiling you can compute before you schedule anything: runs × cap. The lookups an MCP agent makes with search_endpoints and get_endpoint add nothing, because they're free.
| Schedule | Worst case | Credits a month |
|---|---|---|
| 10 runs a day, cap 5 | 10 × 5 × 30 | 1,500 |
| 100 runs a day, cap 5 | 100 × 5 × 30 | 15,000, within the Build pack's 50,000 |
| 100 runs a day, cap 3 | 100 × 3 × 30 | 9,000, within the Starter pack's 10,000 |
Real runs usually stop before the cap. Every account gets 100 free credits once, after verifying an email address, enough for 20 runs at cap 5; a recurring schedule needs a pack. See pricing for what credits cost and Scheduled AI Agent Runs: Budgeting Credits per Run for budgeting recurring crews. Requests share the account's rate limit, 1 a second on a free account, so a crew with several agents searching at once may see 429s; the tool passes the wait back to the agent.
Start with the custom tool and one agent, run it with verbose=True to watch which queries it sends, then tighten the description and the cap. To see the data the tool returns before you write any code, run a search in the playground on the Google Search API page.
APIs in this post
Frequently asked questions
What is the difference between crewai and crewai-tools?
crewai is the framework: agents, tasks, crews and the BaseTool class. crewai-tools is a separate package of ready-made tools plus adapters such as MCPServerAdapter. A custom tool needs only crewai; loading MCP tools needs crewai-tools with its mcp extra.
How do I limit how often an agent calls a tool?
Set max_usage_count on the tool, as in max_usage_count: int | None = 5. Once it's reached, the tool returns a usage-limit message instead of running, and the agent has to answer with what it has. Combine it with the agent's max_iter to bound the whole run. The count includes failed attempts.
Should a CrewAI tool raise exceptions or return error text?
Return text for errors the agent can act on, such as a rate limit with the seconds to wait, a not-found result or invalid parameters. The model reads the message and adjusts. Raise only for problems no retry will fix, such as a missing API key in the environment, so the run stops early and visibly.
Can a CrewAI agent use several Perceptlayer endpoints?
Yes. Either write one custom tool per endpoint you need, which keeps each tool's output small, or load the MCP server's three tools so the agent can find and call any endpoint in the catalogue. Every endpoint call costs its listed credits, 1 for nearly all, and only on success.
Does the custom tool work with async crews?
The tool above implements the synchronous _run; CrewAI's docs show an _arun method for non-blocking I/O if you need one. For many parallel searches, keep the per-account rate limit in mind: a free account allows 1 request a second and a paying one at least 5. The rate limits docs list the rates per pack.