Core Concepts
Relevant source files
The following files were used as context for generating this wiki page:- tests/server/fastmcp/test_server.py
- tests/server/fastmcp/test_integration.py
- tests/server/fastmcp/auth/test_auth_integration.py
- tests/server/fastmcp/test_tool_manager.py
- tests/server/fastmcp/resources/test_function_resources.py
- examples/servers/simple-auth/README.md
- tests/server/auth/middleware/test_bearer_auth.py
- tests/server/fastmcp/test_title.py
The python-sdk provides a framework for building servers that adhere to the Model Context Protocol (MCP). The core of this framework is the FastMCP class, which acts as the main entry point for creating and configuring an MCP server. It manages key features such as Tools, Resources, and Prompts, and integrates with communication transports and authentication mechanisms.
This document outlines the fundamental concepts and components of the SDK, including the server architecture, feature definitions, communication protocols, and authentication flows. The examples and explanations are derived from the project's test suite and example code, providing a practical overview of how to use the SDK to build robust MCP servers.
Server Architecture
The FastMCP server is built on top of the Starlette ASGI framework. It exposes MCP functionality over different communication transports, primarily Server-Sent Events (SSE) and a custom StreamableHTTP protocol. The server manages collections of Tools, Resources, and Prompts, which are the primary capabilities exposed to clients.
Sources: tests/server/fastmcp/test_server.py, tests/server/fastmcp/test_integration.py
Key Components
| Component | Description | Source Files |
|---|---|---|
FastMCP | The main server class that orchestrates all other components. | tests/server/fastmcp/test_server.py |
ToolManager | Manages the registration and execution of server-side functions (Tools). | tests/server/fastmcp/test_tool_manager.py |
ResourceManager | Manages static and dynamic data sources (Resources). | tests/server/fastmcp/test_server.py |
PromptManager | Manages server-side message templates (Prompts). | tests/server/fastmcp/test_server.py |
| Transports | Communication layers (e.g., SSE, StreamableHTTP) that connect clients to the server. | tests/server/fastmcp/test_integration.py |
| Authentication | Handles client authentication, typically via OAuth 2.0 Bearer Tokens. | tests/server/fastmcp/auth/test_auth_integration.py |
High-Level Architecture Diagram
The following diagram illustrates the high-level architecture of a FastMCP server and its interaction with a client.
This diagram shows a client connecting to the server via a transport layer. Requests are processed by authentication middleware before reaching the FastMCP instance, which delegates tasks to the appropriate manager.
Sources: tests/server/fastmcp/test_integration.py, tests/server/fastmcp/test_server.py, tests/server/auth/middleware/test_bearer_auth.py
Tools
Tools are Python functions exposed by the server that can be executed by a client. They are the primary mechanism for providing interactive capabilities.
Sources: tests/server/fastmcp/test_server.py, tests/server/fastmcp/test_tool_manager.py
Defining Tools
Tools are defined by decorating a Python function with @mcp.tool(). The decorator inspects the function's signature, docstring, and type hints to generate the tool's schema.
# tests/server/fastmcp/test_server.py:155-160
mcp = FastMCP()
@mcp.tool()
def sum(x: int, y: int) -> int:
return x + y
The SDK supports various function signatures, including those with Pydantic models, default arguments, and context injection.
Sources: tests/server/fastmcp/test_server.py:155-160, tests/server/fastmcp/test_tool_manager.py:100-108
Tool Execution Flow
This diagram shows the sequence of events when a client calls a tool.
The ToolManager validates arguments against the tool's schema, executes the function, and converts the return value into the appropriate MCP ContentBlock format.
Sources: tests/server/fastmcp/test_tool_manager.py:204-212, tests/server/fastmcp/test_server.py:382-399
Content and Structured Output
Tools can return various types of data, which are converted into different ContentBlock types:
- Primitives (int, str, etc.): Converted to
TextContent. Image/Audiohelpers: Converted toImageContent/AudioContentwith Base64-encoded data.- Pydantic Models / Dataclasses: The return value is provided as a JSON object in the
structuredContentfield of the result, while a JSON string representation is placed inTextContent. - Lists / Dictionaries: Handled as either
TextContent(JSON string) or structured data, depending on the return type hint.
Sources: tests/server/fastmcp/test_server.py:280-496, tests/server/fastmcp/test_tool_manager.py:463-631
Display Titles
Tools can be given a user-friendly title that is used for display purposes in clients. The display name is resolved with the following precedence: title parameter > annotations.title > function name.
# tests/server/fastmcp/test_title.py:19-22
# Tool with title
@mcp.tool(description="Tool with title", title="User-Friendly Tool")
def tool_with_title(message: str) -> str:
return message
Sources: tests/server/fastmcp/test_title.py:9-70
Resources
Resources represent data that a client can read from the server. They are identified by a URI and can be static or dynamically generated.
Sources: tests/server/fastmcp/test_server.py, tests/server/fastmcp/resources/test_function_resources.py
Defining Resources
Resources can be created from functions using the @mcp.resource() decorator or instantiated directly (e.g., FunctionResource, FileResource).
- Function-based Resources: The decorated function is executed to generate the resource content.
- File-based Resources: The content is read directly from a file on the server.
# tests/server/fastmcp/test_server.py:644-647
@mcp.resource("function://test", name="test_get_data")
def get_data() -> str:
"""get_data returns a string"""
return "Hello, world!"
Sources: tests/server/fastmcp/test_server.py:592-652, tests/server/fastmcp/resources/test_function_resources.py:8-48
Resource Templates
Resources can be defined with URI templates to create dynamic resources. The template parameters are extracted from the request URI and passed as arguments to the resource function.
# tests/server/fastmcp/test_server.py:691-694
@mcp.resource("resource://{name}/data")
def get_data(name: str) -> str:
return f"Data for {name}"
In this example, a client request to resource://test/data would call get_data(name="test"). The function signature must match the URI parameters.
Sources: tests/server/fastmcp/test_server.py:674-703
Prompts
Prompts are server-side templates used to generate sequences of messages, often for constructing inputs for language models. They can accept arguments to customize their output.
Defining Prompts
Prompts are defined using the @mcp.prompt() decorator. The decorated function returns a string or a list of Message objects.
# tests/server/fastmcp/test_server.py:892-895
@mcp.prompt()
def fn(name: str) -> str:
return f"Hello, {name}!"
When a client requests this prompt with the argument {"name": "World"}, the server returns a UserMessage with the content "Hello, World!".
Sources: tests/server/fastmcp/test_server.py:878-936
Context Injection
Tools, resources, and prompts can have a Context object injected as a parameter. This object provides access to the underlying server session and request-specific information. It can be used for:
- Sending log messages (
ctx.debug,ctx.info, etc.). - Sending progress notifications.
- Reading other resources (
ctx.read_resource).
# tests/server/fastmcp/test_server.py:841-847
@mcp.tool()
async def tool_with_resource(ctx: Context[ServerSession, None]) -> str:
r_iter = await ctx.read_resource("test://data")
r_list = list(r_iter)
assert len(r_list) == 1
r = r_list[0]
return f"Read resource: {r.content} with mime type {r.mime_type}"
Sources: tests/server/fastmcp/test_server.py:761-866
Authentication
The SDK provides a robust OAuth 2.0 authentication system based on RFC specifications. The architecture separates the Authorization Server (AS), which handles user authentication and token issuance, from the Resource Server (RS), which is the MCP server itself.
Sources: examples/servers/simple-auth/README.md, tests/server/fastmcp/auth/test_auth_integration.py
Authentication Flow
The client authentication process follows the standard OAuth 2.0 Authorization Code Flow with PKCE.
This diagram shows the full flow, from discovering the Authorization Server to obtaining an access token and using it to access the MCP server.
Sources: examples/servers/simple-auth/README.md, tests/server/fastmcp/auth/test_auth_integration.py:530-631
Bearer Token Middleware
Authenticated requests to the MCP server must include a valid Authorization: Bearer <token> header. The BearerAuthBackend and RequireAuthMiddleware components handle token validation and scope enforcement.
- The middleware extracts the token from the header.
- It uses a
ProviderTokenVerifierto validate the token against the Authorization Server's records. - It checks for token expiration and required scopes.
- If valid, it populates
request.scope['user']andrequest.scope['auth']for use by the application.
If authentication or authorization fails, the middleware returns a 401 Unauthorized or 403 Forbidden response.
Sources: tests/server/auth/middleware/test_bearer_auth.py:1-331
Conclusion
The python-sdk provides a comprehensive and flexible toolkit for building MCP-compliant servers. By leveraging decorators for defining capabilities and a clear separation of concerns between the server logic, transport layer, and authentication, developers can quickly create powerful and secure applications. The core concepts of Tools, Resources, and Prompts offer a structured way to expose server functionality, while the robust authentication system ensures secure client interactions.