docs: migrate mcp.types/mcp imports to fastmcp equivalents

This commit is contained in:
Jeremiah Lowin 2026-07-06 00:24:38 -04:00
commit c6aa7f5e53
No known key found for this signature in database
15 changed files with 46 additions and 47 deletions

View file

@ -212,11 +212,11 @@ import base64
import io
import qrcode
from mcp import types
from fastmcp import FastMCP
from fastmcp.apps import AppConfig, ResourceCSP
from fastmcp.tools import ToolResult
from fastmcp.types import ImageContent
mcp = FastMCP("QR Code Server")
@ -236,7 +236,7 @@ def generate_qr(text: str = "https://gofastmcp.com") -> ToolResult:
b64 = base64.b64encode(buffer.getvalue()).decode()
return ToolResult(
content=[types.ImageContent(type="image", data=b64, mimeType="image/png")]
content=[ImageContent(type="image", data=b64, mime_type="image/png")]
)

View file

@ -45,23 +45,23 @@ For fine-grained targeting, subclass `MessageHandler` to use specific hooks:
```python
from fastmcp import Client
from fastmcp.client.messages import MessageHandler
import mcp.types
import mcp_types
class MyMessageHandler(MessageHandler):
async def on_tool_list_changed(
self, notification: mcp.types.ToolListChangedNotification
self, notification: mcp_types.ToolListChangedNotification
) -> None:
"""Handle tool list changes."""
print("Tool list changed - refreshing available tools")
async def on_resource_list_changed(
self, notification: mcp.types.ResourceListChangedNotification
self, notification: mcp_types.ResourceListChangedNotification
) -> None:
"""Handle resource list changes."""
print("Resource list changed")
async def on_prompt_list_changed(
self, notification: mcp.types.PromptListChangedNotification
self, notification: mcp_types.PromptListChangedNotification
) -> None:
"""Handle prompt list changes."""
print("Prompt list changed")
@ -76,7 +76,7 @@ client = Client(
```python
from fastmcp.client.messages import MessageHandler
import mcp.types
import mcp_types
class MyMessageHandler(MessageHandler):
async def on_message(self, message) -> None:
@ -84,37 +84,37 @@ class MyMessageHandler(MessageHandler):
pass
async def on_notification(
self, notification: mcp.types.ServerNotification
self, notification: mcp_types.ServerNotification
) -> None:
"""Called for notifications (fire-and-forget)."""
pass
async def on_tool_list_changed(
self, notification: mcp.types.ToolListChangedNotification
self, notification: mcp_types.ToolListChangedNotification
) -> None:
"""Called when the server's tool list changes."""
pass
async def on_resource_list_changed(
self, notification: mcp.types.ResourceListChangedNotification
self, notification: mcp_types.ResourceListChangedNotification
) -> None:
"""Called when the server's resource list changes."""
pass
async def on_prompt_list_changed(
self, notification: mcp.types.PromptListChangedNotification
self, notification: mcp_types.PromptListChangedNotification
) -> None:
"""Called when the server's prompt list changes."""
pass
async def on_progress(
self, notification: mcp.types.ProgressNotification
self, notification: mcp_types.ProgressNotification
) -> None:
"""Called for progress updates during long-running operations."""
pass
async def on_logging_message(
self, notification: mcp.types.LoggingMessageNotification
self, notification: mcp_types.LoggingMessageNotification
) -> None:
"""Called for log messages from the server."""
pass
@ -127,14 +127,14 @@ A practical example of maintaining a tool cache that refreshes when tools change
```python
from fastmcp import Client
from fastmcp.client.messages import MessageHandler
import mcp.types
import mcp_types
class ToolCacheHandler(MessageHandler):
def __init__(self):
self.cached_tools = []
async def on_tool_list_changed(
self, notification: mcp.types.ToolListChangedNotification
self, notification: mcp_types.ToolListChangedNotification
) -> None:
"""Clear tool cache when tools change."""
print("Tools changed - clearing cache")

View file

@ -21,7 +21,7 @@ Request a rendered prompt with `get_prompt()`:
async with client:
# Simple prompt without arguments
result = await client.get_prompt("welcome_message")
# result -> mcp.types.GetPromptResult
# result -> fastmcp.types.GetPromptResult
# Access the generated messages
for message in result.messages:
@ -143,5 +143,5 @@ For complete control, use `get_prompt_mcp()` which returns the full MCP protocol
```python
async with client:
result = await client.get_prompt_mcp("example_prompt", {"arg": "value"})
# result -> mcp.types.GetPromptResult
# result -> fastmcp.types.GetPromptResult
```

View file

@ -106,5 +106,5 @@ For complete control, use `read_resource_mcp()` which returns the full MCP proto
```python
async with client:
result = await client.read_resource_mcp("resource://example")
# result -> mcp.types.ReadResourceResult
# result -> fastmcp.types.ReadResourceResult
```

View file

@ -172,7 +172,7 @@ Install the Google Gemini handler with `pip install fastmcp[gemini]`.
When you provide a `sampling_handler`, FastMCP automatically advertises full sampling capabilities to the server, including tool support. To disable tool support for simpler handlers:
```python
from mcp.types import SamplingCapability
from fastmcp.types import SamplingCapability
client = Client(
"my_mcp_server.py",

View file

@ -80,7 +80,7 @@ async with client:
Fully hydrated Python objects with complex type support (datetimes, UUIDs, custom classes). FastMCP exclusive.
</ResponseField>
<ResponseField name=".content" type="list[mcp.types.ContentBlock]">
<ResponseField name=".content" type="list[fastmcp.types.ContentBlock]">
Standard MCP content blocks (`TextContent`, `ImageContent`, `AudioContent`, etc.).
</ResponseField>
@ -173,7 +173,7 @@ For complete control, use `call_tool_mcp()` which returns the raw MCP protocol o
```python
async with client:
result = await client.call_tool_mcp("my_tool", {"param": "value"})
# result -> mcp.types.CallToolResult
# result -> fastmcp.types.CallToolResult
if result.isError:
print(f"Tool failed: {result.content}")

View file

@ -1426,7 +1426,7 @@ Prompt functions now use `Message` instead of `mcp.types.PromptMessage`:
```python
# v2.x
from mcp.types import PromptMessage, TextContent
from fastmcp.types import PromptMessage, TextContent
@mcp.prompt
def my_prompt() -> PromptMessage:

View file

@ -171,7 +171,7 @@ Prompt functions now use FastMCP's `Message` class instead of `mcp.types.PromptM
```python
# Before
from mcp.types import PromptMessage, TextContent
from fastmcp.types import PromptMessage, TextContent
@mcp.prompt
def my_prompt() -> PromptMessage:

View file

@ -51,9 +51,9 @@ Also: if prompts return raw dicts like `{"role": "user", "content": "..."}`, the
The MCP SDK's FastMCP 1.0 silently coerced dicts; standalone FastMCP requires typed returns.
STEP 4 — OTHER MCP IMPORTS (only if importing from mcp.* directly):
Direct imports from the `mcp` package (e.g., `import mcp.types`, `from mcp.server.stdio import stdio_server`) still work because FastMCP includes `mcp` as a dependency. However, prefer FastMCP's own APIs where equivalents exist:
- mcp.types.TextContent for tool returns → just return plain Python values (str, int, dict, etc.)
- mcp.types.ImageContent → fastmcp.utilities.types.Image
FastMCP now builds on MCP SDK v2, which removed the `mcp.types` module — protocol types live in the standalone `mcp_types` package. FastMCP re-exports the common ones from `fastmcp.types`. Update any `from mcp.types import X` to `from fastmcp.types import X` (or `import mcp_types`). Prefer FastMCP's own APIs where equivalents exist:
- fastmcp.types.TextContent for tool returns → just return plain Python values (str, int, dict, etc.)
- fastmcp.types.ImageContent → fastmcp.utilities.types.Image
- from mcp.server.stdio import stdio_server → not needed, mcp.run() handles transport
STEP 5 — DECORATORS (only if treating decorated functions as objects):
@ -113,7 +113,7 @@ def debug(error: str) -> list[Message]:
### Other `mcp.*` Imports
If your server imports directly from the `mcp` package — like `import mcp.types` or `from mcp.server.stdio import stdio_server` — those still work. FastMCP includes `mcp` as a dependency, so nothing breaks.
FastMCP now builds on MCP SDK v2. The `mcp.types` module no longer exists — protocol types moved to a standalone `mcp_types` package, and the field names were renamed from camelCase to snake_case (`inputSchema` → `input_schema`, `mimeType` → `mime_type`, and so on). FastMCP re-exports the types you're most likely to use from `fastmcp.types`, so update `from mcp.types import X` to `from fastmcp.types import X`. For the full picture, see [Upgrading to FastMCP on MCP SDK v2](/development/upgrading-to-mcp-sdk-v2).
Where FastMCP provides its own API for the same thing, it's worth switching over:
@ -124,7 +124,7 @@ Where FastMCP provides its own API for the same thing, it's worth switching over
| `mcp.types.PromptMessage(...)` | `from fastmcp.prompts import Message` |
| `from mcp.server.stdio import stdio_server` | Not needed — `mcp.run()` handles transport |
For anything without a FastMCP equivalent (e.g., specific protocol types you use directly), the `mcp.*` import is fine to keep.
For protocol types without a FastMCP equivalent, import them from `fastmcp.types` when re-exported there, otherwise from `mcp_types` directly.
### Decorated Functions

View file

@ -95,7 +95,7 @@ The connector must be explicitly enabled in each chat session through Developer
Use `annotations=ToolAnnotations(readOnlyHint=True)` to skip confirmation prompts for read-only tools:
```python
from mcp.types import ToolAnnotations
from fastmcp.types import ToolAnnotations
@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
def get_status() -> str:

View file

@ -331,14 +331,14 @@ Tools can customize which components are visible to their current session using
FastMCP automatically sends list change notifications when components (such as tools, resources, or prompts) are added, removed, enabled, or disabled. In rare cases where you need to manually trigger these notifications, you can use the context's notification methods:
```python
import mcp.types
import mcp_types
@mcp.tool
async def custom_tool_management(ctx: Context) -> str:
"""Example of manual notification after custom tool changes."""
await ctx.send_notification(mcp.types.ToolListChangedNotification())
await ctx.send_notification(mcp.types.ResourceListChangedNotification())
await ctx.send_notification(mcp.types.PromptListChangedNotification())
await ctx.send_notification(mcp_types.ToolListChangedNotification())
await ctx.send_notification(mcp_types.ResourceListChangedNotification())
await ctx.send_notification(mcp_types.PromptListChangedNotification())
return "Notifications sent"
```

View file

@ -15,7 +15,7 @@ Icons provide visual representations for your MCP servers and components, helpin
Icons use the standard MCP Icon type from the MCP protocol specification. Each icon specifies a source URL or data URI, and optionally includes MIME type and size information.
```python
from mcp.types import Icon
from fastmcp.types import Icon
icon = Icon(
src="https://example.com/icon.png",
@ -36,7 +36,7 @@ Add icons and a website URL to your server for display in client applications. M
```python
from fastmcp import FastMCP
from mcp.types import Icon
from fastmcp.types import Icon
mcp = FastMCP(
name="WeatherService",
@ -65,7 +65,7 @@ Icons can be added to individual tools, resources, resource templates, and promp
### Tool Icons
```python
from mcp.types import Icon
from fastmcp.types import Icon
@mcp.tool(
icons=[Icon(src="https://example.com/calculator-icon.png")]
@ -115,7 +115,7 @@ def analyze_code(code: str):
For small icons or when you want to embed the icon directly without external dependencies, use data URIs. This approach eliminates the need for hosting and ensures the icon is always available.
```python
from mcp.types import Icon
from fastmcp.types import Icon
from fastmcp.utilities.types import Image
# SVG icon as data URI
@ -135,7 +135,7 @@ def my_tool() -> str:
FastMCP provides the `Image` utility class to convert local image files into data URIs.
```python
from mcp.types import Icon
from fastmcp.types import Icon
from fastmcp.utilities.types import Image
# Generate a data URI from a local image file

View file

@ -265,8 +265,7 @@ async def on_list_prompts(self, context: MiddlewareContext, call_next):
Called when a client connects and initializes the session. This hook cannot modify the initialization response.
```python
from mcp import McpError
from mcp.types import ErrorData
from fastmcp.exceptions import McpError
async def on_initialize(self, context: MiddlewareContext, call_next):
client_info = context.message.params.get("clientInfo", {})
@ -274,7 +273,7 @@ async def on_initialize(self, context: MiddlewareContext, call_next):
# Reject before call_next to send error to client
if client_name == "blocked-client":
raise McpError(ErrorData(code=-32000, message="Client not supported"))
raise McpError(code=-32000, message="Client not supported")
await call_next(context)
print(f"Client {client_name} initialized")

View file

@ -84,7 +84,7 @@ Use model preferences when different tasks benefit from different model characte
For requests that need conversational context, construct a list of `SamplingMessage` objects representing the conversation history. Each message has a `role` ("user" or "assistant") and `content` (a `TextContent` object).
```python
from mcp.types import SamplingMessage, TextContent
from fastmcp.types import SamplingMessage, TextContent
from fastmcp import FastMCP, Context
mcp = FastMCP()
@ -354,7 +354,7 @@ Use `sample_step()` when you need to:
By default, `sample_step()` executes any tool calls and includes the results in the history. Call it in a loop, passing the updated history each time, until a stop condition is met.
```python
from mcp.types import SamplingMessage
from fastmcp.types import SamplingMessage
from fastmcp import FastMCP, Context
mcp = FastMCP()
@ -407,7 +407,7 @@ The contents of `step.history` depend on `execute_tools`:
Set `execute_tools=False` to handle tool execution yourself. When disabled, `step.history` contains the user message and the assistant's response with tool calls—but no tool results. You execute the tools and append the results as a user message.
```python
from mcp.types import SamplingMessage, ToolResultContent, TextContent
from fastmcp.types import SamplingMessage, ToolResultContent, TextContent
from fastmcp import FastMCP, Context
mcp = FastMCP()

View file

@ -723,7 +723,7 @@ For complete control over tool responses, return a `ToolResult` object. This giv
```python
from fastmcp.tools.tool import ToolResult
from mcp.types import TextContent
from fastmcp.types import TextContent
@mcp.tool
def advanced_tool() -> ToolResult:
@ -944,7 +944,7 @@ Annotations serve several purposes in client applications:
You can add annotations to a tool using the `annotations` parameter in the `@mcp.tool` decorator. FastMCP accepts either a plain dict or `ToolAnnotations`; the examples below use `ToolAnnotations` for consistency and stronger editor/type support.
```python
from mcp.types import ToolAnnotations
from fastmcp.types import ToolAnnotations
@mcp.tool(
annotations=ToolAnnotations(
@ -983,7 +983,7 @@ Mark a tool as read-only when it retrieves data, performs calculations, or check
```python
from fastmcp import FastMCP
from mcp.types import ToolAnnotations
from fastmcp.types import ToolAnnotations
mcp = FastMCP("Data Server")