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
4 changes: 1 addition & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2119,8 +2119,6 @@ uv run client
import asyncio
import os

from pydantic import AnyUrl

from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client
from mcp.shared.context import RequestContext
Expand Down Expand Up @@ -2173,7 +2171,7 @@ async def run():
print(f"Available tools: {[t.name for t in tools.tools]}")

# Read a resource (greeting resource from fastmcp_quickstart)
resource_content = await session.read_resource(AnyUrl("greeting://World"))
resource_content = await session.read_resource("greeting://World")
content_block = resource_content.contents[0]
if isinstance(content_block, types.TextContent):
print(f"Resource content: {content_block.text}")
Expand Down
43 changes: 42 additions & 1 deletion docs/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,35 @@ notification = server_notification_adapter.validate_python(data)

All adapters are exported from `mcp.types`.

### `RequestParams.Meta` replaced with `RequestParamsMeta` TypedDict

The nested `RequestParams.Meta` Pydantic model class has been replaced with a top-level `RequestParamsMeta` TypedDict. This affects the `ctx.meta` field in request handlers and any code that imports or references this type.

**Key changes:**

- `RequestParams.Meta` (Pydantic model) → `RequestParamsMeta` (TypedDict)
- Attribute access (`meta.progress_token`) → Dictionary access (`meta.get("progress_token")`)
- `progress_token` field changed from `ProgressToken | None = None` to `NotRequired[ProgressToken]`
`

**In request context handlers:**

```python
# Before (v1)
@server.call_tool()
async def handle_tool(name: str, arguments: dict) -> list[TextContent]:
ctx = server.request_context
if ctx.meta and ctx.meta.progress_token:
await ctx.session.send_progress_notification(ctx.meta.progress_token, 0.5, 100)

# After (v2)
@server.call_tool()
async def handle_tool(name: str, arguments: dict) -> list[TextContent]:
ctx = server.request_context
if ctx.meta and "progress_token" in ctx.meta:
await ctx.session.send_progress_notification(ctx.meta["progress_token"], 0.5, 100)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

feels weird that it's key access but makes sense given you can add anything to meta. just weird vibes.

```

### 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 Expand Up @@ -274,7 +303,19 @@ Affected types:
- `UnsubscribeRequestParams.uri`
- `ResourceUpdatedNotificationParams.uri`

The `ClientSession.read_resource()`, `subscribe_resource()`, and `unsubscribe_resource()` methods now accept both `str` and `AnyUrl` for backwards compatibility.
The `Client` and `ClientSession` methods `read_resource()`, `subscribe_resource()`, and `unsubscribe_resource()` now only accept `str` for the `uri` parameter. If you were passing `AnyUrl` objects, convert them to strings:

```python
# Before (v1)
from pydantic import AnyUrl

await client.read_resource(AnyUrl("test://resource"))

