Jeremiah Lowin commited on
Commit
f07a282
·
1 Parent(s): 1ef0006

update docs

Browse files
docs/servers/fastmcp.mdx CHANGED
@@ -308,7 +308,6 @@ Server behavior, like transport settings (host, port for SSE) and how duplicate
308
 
309
  ```python
310
  from fastmcp import FastMCP
311
- from fastmcp.settings import DuplicateBehavior
312
 
313
  # Configure during initialization
314
  mcp = FastMCP(
@@ -331,5 +330,4 @@ print(mcp.settings.on_duplicate_tools) # Output: "error"
331
  - **`on_duplicate_resources`**: How to handle duplicate resource registrations
332
  - **`on_duplicate_prompts`**: How to handle duplicate prompt registrations
333
 
334
- All of these can be configured directly as parameters when creating the `FastMCP` instance.
335
-
 
308
 
309
  ```python
310
  from fastmcp import FastMCP
 
311
 
312
  # Configure during initialization
313
  mcp = FastMCP(
 
330
  - **`on_duplicate_resources`**: How to handle duplicate resource registrations
331
  - **`on_duplicate_prompts`**: How to handle duplicate prompt registrations
332
 
333
+ All of these can be configured directly as parameters when creating the `FastMCP` instance.
 
docs/servers/prompts.mdx CHANGED
@@ -205,7 +205,6 @@ You can configure how the FastMCP server handles attempts to register multiple p
205
 
206
  ```python
207
  from fastmcp import FastMCP
208
- from fastmcp.settings import DuplicateBehavior
209
 
210
  mcp = FastMCP(
211
  name="PromptServer",
@@ -216,14 +215,14 @@ mcp = FastMCP(
216
  def greeting(): return "Hello, how can I help you today?"
217
 
218
  # This registration attempt will raise a ValueError because
219
- # "greeting" is already registered and the behavior is ERROR.
220
  # @mcp.prompt()
221
  # def greeting(): return "Hi there! What can I do for you?"
222
  ```
223
 
224
- The `DuplicateBehavior` enum options are:
225
 
226
- - `WARN` (default): Logs a warning, and the new prompt replaces the old one.
227
- - `ERROR`: Raises a `ValueError`, preventing the duplicate registration.
228
- - `REPLACE`: Silently replaces the existing prompt with the new one.
229
- - `IGNORE`: Keeps the original prompt and ignores the new registration attempt.
 
205
 
206
  ```python
207
  from fastmcp import FastMCP
 
208
 
209
  mcp = FastMCP(
210
  name="PromptServer",
 
215
  def greeting(): return "Hello, how can I help you today?"
216
 
217
  # This registration attempt will raise a ValueError because
218
+ # "greeting" is already registered and the behavior is "error".
219
  # @mcp.prompt()
220
  # def greeting(): return "Hi there! What can I do for you?"
221
  ```
222
 
223
+ The duplicate behavior options are:
224
 
225
+ - `"warn"` (default): Logs a warning, and the new prompt replaces the old one.
226
+ - `"error"`: Raises a `ValueError`, preventing the duplicate registration.
227
+ - `"replace"`: Silently replaces the existing prompt with the new one.
228
+ - `"ignore"`: Keeps the original prompt and ignores the new registration attempt.
docs/servers/resources.mdx CHANGED
@@ -297,7 +297,6 @@ You can configure how the FastMCP server handles attempts to register multiple r
297
 
298
  ```python
299
  from fastmcp import FastMCP
300
- from fastmcp.settings import DuplicateBehavior
301
 
302
  mcp = FastMCP(
303
  name="ResourceServer",
@@ -308,14 +307,14 @@ mcp = FastMCP(
308
  def get_config_v1(): return {"version": 1}
309
 
310
  # This registration attempt will raise a ValueError because
311
- # "data://config" is already registered and the behavior is ERROR.
312
  # @mcp.resource("data://config")
313
  # def get_config_v2(): return {"version": 2}
314
  ```
315
 
316
- The `DuplicateBehavior` enum options are:
317
 
318
- - `WARN` (default): Logs a warning, and the new resource/template replaces the old one.
319
- - `ERROR`: Raises a `ValueError`, preventing the duplicate registration.
320
- - `REPLACE`: Silently replaces the existing resource/template with the new one.
321
- - `IGNORE`: Keeps the original resource/template and ignores the new registration attempt.
 
297
 
298
  ```python
299
  from fastmcp import FastMCP
 
300
 
301
  mcp = FastMCP(
302
  name="ResourceServer",
 
307
  def get_config_v1(): return {"version": 1}
308
 
309
  # This registration attempt will raise a ValueError because
310
+ # "data://config" is already registered and the behavior is "error".
311
  # @mcp.resource("data://config")
312
  # def get_config_v2(): return {"version": 2}
313
  ```
314
 
315
+ The duplicate behavior options are:
316
 
317
+ - `"warn"` (default): Logs a warning, and the new resource/template replaces the old one.
318
+ - `"error"`: Raises a `ValueError`, preventing the duplicate registration.
319
+ - `"replace"`: Silently replaces the existing resource/template with the new one.
320
+ - `"ignore"`: Keeps the original resource/template and ignores the new registration attempt.
docs/servers/resources_backup.mdx DELETED
@@ -1,270 +0,0 @@
1
- ---
2
- title: Resources & Templates
3
- sidebarTitle: Resources & Templates
4
- description: Expose data sources and dynamic content generators to your MCP client.
5
- icon: database
6
- ---
7
-
8
- Resources represent data or files that an MCP client can read, and resource templates extend this concept by allowing clients to request dynamically generated resources based on parameters passed in the URI.
9
-
10
- FastMCP simplifies defining both static and dynamic resources, primarily using the `@mcp.resource` decorator.
11
-
12
- ## What Are Resources?
13
-
14
- Resources provide read-only access to data for the LLM or client application. When a client requests a resource URI:
15
-
16
- 1. FastMCP finds the corresponding resource definition.
17
- 2. If it's dynamic (defined by a function), the function is executed.
18
- 3. The content (text, JSON, binary data) is returned to the client.
19
-
20
- This allows LLMs to access files, database content, configuration, or dynamically generated information relevant to the conversation.
21
-
22
- ## Defining Resources with `@mcp.resource`
23
-
24
- The most common way to define a resource is by decorating a Python function. The decorator requires the resource's unique URI.
25
-
26
- ```python
27
- import json
28
- from fastmcp import FastMCP
29
-
30
- mcp = FastMCP(name="DataServer")
31
-
32
- # Basic dynamic resource returning a string
33
- @mcp.resource("resource://greeting")
34
- def get_greeting() -> str:
35
- """Provides a simple greeting message."""
36
- return "Hello from FastMCP Resources!"
37
-
38
- # Resource returning JSON data (dict is auto-serialized)
39
- @mcp.resource("data://config")
40
- def get_config() -> dict:
41
- """Provides application configuration as JSON."""
42
- return {
43
- "theme": "dark",
44
- "version": "1.2.0",
45
- "features": ["tools", "resources"],
46
- }
47
- ```
48
-
49
- **Key Concepts:**
50
-
51
- * **URI:** The first argument to `@resource` is the unique URI (e.g., `"resource://greeting"`) clients use to request this data.
52
- * **Lazy Loading:** The decorated function (`get_greeting`, `get_config`) is only executed when a client specifically requests that resource URI via `resources/read`.
53
- * **Inferred Metadata:** By default:
54
- * Resource Name: Taken from the function name (`get_greeting`).
55
- * Resource Description: Taken from the function's docstring.
56
-
57
- ### Return Value Handling
58
-
59
- FastMCP automatically converts your function's return value into the appropriate MCP resource content:
60
-
61
- - **`str`**: Sent as `TextResourceContents` (with `mime_type="text/plain"` by default).
62
- - **`dict`, `list`, `pydantic.BaseModel`**: Automatically serialized to a JSON string and sent as `TextResourceContents` (with `mime_type="application/json"` by default).
63
- - **`bytes`**: Base64 encoded and sent as `BlobResourceContents`. You should specify an appropriate `mime_type` (e.g., `"image/png"`, `"application/octet-stream"`).
64
- - **`None`**: Results in an empty resource content list being returned.
65
-
66
- ### Resource Metadata
67
-
68
- You can customize the resource's properties using arguments in the decorator:
69
-
70
- ```python
71
- from fastmcp import FastMCP
72
-
73
- mcp = FastMCP(name="DataServer")
74
-
75
- # Example specifying metadata
76
- @mcp.resource(
77
- uri="data://app-status", # Explicit URI (required)
78
- name="ApplicationStatus", # Custom name
79
- description="Provides the current status of the application.", # Custom description
80
- mime_type="application/json", # Explicit MIME type
81
- tags={"monitoring", "status"} # Categorization tags
82
- )
83
- def get_application_status() -> dict:
84
- """Internal function description (ignored if description is provided above)."""
85
- return {"status": "ok", "uptime": 12345, "version": mcp.settings.version} # Example usage
86
- ```
87
-
88
- - **`uri`**: The unique identifier for the resource (required).
89
- - **`name`**: A human-readable name (defaults to function name).
90
- - **`description`**: Explanation of the resource (defaults to docstring).
91
- - **`mime_type`**: Specifies the content type (FastMCP often infers a default like `text/plain` or `application/json`, but explicit is better for non-text types).
92
- - **`tags`**: A set of strings for categorization, potentially used by clients for filtering.
93
-
94
- ### Using Context in Resources
95
-
96
- Like tools, resource functions can request the `Context` object to access MCP session capabilities.
97
-
98
- ```python
99
- from fastmcp import FastMCP, Context
100
- import datetime
101
-
102
- mcp = FastMCP(name="DataServer")
103
-
104
- @mcp.resource("data://server-info", tags={"server", "info"})
105
- async def get_server_info(ctx: Context) -> dict:
106
- """Provides information about the server using context."""
107
- await ctx.info(f"Generating server info resource for request {ctx.request_id}")
108
- # You could potentially read other resources via ctx.read_resource here
109
- return {
110
- "server_name": mcp.name,
111
- "timestamp": datetime.datetime.now(datetime.UTC).isoformat(),
112
- "client_id": ctx.client_id or "N/A",
113
- "log_level": mcp.settings.log_level,
114
- }
115
- ```
116
-
117
- ### Asynchronous Resources
118
-
119
- Use `async def` for resource functions that perform I/O operations (e.g., reading from a database or network) to avoid blocking the server.
120
-
121
- ```python
122
- import aiofiles
123
- from fastmcp import FastMCP
124
-
125
- mcp = FastMCP(name="DataServer")
126
-
127
- @mcp.resource("file:///app/data/important_log.txt", mime_type="text/plain")
128
- async def read_important_log() -> str:
129
- """Reads content from a specific log file asynchronously."""
130
- try:
131
- async with aiofiles.open("/app/data/important_log.txt", mode="r") as f:
132
- content = await f.read()
133
- return content
134
- except FileNotFoundError:
135
- return "Log file not found."
136
- ```
137
-
138
- ## (Alternative) Defining Static Resources
139
-
140
- While `@mcp.resource` is ideal for dynamic content, you can directly register pre-defined resources (like static files or simple text) using `mcp.add_resource()` and concrete `Resource` subclasses.
141
-
142
- ```python
143
- from pathlib import Path
144
- from fastmcp import FastMCP
145
- from fastmcp.resources import FileResource, TextResource, DirectoryResource
146
-
147
- mcp = FastMCP(name="DataServer")
148
-
149
- # 1. Exposing a static file directly
150
- readme_path = Path("./README.md").resolve()
151
- if readme_path.exists():
152
- # Use a file:// URI scheme
153
- readme_resource = FileResource(
154
- uri=f"file://{readme_path.as_posix()}",
155
- path=readme_path, # Path to the actual file
156
- name="README File",
157
- description="The project's README.",
158
- mime_type="text/markdown",
159
- tags={"documentation"}
160
- )
161
- mcp.add_resource(readme_resource)
162
-
163
- # 2. Exposing simple, predefined text
164
- notice_resource = TextResource(
165
- uri="resource://notice",
166
- name="Important Notice",
167
- text="System maintenance scheduled for Sunday.",
168
- tags={"notification"}
169
- )
170
- mcp.add_resource(notice_resource)
171
-
172
- # 3. Exposing a directory listing
173
- data_dir_path = Path("./app_data").resolve()
174
- if data_dir_path.is_dir():
175
- data_listing_resource = DirectoryResource(
176
- uri="resource://data-files",
177
- path=data_dir_path, # Path to the directory
178
- name="Data Directory Listing",
179
- description="Lists files available in the data directory.",
180
- recursive=False # Set to True to list subdirectories
181
- )
182
- mcp.add_resource(data_listing_resource) # Returns JSON list of files
183
- ```
184
-
185
- **Common Resource Classes:**
186
-
187
- - `TextResource`: For simple string content.
188
- - `BinaryResource`: For raw `bytes` content.
189
- - `FileResource`: Reads content from a local file path. Handles text/binary modes and lazy reading.
190
- - `HttpResource`: Fetches content from an HTTP(S) URL (requires `httpx`).
191
- - `DirectoryResource`: Lists files in a local directory (returns JSON).
192
- - (`FunctionResource`: Internal class used by `@mcp.resource`).
193
-
194
- Use these when the content is static or sourced directly from a file/URL, bypassing the need for a dedicated Python function.
195
-
196
- ## Defining Resource Templates
197
-
198
- Resource Templates allow clients to request resources whose content depends on parameters embedded in the URI. Define a template using the **same `@mcp.resource` decorator**, but include `{parameter_name}` placeholders in the URI string and add corresponding arguments to your function signature.
199
-
200
- ```python
201
- from fastmcp import FastMCP
202
-
203
- mcp = FastMCP(name="DataServer")
204
-
205
- # Template URI includes {city} placeholder
206
- @mcp.resource("data://weather/{city}")
207
- # Function accepts 'city' parameter matching the placeholder
208
- def get_weather_for_city(city: str) -> dict:
209
- """Provides weather information for a specific city."""
210
- print(f"Server: Generating weather for city: {city}...")
211
- # In reality, call a weather API using the 'city' parameter
212
- temp = 20 + len(city) % 5 # Dummy logic
213
- condition = "Sunny" if len(city) % 2 == 0 else "Cloudy"
214
- return {"city": city.capitalize(), "temperature": temp, "unit": "celsius", "condition": condition}
215
-
216
- # Template with an integer parameter
217
- @mcp.resource("users://{user_id}/profile")
218
- async def get_user_profile(user_id: int) -> dict:
219
- """Retrieves a user's profile information by ID."""
220
- print(f"Server: Generating profile for user ID: {user_id}...")
221
- # In reality, fetch from database using user_id
222
- # FastMCP uses Pydantic to auto-convert the string URI part to int
223
- if user_id == 1:
224
- return {"id": user_id, "name": "Alice", "email": "alice@example.com", "status": "active"}
225
- elif user_id == 2:
226
- return {"id": user_id, "name": "Bob", "email": "bob@example.com", "status": "inactive"}
227
- else:
228
- # Example of returning an error structure
229
- return {"error": f"User with ID {user_id} not found"}
230
- ```
231
-
232
- **How Templates Work:**
233
-
234
- 1. **Definition:** When FastMCP sees `{...}` placeholders in the `@resource` URI and matching function parameters, it registers a `ResourceTemplate`.
235
- 2. **Discovery:** Clients list templates via `resources/listResourceTemplates`.
236
- 3. **Request & Matching:** A client requests a specific URI, e.g., `data://weather/london`. FastMCP matches this to the `data://weather/{city}` template.
237
- 4. **Parameter Extraction:** It extracts the parameter value: `city="london"`.
238
- 5. **Type Conversion & Function Call:** It converts the extracted string `"london"` to the type hinted in the function (`str` in this case) and calls `get_weather_for_city(city="london")`. For `users://1/profile`, it converts `"1"` to `int` before calling `get_user_profile(user_id=1)`.
239
- 6. **Response:** The function's return value is formatted (e.g., dict to JSON) and sent back as the content of the requested resource URI (`data://weather/london`).
240
-
241
- Templates provide a powerful way to expose parameterized data access points following REST-like principles.
242
-
243
- ## Server Behavior: Handling Duplicate Resources
244
-
245
- You can configure how the FastMCP server handles attempts to register multiple resources or templates with the same URI. Use the `on_duplicate_resources` setting during `FastMCP` initialization.
246
-
247
- ```python
248
- from fastmcp import FastMCP
249
- from fastmcp.settings import DuplicateBehavior
250
-
251
- mcp = FastMCP(
252
- name="ResourceServer",
253
- on_duplicate_resources="error" # Raise error on duplicates
254
- )
255
-
256
- @mcp.resource("data://config")
257
- def get_config_v1(): return {"version": 1}
258
-
259
- # This registration attempt will raise a ValueError because
260
- # "data://config" is already registered and the behavior is ERROR.
261
- # @mcp.resource("data://config")
262
- # def get_config_v2(): return {"version": 2}
263
- ```
264
-
265
- The `DuplicateBehavior` enum options are:
266
-
267
- - `WARN` (default): Logs a warning, and the new resource/template replaces the old one.
268
- - `ERROR`: Raises a `ValueError`, preventing the duplicate registration.
269
- - `REPLACE`: Silently replaces the existing resource/template with the new one.
270
- - `IGNORE`: Keeps the original resource/template and ignores the new registration attempt.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
docs/servers/tools.mdx CHANGED
@@ -310,7 +310,6 @@ You can control how the FastMCP server behaves if you try to register multiple t
310
 
311
  ```python
312
  from fastmcp import FastMCP
313
- from fastmcp.settings import DuplicateBehavior
314
 
315
  mcp = FastMCP(
316
  name="StrictServer",
@@ -322,14 +321,14 @@ mcp = FastMCP(
322
  def my_tool(): return "Version 1"
323
 
324
  # This will now raise a ValueError because 'my_tool' already exists
325
- # and on_duplicate_tools is set to ERROR.
326
  # @mcp.tool()
327
  # def my_tool(): return "Version 2"
328
  ```
329
 
330
- The `DuplicateBehavior` enum options are:
331
 
332
- - `WARN` (default): Logs a warning and the new tool replaces the old one.
333
- - `ERROR`: Raises a `ValueError`, preventing the duplicate registration.
334
- - `REPLACE`: Silently replaces the existing tool with the new one.
335
- - `IGNORE`: Keeps the original tool and ignores the new registration attempt.
 
310
 
311
  ```python
312
  from fastmcp import FastMCP
 
313
 
314
  mcp = FastMCP(
315
  name="StrictServer",
 
321
  def my_tool(): return "Version 1"
322
 
323
  # This will now raise a ValueError because 'my_tool' already exists
324
+ # and on_duplicate_tools is set to "error".
325
  # @mcp.tool()
326
  # def my_tool(): return "Version 2"
327
  ```
328
 
329
+ The duplicate behavior options are:
330
 
331
+ - `"warn"` (default): Logs a warning and the new tool replaces the old one.
332
+ - `"error"`: Raises a `ValueError`, preventing the duplicate registration.
333
+ - `"replace"`: Silently replaces the existing tool with the new one.
334
+ - `"ignore"`: Keeps the original tool and ignores the new registration attempt.