FastMCP Tools, Resources and Prompts Explained

The three MCP building blocks compared: what each one does, how to declare it and which to choose for a given job.

Three code windows showing a FastMCP tool, resource and prompt decorator

Key takeaways

  • Tools act, resources inform and prompts guide.
  • Annotations such as readOnlyHint and destructiveHint describe tool behaviour.
  • Resource templates serve many URIs from one function.
  • The Context object adds logging, progress and elicitation.

Every MCP server is assembled from three kinds of component: tools, resources and prompts. Knowing what each one is for makes your server easier for models to use and easier for you to maintain. This guide covers all three in depth, along with the context object that ties them to the rest of the server.

The Three Components at a Glance

ComponentPurposeTypically chosen byDecorator
ToolPerform an action or computationThe model@mcp.tool
ResourceProvide read-only data at a URIThe application@mcp.resource(uri)
PromptSupply a reusable message templateThe user@mcp.prompt

The “chosen by” column reflects the usual pattern in MCP host applications, not a hard rule. What matters is the intent: tools do things, resources are things and prompts say things.

Tools

A tool is a function the model may decide to call while answering a request. Typical tools query a database, call an API, run a calculation or change something in another system.

from fastmcp import FastMCP

mcp = FastMCP("Calculator")


@mcp.tool
def add(a: int, b: int) -> int:
    """Add two integers and return the sum."""
    return a + b

FastMCP turns the signature into a schema and validates incoming arguments before your code runs, so a call with a missing or wrongly typed argument is rejected cleanly.

Naming, tags and metadata

By default the function name becomes the tool name and the docstring becomes its description. Both can be overridden, and tags help you organise large servers:

@mcp.tool(
    name="find_products",
    description="Search the product catalogue with optional category filtering.",
    tags={"catalogue", "search"},
)
def search_products(query: str, category: str | None = None) -> list[dict]:
    ...

Behaviour hints

Annotations tell clients how a tool behaves, which helps them decide when to ask the user for confirmation. Mark read-only tools as such, and flag irreversible ones as destructive:

from mcp.types import ToolAnnotations


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True, idempotentHint=True))
def get_order(order_id: str) -> dict:
    """Look up an order by its ID."""
    ...


@mcp.tool(annotations=ToolAnnotations(destructiveHint=True))
def delete_user(user_id: str) -> dict:
    """Permanently delete a user account."""
    return {"deleted": user_id}

Structured output

Return a dataclass or a Pydantic model and FastMCP generates an output schema, so clients receive typed, structured data rather than loose text:

from dataclasses import dataclass


@dataclass
class Person:
    name: str
    age: int
    email: str


@mcp.tool
def get_user_profile(user_id: str) -> Person:
    """Get a user's profile information."""
    return Person(name="Alice", age=30, email="alice@example.com")

Primitive return values such as an int are wrapped as {"result": ...}. Collections need an item type, for example list[dict].

Async tools and timeouts

Tools may be async, which suits network calls. A timeout stops a tool that takes too long:

@mcp.tool(timeout=30.0)
async def fetch_data(url: str) -> dict:
    """Fetch data with a 30-second timeout."""
    ...

The Context Object

When a tool needs to log progress, read other components or talk back to the client, add a parameter typed as Context. FastMCP injects it automatically and hides it from the schema the model sees.

from fastmcp import Context


@mcp.tool
async def process_items(items: list[str], ctx: Context) -> int:
    """Process a batch of items and report progress."""
    await ctx.info(f"Processing {len(items)} items")
    for i, item in enumerate(items, start=1):
        ...
        await ctx.report_progress(progress=i, total=len(items))
    return len(items)

The context offers several other useful capabilities:

  • Logging with ctx.debug(), ctx.info(), ctx.warning() and ctx.error().
  • Reading resources with await ctx.read_resource("resource://config").
  • Asking the user for missing information with await ctx.elicit("Enter your name:", response_type=str), then checking whether the result’s action is "accept".
  • Request state with ctx.set_state() and ctx.get_state(), scoped to a single request.
  • Request details such as ctx.request_id, ctx.client_id and ctx.transport.