# After (v2)
await client.read_resource("test://resource")
# Or if you have an AnyUrl from elsewhere:
await client.read_resource(str(my_any_url))
```

## Deprecations

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,9 @@ async def test_tool_with_progress(ctx: Context[ServerSession, None]) -> str:
await ctx.report_progress(progress=100, total=100, message="Completed step 100 of 100")

# Return progress token as string
progress_token = ctx.request_context.meta.progress_token if ctx.request_context and ctx.request_context.meta else 0
progress_token = (
ctx.request_context.meta.get("progress_token") if ctx.request_context and ctx.request_context.meta else 0
)
return str(progress_token)


Expand Down
4 changes: 1 addition & 3 deletions examples/snippets/clients/stdio_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
import asyncio
import os

from pydantic import AnyUrl

from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client
from mcp.shared.context import RequestContext
Expand Down Expand Up @@ -59,7 +57,7 @@ async def run():
print(f"Available tools: {[t.name for t in tools.tools]}")

# Read a resource (greeting resource from fastmcp_quickstart)
resource_content = await session.read_resource(AnyUrl("greeting://World"))
resource_content = await session.read_resource("greeting://World")
content_block = resource_content.contents[0]
if isinstance(content_block, types.TextContent):
print(f"Resource content: {content_block.text}")
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ dependencies = [
"jsonschema>=4.20.0",
"pywin32>=311; sys_platform == 'win32'",
"pyjwt[crypto]>=2.10.1",
"typing-extensions>=4.9.0",
"typing-extensions>=4.13.0",
"typing-inspection>=0.4.1",
]

Expand Down
108 changes: 69 additions & 39 deletions src/mcp/client/client.py
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes here are not breaking change.

Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,29 @@
from contextlib import AsyncExitStack
from typing import Any

from pydantic import AnyUrl

import mcp.types as types
from mcp.client._memory import InMemoryTransport
from mcp.client.session import (
ClientSession,
ElicitationFnT,
ListRootsFnT,
LoggingFnT,
MessageHandlerFnT,
SamplingFnT,
)
from mcp.client.session import ClientSession, ElicitationFnT, ListRootsFnT, LoggingFnT, MessageHandlerFnT, SamplingFnT
from mcp.server import Server
from mcp.server.fastmcp import FastMCP
from mcp.shared.session import ProgressFnT
from mcp.types import (
CallToolResult,
CompleteResult,
EmptyResult,
GetPromptResult,
Implementation,
ListPromptsResult,
ListResourcesResult,
ListResourceTemplatesResult,
ListToolsResult,
LoggingLevel,
PaginatedRequestParams,
PromptReference,
ReadResourceResult,
RequestParamsMeta,
ResourceTemplateReference,
ServerCapabilities,
)


class Client:
Expand All @@ -39,8 +47,11 @@ class Client:
def add(a: int, b: int) -> int:
return a + b

async with Client(server) as client:
result = await client.call_tool("add", {"a": 1, "b": 2})
async def main():
async with Client(server) as client:
result = await client.call_tool("add", {"a": 1, "b": 2})

asyncio.run(main())
```
"""

Expand All @@ -62,7 +73,7 @@ def __init__(
list_roots_callback: ListRootsFnT | None = None,
logging_callback: LoggingFnT | None = None,
message_handler: MessageHandlerFnT | None = None,
client_info: types.Implementation | None = None,
client_info: Implementation | None = None,
elicitation_callback: ElicitationFnT | None = None,
) -> None:
"""Initialize the client with a server.
Expand Down Expand Up @@ -143,13 +154,13 @@ def session(self) -> ClientSession:
return self._session

@property
def server_capabilities(self) -> types.ServerCapabilities | None:
def server_capabilities(self) -> ServerCapabilities | None:
"""The server capabilities received during initialization, or None if not yet initialized."""
return self.session.get_server_capabilities()

async def send_ping(self) -> types.EmptyResult:
async def send_ping(self, *, meta: RequestParamsMeta | None = None) -> EmptyResult:
"""Send a ping request to the server."""
return await self.session.send_ping()
return await self.session.send_ping(meta=meta)

