A step-by-step guide to building a Model Context Protocol (MCP) server using Python and FastMCP, from basic tools to dynamic resources.
FastMCP
class. This object acts as the container for all your tools and resources.
Create a new file called my_mcp_server.py
:
@mcp.tool
.
add
) as the tool’s name.a: int
, b: int
) to generate a JSON schema for the inputs.@mcp.resource
, providing a unique URI.
Let’s expose a simple configuration dictionary as a resource.
resource://config
, FastMCP will execute the get_config
function and return its output (serialized as JSON) to the client. The function is only called when the resource is requested, enabling lazy-loading of data.
@mcp.resource
decorator but with placeholders in the URI.
Let’s create a template that provides a personalized greeting.
greetings://Ford
will call personalized_greeting(name="Ford")
.greetings://Marvin
will call personalized_greeting(name="Marvin")
.{name}
placeholder in the URI to the name
parameter in your function.
__main__
block to your script that calls mcp.run()
.
my_mcp_server.py
(click to expand):