Resources

Resources expose data for reading. Each has a URI, and clients fetch it when the application decides the content is relevant. A static resource has a fixed URI:

@mcp.resource("resource://greeting")
def get_greeting() -> str:
    """Provides a simple greeting message."""
    return "Hello from FastMCP Resources!"

Resource templates

A template contains placeholders that map to function parameters, so one function can serve many URIs:

import json


@mcp.resource("weather://{city}/current")
def get_weather(city: str) -> str:
    """Weather information for a specific city."""
    return json.dumps({"city": city.capitalize(), "temperature": 22, "condition": "Sunny"})

A request for weather://london/current calls get_weather("london"). Templates are ideal for records, files and other collections where listing every item in advance would be impractical.

Good resource design

  • Choose URI schemes that describe the data, such as config://, docs:// or db://.
  • Keep resources free of side effects; reading should never change anything.
  • Return compact content. Large blobs consume the model’s context window quickly.

Prompts

Prompts package instructions you want to reuse. Applications usually present them to the user as commands or menu items, and the returned text becomes a message for the model.

@mcp.prompt
def ask_about_topic(topic: str) -> str:
    """Generate a request for an explanation of a topic."""
    return f"Can you please explain the concept of '{topic}'?"

Optional arguments

Parameters without defaults are required; those with defaults are optional, exactly as in ordinary Python:

@mcp.prompt
def data_analysis_prompt(
    data_uri: str,
    analysis_type: str = "summary",
    include_charts: bool = False,
) -> str:
    """Create a request to analyse data with specific parameters."""
    prompt = f"Please perform a '{analysis_type}' analysis on the data at {data_uri}."
    if include_charts:
        prompt += " Include relevant charts and visualisations."
    return prompt

Multi-message conversations

Return a list of Message objects to seed a short conversation, including assistant turns:

from fastmcp.prompts import Message


@mcp.prompt
def generate_code_request(language: str, task: str) -> list[Message]:
    """Start a conversation that asks for a function."""
    return [
        Message(f"Write a {language} function that does the following: {task}"),
        Message("I'll help you write that function.", role="assistant"),
    ]

Choosing the Right Component

  • Does it change something or compute a result on demand? Make it a tool.
  • Is it data the model should be able to read, addressed by a stable identifier? Make it a resource.
  • Is it a way of phrasing a task that users repeat? Make it a prompt.

Some capabilities fit more than one category. A product catalogue, for instance, could be a resource template for reading individual products and a tool for searching. Offering both is perfectly reasonable.

Design Tips for All Components

  • Keep each component narrow. A tool that does one thing with a precise docstring is chosen more reliably than a broad tool with many optional parameters.
  • Write for the model. Docstrings and parameter descriptions are the model’s only documentation, so state when to use a component and what it returns.
  • Hide server-side values. Values such as the current user ID can be injected with Depends(), which removes them from the schema entirely.
  • Return actionable errors. A message such as “start_date must be before end_date” lets the model correct itself.

Summary

Tools act, resources inform and prompts guide. FastMCP lets you declare all three with a decorator and connects them through the context object, so the decision about which to use is a design question rather than a coding one.

Frequently Asked Questions

Yes. A resource template includes placeholders in its URI, such as weather://{city}/current, and each placeholder maps to a function parameter of the same name.

A resource is read-only data with a stable address, typically chosen by the application. A tool is called by the model on demand and may compute or change something. Search is usually a tool; a specific record is a resource.

Yes. Return a list of Message objects and set role="assistant" on the turns that should come from the assistant, which is useful for seeding a short example conversation.

Inject it on the server with Depends(). Values provided this way, such as the current user's ID, are removed from the tool's schema entirely.

Keep reading

Related Guides