Getting Started
Relevant source files
The following files were used as context for generating this wiki page:
This guide provides a comprehensive overview of setting up a development environment and creating a basic Model Context Protocol (MCP) server using the FastMCP framework. It covers the fundamental concepts of defining tools and resources, running the server, and testing its functionality. The information is based on the quickstart examples and integration tests within the repository.
The FastMCP class is the central component for building an MCP server. It provides decorators to easily define tools and resources, and methods to expose the server over different transport protocols like Server-Sent Events (SSE) or Streamable HTTP.
Development Setup
Before creating a server, you must set up your development environment. The project uses uv for package management and requires Python 3.10 or higher.
Sources: CONTRIBUTING.md:7-8
Initial Setup Commands
| Command | Description |
|---|---|
git clone <your-fork-url> | Clone your forked repository. |
uv sync --frozen --all-extras --dev | Install all project dependencies, including development and extra packages, using the locked versions. |
uv tool install pre-commit --with pre-commit-uv ... | Set up pre-commit hooks to automatically run formatters and linters before each commit. |
Sources: CONTRIBUTING.md:10-18
Development Workflow Tools
The project enforces code quality through a set of tools. These should be run during development to ensure contributions meet the required standards.
| Command | Description |
|---|---|
uv run pytest | Run the test suite using pytest. |
uv run pyright | Perform static type checking. |
uv run ruff check . | Lint the codebase for style and errors. |
uv run ruff format . | Automatically format the code. |
Sources: CONTRIBUTING.md:29-40, CLAUDE.md:39-50
Creating a FastMCP Server
The FastMCP class is the primary entry point for creating an MCP server. It manages tools, resources, and server configuration.
Sources: tests/server/fastmcp/test_server.py:17
Basic Server Initialization
A server is created by instantiating the FastMCP class. You can provide metadata like a name and instructions.
# examples/snippets/servers/fastmcp_quickstart.py:10-11
from mcp.server.fastmcp import FastMCP
mcp = FastMCP(name="Demo")
Sources: examples/snippets/servers/fastmcp_quickstart.py:10-11
The diagram below illustrates the core components of the FastMCP class and its relationship with its managers.
This diagram shows that FastMCP utilizes a ToolManager and a ResourceManager to handle the registration and execution of tools and resources.
Sources: tests/server/fastmcp/test_server.py:151, tests/server/fastmcp/test_server.py:656, tests/server/fastmcp/test_tool_manager.py, tests/server/fastmcp/resources/test_resource_manager.py
Defining Tools
Tools are functions that a client can execute. They are defined using the @mcp.tool() decorator. The function's signature, including type hints and docstrings, is used to automatically generate the tool's schema and description.
# examples/snippets/servers/fastmcp_quickstart.py:14-17
@mcp.tool()
def add(a: int, b: int) -> int:
"""Adds two numbers together"""
return a + b
Sources: examples/snippets/servers/fastmcp_quickstart.py:14-17
- The decorator
@mcp.tool()registers theaddfunction as a tool. - Type hints (
a: int,b: int,-> int) define the input and output schema. - The docstring becomes the tool's description.
Sources: tests/server/fastmcp/test_server.py:150-155
Defining Resources
Resources represent data that a client can read. They are defined using the @mcp.resource() decorator, which takes a URI template as an argument.
# examples/snippets/servers/fastmcp_quickstart.py:20-23
@mcp.resource("greeting://{name}")
def greeting(name: str) -> str:
"""Returns a personalized greeting"""
return f"Hello, {name}!"
Sources: examples/snippets/servers/fastmcp_quickstart.py:20-23
- The decorator
@mcp.resource("greeting://{name}")registers a resource template. - Placeholders in the URI template (e.g.,
{name}) must match the function's parameter names. - When a client requests a specific URI like
greeting://Alice, the framework matches it to the template, extracts the parameters, and calls the function.
Sources: tests/server/fastmcp/test_server.py:702-710
Running the Server
Once tools and resources are defined, the FastMCP instance can generate a runnable web application. The framework supports multiple transport protocols.
Transport Options
mcp.sse_app(): Creates a Starlette application that communicates over Server-Sent Events (SSE).mcp.streamable_http_app(): Creates an application for the Streamable HTTP transport.
Sources: tests/server/fastmcp/test_integration.py:126-129, tests/server/fastmcp/test_server.py:990-993
The following flowchart shows the server startup process.
This diagram illustrates the sequence from script execution to a running server ready to accept client connections.
Sources: examples/snippets/servers/fastmcp_quickstart.py
Testing the Server
Integration tests validate the server's functionality by simulating a client. The mcp.client.session.ClientSession is used to interact with the server.
Client-Server Interaction Flow
The following sequence diagram shows a typical client interaction to call a tool.
This diagram shows the client initializing a session, discovering the add tool, and then calling it with parameters.
Sources: tests/server/fastmcp/test_integration.py:618-632
Example Test Case
The integration tests demonstrate how to connect to a running server, initialize a session, and call its features.
-
Create a client: A transport-specific client is created, pointing to the server's URL.
# tests/server/fastmcp/test_integration.py:183-189 def create_client_for_transport(transport: str, server_url: str): """Create the appropriate client context manager based on transport type.""" if transport == "sse": endpoint = f"{server_url}/sse" return sse_client(endpoint) ... -
Establish a session: The
ClientSessioncontext manager handles the connection.# tests/server/fastmcp/test_integration.py:622-623 async with client_cm as client_streams: read_stream, write_stream = unpack_streams(client_streams) async with ClientSession(read_stream, write_stream) as session: ... -
Interact with the server: Use
sessionmethods likecall_toolandread_resource.# tests/server/fastmcp/test_integration.py:629-632 # Test add tool tool_result = await session.call_tool("add", {"a": 10, "b": 20}) assert len(tool_result.content) == 1 assert isinstance(tool_result.content[0], TextContent) assert tool_result.content[0].text == "30"Sources: tests/server/fastmcp/test_integration.py:629-632
# tests/server/fastmcp/test_integration.py:635-638 # Test greeting resource directly from pydantic import AnyUrl resource_result = await session.read_resource(AnyUrl("greeting://Alice")) assert resource_result.contents[0].text == "Hello, Alice!"
Summary
This guide has walked through the essential steps to get started with the Python SDK for MCP. By following these steps, a developer can set up their environment, define a FastMCP server with custom tools and resources, and run it using a supported transport. The testing framework provides a clear pattern for building clients to interact with and validate the server's behavior.