async def send_progress_notification(
self,
Expand All @@ -166,36 +177,47 @@ async def send_progress_notification(
message=message,
)

async def set_logging_level(self, level: types.LoggingLevel) -> types.EmptyResult:
async def set_logging_level(self, level: LoggingLevel, *, meta: RequestParamsMeta | None = None) -> EmptyResult:
"""Set the logging level on the server."""
return await self.session.set_logging_level(level)
return await self.session.set_logging_level(level=level, meta=meta)

async def list_resources(self, *, cursor: str | None = None) -> types.ListResourcesResult:
async def list_resources(
self,
*,
cursor: str | None = None,
meta: RequestParamsMeta | None = None,
) -> ListResourcesResult:
"""List available resources from the server."""
return await self.session.list_resources(params=types.PaginatedRequestParams(cursor=cursor))
return await self.session.list_resources(params=PaginatedRequestParams(cursor=cursor, _meta=meta))

async def list_resource_templates(self, *, cursor: str | None = None) -> types.ListResourceTemplatesResult:
async def list_resource_templates(
self,
*,
cursor: str | None = None,
meta: RequestParamsMeta | None = None,
) -> ListResourceTemplatesResult:
"""List available resource templates from the server."""
return await self.session.list_resource_templates(params=types.PaginatedRequestParams(cursor=cursor))
return await self.session.list_resource_templates(params=PaginatedRequestParams(cursor=cursor, _meta=meta))

async def read_resource(self, uri: str | AnyUrl) -> types.ReadResourceResult:
async def read_resource(self, uri: str, *, meta: RequestParamsMeta | None = None) -> ReadResourceResult:
"""Read a resource from the server.

Args:
uri: The URI of the resource to read.
meta: Additional metadata for the request

Returns:
The resource content.
"""
return await self.session.read_resource(uri)
return await self.session.read_resource(uri, meta=meta)

async def subscribe_resource(self, uri: str | AnyUrl) -> types.EmptyResult:
async def subscribe_resource(self, uri: str, *, meta: RequestParamsMeta | None = None) -> EmptyResult:
"""Subscribe to resource updates."""
return await self.session.subscribe_resource(uri)
return await self.session.subscribe_resource(uri, meta=meta)

async def unsubscribe_resource(self, uri: str | AnyUrl) -> types.EmptyResult:
async def unsubscribe_resource(self, uri: str, *, meta: RequestParamsMeta | None = None) -> EmptyResult:
"""Unsubscribe from resource updates."""
return await self.session.unsubscribe_resource(uri)
return await self.session.unsubscribe_resource(uri, meta=meta)

async def call_tool(
self,
Expand All @@ -204,8 +226,8 @@ async def call_tool(
read_timeout_seconds: float | None = None,
progress_callback: ProgressFnT | None = None,
*,
meta: dict[str, Any] | None = None,
) -> types.CallToolResult:
meta: RequestParamsMeta | None = None,
) -> CallToolResult:
"""Call a tool on the server.

Args:
Expand All @@ -226,28 +248,36 @@ async def call_tool(
meta=meta,
)

async def list_prompts(self, *, cursor: str | None = None) -> types.ListPromptsResult:
async def list_prompts(
self,
*,
cursor: str | None = None,
meta: RequestParamsMeta | None = None,
) -> ListPromptsResult:
"""List available prompts from the server."""
return await self.session.list_prompts(params=types.PaginatedRequestParams(cursor=cursor))
return await self.session.list_prompts(params=PaginatedRequestParams(cursor=cursor, _meta=meta))

async def get_prompt(self, name: str, arguments: dict[str, str] | None = None) -> types.GetPromptResult:
async def get_prompt(
self, name: str, arguments: dict[str, str] | None = None, *, meta: RequestParamsMeta | None = None
) -> GetPromptResult:
"""Get a prompt from the server.

Args:
name: The name of the prompt
arguments: Arguments to pass to the prompt
meta: Additional metadata for the request

Returns:
The prompt content.
"""
return await self.session.get_prompt(name=name, arguments=arguments)
return await self.session.get_prompt(name=name, arguments=arguments, meta=meta)

async def complete(
self,
ref: types.ResourceTemplateReference | types.PromptReference,
ref: ResourceTemplateReference | PromptReference,
argument: dict[str, str],
context_arguments: dict[str, str] | None = None,
) -> types.CompleteResult:
) -> CompleteResult:
"""Get completions for a prompt or resource template argument.

Args:
Expand All @@ -260,9 +290,9 @@ async def complete(
"""
return await self.session.complete(ref=ref, argument=argument, context_arguments=context_arguments)

async def list_tools(self, *, cursor: str | None = None) -> types.ListToolsResult:
async def list_tools(self, *, cursor: str | None = None, meta: RequestParamsMeta | None = None) -> ListToolsResult:
"""List available tools from the server."""
return await self.session.list_tools(params=types.PaginatedRequestParams(cursor=cursor))
return await self.session.list_tools(params=PaginatedRequestParams(cursor=cursor, _meta=meta))

async def send_roots_list_changed(self) -> None:
"""Send a notification that the roots list has changed."""
Expand Down
13 changes: 4 additions & 9 deletions src/mcp/client/experimental/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

import mcp.types as types
from mcp.shared.experimental.tasks.polling import poll_until_terminal
from mcp.types._types import RequestParamsMeta

if TYPE_CHECKING:
from mcp.client.session import ClientSession
Expand All @@ -53,7 +54,7 @@ async def call_tool_as_task(
arguments: dict[str, Any] | None = None,
*,
ttl: int = 60000,
meta: dict[str, Any] | None = None,
meta: RequestParamsMeta | None = None,
) -> types.CreateTaskResult:
"""Call a tool as a task, returning a CreateTaskResult for polling.

Expand Down Expand Up @@ -87,17 +88,13 @@ async def call_tool_as_task(
# Get result
final = await session.experimental.get_task_result(task_id, CallToolResult)
"""
_meta: types.RequestParams.Meta | None = None
if meta is not None:
_meta = types.RequestParams.Meta(**meta)

return await self._session.send_request(
types.CallToolRequest(
params=types.CallToolRequestParams(
name=name,
arguments=arguments,
task=types.TaskMetadata(ttl=ttl),
_meta=_meta,
_meta=meta,
),
),
types.CreateTaskResult,
Expand All @@ -113,9 +110,7 @@ async def get_task(self, task_id: str) -> types.GetTaskResult:
GetTaskResult containing the task status and metadata
"""
return await self._session.send_request(
types.GetTaskRequest(
params=types.GetTaskRequestParams(task_id=task_id),
),
types.GetTaskRequest(params=types.GetTaskRequestParams(task_id=task_id)),
types.GetTaskResult,
)

Expand Down
Loading