Lesson 3 of 5 · CrewAI
Tools in CrewAI
Give CrewAI agents tools: the @tool decorator, BaseTool classes with Pydantic schemas, crewai-tools and MCP servers, plus caching, usage limits and results.
- 7 min read
- Intermediate
- Reviewed
- Write a CrewAI tool with the @tool decorator
- Write a tool class with BaseTool and a Pydantic argument schema
- Use ready-made tools from crewai-tools and tools from MCP servers
- Control caching with cache_function, and limit how often a tool is used
Agents that can look things up
Without tools, an agent can only use what the model knows. With tools, it can check stock, search the web, read files or call your systems. In CrewAI, tools belong to agents: each agent gets the tools its role needs. (The Tool Calling course explains how models request tools in general.)
Two ways to write a tool
from pydantic import BaseModel, Field
from crewai import LLM, Agent, Crew, Task
from crewai.tools import BaseTool, tool
llm = LLM(model="anthropic/MODEL_NAME")
@tool("Bike stock lookup")
def bike_stock(model_name: str, city: str) -> str:
"""Check how many units of a bike model are in stock at the shop in a city."""
stock = {("volta city 3", "lisbon"): 4, ("volta city 3", "porto"): 0}
return f"{stock.get((model_name.lower(), city.lower()), 0)} in stock"
class DeliveryInput(BaseModel):
city: str = Field(description="Destination city")
weight_kg: float = Field(description="Bike weight in kilograms")
class DeliveryQuote(BaseTool):
name: str = "Delivery quote"
description: str = "Quote the price to deliver a bike to a city in Portugal or Spain."
args_schema: type[BaseModel] = DeliveryInput
def _run(self, city: str, weight_kg: float) -> str:
price = (0 if city.lower() in {"lisbon", "porto"} else 25) + max(0, weight_kg - 20) * 2
return f"{price:.2f} EUR"
assistant = Agent(
role="Shop assistant",
goal="Give customers accurate answers about stock and delivery",
backstory="You work at Velamuvi Bikes. You always check the tools instead of guessing.",
tools=[bike_stock, DeliveryQuote()],
llm=llm,
)
task = Task(
description="A customer in Porto wants a Volta City 3 (24 kg). Check stock in Porto and Lisbon "
"and the delivery price to Porto, then answer them.",
expected_output="A short, friendly answer with the stock situation and the delivery price.",
agent=assistant,
)
print(Crew(agents=[assistant], tasks=[task]).kickoff().raw)The Volta City 3 is out of stock in Porto, but our Lisbon shop has 4. We can deliver one to you in Porto for 8.00 EUR.
@tool("Bike stock lookup")turns a function into a tool. The string is the tool's name; the docstring is its description; type hints define its arguments.BaseToolsubclasses suit tools with settings or more complex arguments.args_schemais a Pydantic model, so every argument can have a description, and_rundoes the work.
In this run, the agent checked Porto (none in stock), then Lisbon (4), then asked for a delivery quote to Porto (8.00 EUR for a 24 kg bike), and only then answered. That's the point of the backstory line “You always check the tools instead of guessing”, combined with tools whose descriptions say exactly what they do.
Ready-made tools and MCP
The separate crewai-tools package (pip install "crewai[tools]") contains over a hundred ready-made tools, for example:
SerperDevToolandTavilySearchTool: web search (with an API key from those services).ScrapeWebsiteToolandWebsiteSearchTool: read or search web pages.FileReadTool,DirectoryReadTool,PDFSearchTool: read and search local files.
Agents can also use tools from MCP servers (see the Model Context Protocol course), either through the agent's mcps setting or the MCPServerAdapter in crewai-tools, so a crew can use the same tools as your other AI applications.
Caching and limits
CrewAI caches tool results by default: if an agent calls the same tool with the same arguments again during a crew run, it gets the saved result instead of running the tool again. A tool's cache_function decides which results are worth keeping:
# How CrewAI caches tool results, in plain Python: the same tool with the same arguments
# returns the saved result instead of running again. A cache_function decides what to keep.
calls = 0
def bike_stock(model_name, city):
global calls
calls += 1
if city == "Faro":
return "error: Faro shop system offline"
return {"Lisbon": "4 in stock", "Porto": "0 in stock"}.get(city, "0 in stock")
def cache_function(args, result): # don't keep errors: try again next time
return not result.startswith("error")
cache = {}
def use_tool(name, fn, **args):
key = (name, tuple(sorted(args.items())))
if key in cache:
return cache[key] + " (from cache)"
result = fn(**args)
if cache_function(args, result):
cache[key] = result
return result
for city in ["Lisbon", "Porto", "Lisbon", "Faro", "Faro"]:
print(f"{city:<7} {use_tool('bike_stock', bike_stock, model_name='Volta City 3', city=city)}")
print("The tool actually ran", calls, "times for 5 requests")The repeated Lisbon lookup came from the cache, and the errors from Faro weren't cached, so the next request tried again. Other tool settings:
max_usage_count: the most times the tool may be used, a guard against agents that call a costly tool over and over.result_as_answer=True: the tool's result becomes the task's final answer, unchanged by the model. Useful when the tool already produces exactly what you want, such as a generated report.
Common mistakes
Write a cache_function for a CrewAI tool, so failed or empty results are never reused from the cache.
results = [({"city": "Lisbon"}, "4 in stock"), ({"city": "Faro"}, "error: timeout"),
({"city": "Porto"}, ""), ({"city": "Braga"}, "0 in stock")]
def cache_function(args, result):
# Return True only if the result is worth caching: it must not be empty
# and must not start with "error".
pass
for args, result in results:
print(args["city"], cache_function(args, result))
What does a CrewAI tool's cache_function decide?
Summary
- Tools belong to agents; give each agent only what its role needs.
- Write tools with
@tool("Name")(docstring and type hints) orBaseToolwith a Pydanticargs_schemaand_run. crewai-toolsoffers ready-made search, scraping and file tools; agents can also use MCP servers.- Tool results are cached by default;
cache_function,max_usage_countandresult_as_answercontrol behaviour.
Next: processes, from sequential to hierarchical, and Flows.
Finished reading? Tick it off to track your progress.