Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions docs/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,60 @@ app = Starlette(routes=[Mount("/", app=mcp.streamable_http_app(json_response=Tru

**Note:** DNS rebinding protection is automatically enabled when `host` is `127.0.0.1`, `localhost`, or `::1`. This now happens in `sse_app()` and `streamable_http_app()` instead of the constructor.

### Replace `RootModel` by union types with `TypeAdapter` validation

The following union types are no longer `RootModel` subclasses:

- `ClientRequest`
- `ServerRequest`
- `ClientNotification`
- `ServerNotification`
- `ClientResult`
- `ServerResult`
- `JSONRPCMessage`

This means you can no longer access `.root` on these types or use `model_validate()` directly on them. Instead, use the provided `TypeAdapter` instances for validation.

**Before (v1):**

```python
from mcp.types import ClientRequest, ServerNotification

# Using RootModel.model_validate()
request = ClientRequest.model_validate(data)
actual_request = request.root # Accessing the wrapped value

notification = ServerNotification.model_validate(data)
actual_notification = notification.root
```

**After (v2):**

```python
from mcp.types import client_request_adapter, server_notification_adapter

# Using TypeAdapter.validate_python()
request = client_request_adapter.validate_python(data)
# No .root access needed - request is the actual type

notification = server_notification_adapter.validate_python(data)
# No .root access needed - notification is the actual type
```

**Available adapters:**

| Union Type | Adapter |
|------------|---------|
| `ClientRequest` | `client_request_adapter` |
| `ServerRequest` | `server_request_adapter` |
| `ClientNotification` | `client_notification_adapter` |
| `ServerNotification` | `server_notification_adapter` |
| `ClientResult` | `client_result_adapter` |
| `ServerResult` | `server_result_adapter` |
| `JSONRPCMessage` | `jsonrpc_message_adapter` |

All adapters are exported from `mcp.types`.

### Resource URI type changed from `AnyUrl` to `str`

The `uri` field on resource-related types now uses `str` instead of Pydantic's `AnyUrl`. This aligns with the [MCP specification schema](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/schema/draft/schema.ts) which defines URIs as plain strings (`uri: string`) without strict URL validation. This change allows relative paths like `users/me` that were previously rejected.
Expand Down
23 changes: 14 additions & 9 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -125,18 +125,23 @@ extend-exclude = ["README.md"]

[tool.ruff.lint]
select = [
"C4", # flake8-comprehensions
"C90", # mccabe
"D212", # pydocstyle: multi-line docstring summary should start at the first line
"E", # pycodestyle
"F", # pyflakes
"I", # isort
"PERF", # Perflint
"PL", # Pylint
"UP", # pyupgrade
"C4", # flake8-comprehensions
"C90", # mccabe
"D212", # pydocstyle: multi-line docstring summary should start at the first line
"E", # pycodestyle
"F", # pyflakes
"I", # isort
"PERF", # Perflint
"PL", # Pylint
"UP", # pyupgrade
"TID251", # https://docs.astral.sh/ruff/rules/banned-api/
]
ignore = ["PERF203", "PLC0415", "PLR0402"]

[tool.ruff.lint.flake8-tidy-imports.banned-api]
"pydantic.RootModel".msg = "Use `pydantic.TypeAdapter` instead."


[tool.ruff.lint.mccabe]
max-complexity = 24 # Default is 10

Expand Down
6 changes: 3 additions & 3 deletions src/mcp/client/experimental/task_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ def build_capability(self) -> types.ClientTasksCapability | None:
def handles_request(request: types.ServerRequest) -> bool:
"""Check if this handler handles the given request type."""
return isinstance(
request.root,
request,
types.GetTaskRequest | types.GetTaskPayloadRequest | types.ListTasksRequest | types.CancelTaskRequest,
)

Expand All @@ -259,7 +259,7 @@ async def handle_request(
types.ClientResult | types.ErrorData
)

match responder.request.root:
match responder.request:
case types.GetTaskRequest(params=params):
response = await self.get_task(ctx, params)
client_response = client_response_type.validate_python(response)
Expand All @@ -281,7 +281,7 @@ async def handle_request(
await responder.respond(client_response)

case _: # pragma: no cover
raise ValueError(f"Unhandled request type: {type(responder.request.root)}")
raise ValueError(f"Unhandled request type: {type(responder.request)}")


# Backwards compatibility aliases
Expand Down
38 changes: 14 additions & 24 deletions src/mcp/client/experimental/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,15 +92,13 @@ async def call_tool_as_task(
_meta = types.RequestParams.Meta(**meta)

return await self._session.send_request(
types.ClientRequest(
types.CallToolRequest(
params=types.CallToolRequestParams(
name=name,
arguments=arguments,
task=types.TaskMetadata(ttl=ttl),
_meta=_meta,
),
)
types.CallToolRequest(
params=types.CallToolRequestParams(
name=name,
arguments=arguments,
task=types.TaskMetadata(ttl=ttl),
_meta=_meta,
),
),
types.CreateTaskResult,
)
Expand All @@ -115,10 +113,8 @@ async def get_task(self, task_id: str) -> types.GetTaskResult:
GetTaskResult containing the task status and metadata
"""
return await self._session.send_request(
types.ClientRequest(
types.GetTaskRequest(
params=types.GetTaskRequestParams(task_id=task_id),
)
types.GetTaskRequest(
params=types.GetTaskRequestParams(task_id=task_id),
),
types.GetTaskResult,
)
Expand All @@ -142,10 +138,8 @@ async def get_task_result(
The task result, validated against result_type
"""
return await self._session.send_request(
types.ClientRequest(
types.GetTaskPayloadRequest(
params=types.GetTaskPayloadRequestParams(task_id=task_id),
)
types.GetTaskPayloadRequest(
params=types.GetTaskPayloadRequestParams(task_id=task_id),
),
result_type,
)
Expand All @@ -164,9 +158,7 @@ async def list_tasks(
"""
params = types.PaginatedRequestParams(cursor=cursor) if cursor else None
return await self._session.send_request(
types.ClientRequest(
types.ListTasksRequest(params=params),
),
types.ListTasksRequest(params=params),
types.ListTasksResult,
)

Expand All @@ -180,10 +172,8 @@ async def cancel_task(self, task_id: str) -> types.CancelTaskResult:
CancelTaskResult with the updated task state
"""
return await self._session.send_request(
types.ClientRequest(
types.CancelTaskRequest(
params=types.CancelTaskRequestParams(task_id=task_id),
)
types.CancelTaskRequest(
params=types.CancelTaskRequestParams(task_id=task_id),
),
types.CancelTaskResult,
)
Expand Down
Loading