Add tutorials

This commit is contained in:
Jeremiah Lowin 2025-06-10 18:44:58 -04:00
commit 2d5c88965b
4 changed files with 326 additions and 1 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 645 KiB

View file

@ -134,7 +134,9 @@
"anchor": "Tutorials",
"icon": "graduation-cap",
"pages": [
"tutorials/create-mcp-server"
"tutorials/mcp",
"tutorials/create-mcp-server",
"tutorials/rest-api"
]
},
{

120
docs/tutorials/mcp.mdx Normal file
View file

@ -0,0 +1,120 @@
---
title: "What is the Model Context Protocol (MCP)?"
sidebarTitle: "What is MCP?"
description: "An introduction to the core concepts of the Model Context Protocol (MCP), explaining what it is, why it's useful, and how it works."
icon: "diagram-project"
---
The Model Context Protocol (MCP) is an open standard designed to solve a fundamental problem in AI development: how can Large Language Models (LLMs) reliably and securely interact with external tools, data, and services?
It's the **bridge between the probabilistic, non-deterministic world of AI and the deterministic, reliable world of your code and data.**
While you could build a custom REST API for your LLM, MCP provides a specialized, standardized "port" for AI-native communication. Think of it as **USB-C for AI**: a single, well-defined interface for connecting any compliant LLM to any compliant tool or data source.
This guide provides a high-level overview of the protocol itself. We'll use **FastMCP**, the leading Python framework for MCP, to illustrate the concepts with simple code examples.
## Why Do We Need a Protocol?
With countless APIs already in existence, the most common question is: "Why do we need another one?"
The answer lies in **standardization**. The AI ecosystem is fragmented. Every model provider has its own way of defining and calling tools. MCP's goal is to create a common language that offers several key advantages:
1. **Interoperability:** Build one MCP server, and it can be used by any MCP-compliant client (Claude, Gemini, OpenAI, custom agents, etc.) without custom integration code. This is the protocol's most important promise.
2. **Discoverability:** Clients can dynamically ask a server what it's capable of at runtime. They receive a structured, machine-readable "menu" of tools and resources.
3. **Security & Safety:** MCP provides a clear, sandboxed boundary. An LLM can't execute arbitrary code on your server; it can only *request* to run the specific, typed, and validated functions you explicitly expose.
4. **Composability:** You can build small, specialized MCP servers and combine them to create powerful, complex applications.
## Core MCP Components
An MCP server exposes its capabilities through three primary components: Tools, Resources, and Prompts.
### Tools: Executable Actions
Tools are functions that the LLM can ask the server to execute. They are the action-oriented part of MCP.
In the spirit of a REST API, you can think of **Tools as being like `POST` requests.** They are used to *perform an action*, *change state*, or *trigger a side effect*, like sending an email, adding a user to a database, or making a calculation.
With FastMCP, creating a tool is as simple as decorating a Python function.
```python
from fastmcp import FastMCP
mcp = FastMCP()
# This function is now an MCP tool named "get_weather"
@mcp.tool
def get_weather(city: str) -> dict:
"""Gets the current weather for a specific city."""
# In a real app, this would call a weather API
return {"city": city, "temperature": "72F", "forecast": "Sunny"}
```
[**Learn more about Tools →**](/servers/tools)
### Resources: Read-Only Data
Resources are data sources that the LLM can read. They are used to load information into the LLM's context, providing it with knowledge it doesn't have from its training data.
Following the REST API analogy, **Resources are like `GET` requests.** Their purpose is to *retrieve information* idempotently, ideally without causing side effects. A resource can be anything from a static text file to a dynamic piece of data from a database. Each resource is identified by a unique URI.
```python
from fastmcp import FastMCP
mcp = FastMCP()
# This function provides a resource at the URI "system://status"
@mcp.resource("system://status")
def get_system_status() -> dict:
"""Returns the current operational status of the service."""
return {"status": "all systems normal"}
```
#### Resource Templates
You can also create **Resource Templates** for dynamic data. A client could request `users://42/profile` to get the profile for a specific user.
```python
from fastmcp import FastMCP
mcp = FastMCP()
# This template provides user data for any given user ID
@mcp.resource("users://{user_id}/profile")
def get_user_profile(user_id: str) -> dict:
"""Returns the profile for a specific user."""
# Fetch user from a database...
return {"id": user_id, "name": "Zaphod Beeblebrox"}
```
[**Learn more about Resources & Templates →**](/servers/resources)
### Prompts: Reusable Instructions
Prompts are reusable, parameterized message templates. They provide a way to define consistent, structured instructions that a client can request to guide the LLM's behavior for a specific task.
```python
from fastmcp import FastMCP
mcp = FastMCP()
@mcp.prompt
def summarize_text(text_to_summarize: str) -> str:
"""Creates a prompt asking the LLM to summarize a piece of text."""
return f"""
Please provide a concise, one-paragraph summary of the following text:
{text_to_summarize}
"""
```
[**Learn more about Prompts →**](/servers/prompts)
## Advanced Capabilities
Beyond the core components, MCP also supports more advanced interaction patterns, such as a server requesting that the *client's* LLM generate a completion (known as **sampling**), or a server sending asynchronous **notifications** to a client. These features enable more complex, bidirectional workflows and are fully supported by FastMCP.
## Next Steps
Now that you understand the core concepts of the Model Context Protocol, you're ready to start building. The best place to begin is our step-by-step tutorial.
[**Tutorial: How to Create an MCP Server in Python →**](/tutorials/create-mcp-server)

203
docs/tutorials/rest-api.mdx Normal file
View file

@ -0,0 +1,203 @@
---
title: "How to Connect an LLM to a REST API"
sidebarTitle: "Connect LLMs to REST APIs"
description: "A step-by-step guide to making any REST API with an OpenAPI spec available to LLMs using FastMCP."
icon: "plug"
---
You've built a powerful REST API, and now you want your LLM to be able to use it. Manually writing a wrapper function for every single endpoint is tedious, error-prone, and hard to maintain.
This is where **FastMCP** shines. If your API has an OpenAPI (or Swagger) specification, FastMCP can automatically convert your entire API into a fully-featured MCP server, making every endpoint available as a secure, typed tool for your AI model.
This guide will walk you through converting a public REST API into an MCP server in just a few lines of code.
<Tip>
Every code block in this tutorial is a complete, runnable example. You can copy and paste it into a file and run it, or paste it directly into a Python REPL like IPython to try it out.
</Tip>
### Prerequisites
Make sure you have FastMCP installed. If not, follow the [installation guide](/getting-started/installation).
```bash
pip install fastmcp
```
## Step 1: Choose a Target API
For this tutorial, we'll use the [JSONPlaceholder API](https://jsonplaceholder.typicode.com/), a free, fake online REST API for testing and prototyping. It's perfect because it's simple and has a public OpenAPI specification.
- **API Base URL:** `https://jsonplaceholder.typicode.com`
- **OpenAPI Spec URL:** We'll use a community-provided spec for it.
## Step 2: Create the MCP Server
Now for the magic. We'll use `FastMCP.from_openapi`. This method takes an `httpx.AsyncClient` configured for your API and its OpenAPI specification, and automatically converts **every endpoint** into a callable MCP `Tool`.
<Tip>
Learn more about working with OpenAPI specs in the [OpenAPI integration docs](/servers/openapi).
</Tip>
<Note>
For this tutorial, we'll use a simplified OpenAPI spec directly in the code. In a real project, you would typically load the spec from a URL or local file.
</Note>
Create a file named `api_server.py`:
```python api_server.py {31-35}
import httpx
from fastmcp import FastMCP
# Create an HTTP client for the target API
client = httpx.AsyncClient(base_url="https://jsonplaceholder.typicode.com")
# Define a simplified OpenAPI spec for JSONPlaceholder
openapi_spec = {
"openapi": "3.0.0",
"info": {"title": "JSONPlaceholder API", "version": "1.0"},
"paths": {
"/users": {
"get": {
"summary": "Get all users",
"operationId": "get_users",
"responses": {"200": {"description": "A list of users."}}
}
},
"/users/{id}": {
"get": {
"summary": "Get a user by ID",
"operationId": "get_user_by_id",
"parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}],
"responses": {"200": {"description": "A single user."}}
}
}
}
}
# Create the MCP server from the OpenAPI spec
mcp = FastMCP.from_openapi(
openapi_spec=openapi_spec,
client=client,
name="JSONPlaceholder MCP Server"
)
if __name__ == "__main__":
mcp.run(transport="streamable-http", port=8000)
```
And that's it! With just a few lines of code, you've created an MCP server that exposes the entire JSONPlaceholder API as a collection of tools.
## Step 3: Test the Generated Server
Let's verify that our new MCP server works. We can use the `fastmcp.Client` to connect to it and inspect its tools.
<Tip>
Learn more about the FastMCP client in the [client docs](/clients/client).
</Tip>
Create a separate file, `api_client.py`:
```python api_client.py {2, 6, 9, 16}
import asyncio
from fastmcp import Client
async def main():
# Connect to the MCP server we just created
async with Client("http://127.0.0.1:8000/mcp") as client:
# List the tools that were automatically generated
tools = await client.list_tools()
print("Generated Tools:")
for tool in tools:
print(f"- {tool.name}")
# Call one of the generated tools
print("\n\nCalling tool 'get_user_by_id'...")
user = await client.call_tool("get_user_by_id", {"id": 1})
print(f"Result:\n{user[0].text}")
if __name__ == "__main__":
asyncio.run(main())
```
First, run your server:
```bash
python api_server.py
```
Then, in another terminal, run the client:
```bash
python api_client.py
```
You should see a list of generated tools (`get_users`, `get_user_by_id`) and the result of calling the `get_user_by_id` tool, which fetches data from the live JSONPlaceholder API.
![](/assets/images/tutorial-rest-api-result.png)
## Step 4: Customizing Route Maps
By default, FastMCP converts every API endpoint into an MCP `Tool`. This ensures maximum compatibility with contemporary LLM clients, many of which **only support the `tools` part of the MCP specification.**
However, for clients that support the full MCP spec, representing `GET` requests as `Resources` can be more semantically correct and efficient.
FastMCP allows users to customize this behavior using the concept of "route maps". A `RouteMap` is a mapping of an API route to an MCP type. FastMCP checks each API route against your custom maps in order. If a route matches a map, it's converted to the specified `mcp_type`. Any route that doesn't match your custom maps will fall back to the default behavior (becoming a `Tool`).
<Tip>
Learn more about route maps in the [OpenAPI integration docs](/servers/openapi#route-mapping).
</Tip>
Heres how you can add custom route maps to turn `GET` requests into `Resources` and `ResourceTemplates` (if they have path parameters):
```python api_server_with_resources.py {3, 37-42}
import httpx
from fastmcp import FastMCP
from fastmcp.server.openapi import RouteMap, MCPType
# Create an HTTP client for the target API
client = httpx.AsyncClient(base_url="https://jsonplaceholder.typicode.com")
# Define a simplified OpenAPI spec for JSONPlaceholder
openapi_spec = {
"openapi": "3.0.0",
"info": {"title": "JSONPlaceholder API", "version": "1.0"},
"paths": {
"/users": {
"get": {
"summary": "Get all users",
"operationId": "get_users",
"responses": {"200": {"description": "A list of users."}}
}
},
"/users/{id}": {
"get": {
"summary": "Get a user by ID",
"operationId": "get_user_by_id",
"parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}],
"responses": {"200": {"description": "A single user."}}
}
}
}
}
# Create the MCP server with custom route mapping
mcp = FastMCP.from_openapi(
openapi_spec=openapi_spec,
client=client,
name="JSONPlaceholder MCP Server",
route_maps=[
# Map GET requests with path parameters (e.g., /users/{id}) to ResourceTemplate
RouteMap(methods=["GET"], pattern=r".*\{.*\}.*", mcp_type=MCPType.RESOURCE_TEMPLATE),
# Map all other GET requests to Resource
RouteMap(methods=["GET"], mcp_type=MCPType.RESOURCE),
]
)
if __name__ == "__main__":
mcp.run(transport="streamable-http", port=8000)
```
With this configuration:
- `GET /users/{id}` becomes a `ResourceTemplate`.
- `GET /users` becomes a `Resource`.
- Any `POST`, `PUT`, etc. endpoints would still become `Tools` by default.