Skip to content
Open
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
14 changes: 13 additions & 1 deletion docs/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,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
78 changes: 46 additions & 32 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 @@ -2,27 +2,16 @@

from __future__ import annotations

import logging
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

logger = logging.getLogger(__name__)
Copy link
Member Author

Choose a reason for hiding this comment

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

Unnecessary logger.

from mcp.types._types import RequestParamsMeta


class Client:
Expand All @@ -42,8 +31,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 Down Expand Up @@ -150,9 +142,9 @@ def server_capabilities(self) -> types.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) -> types.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 @@ -169,19 +161,36 @@ 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: types.LoggingLevel,
*,
meta: RequestParamsMeta | None = None,
) -> types.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,
) -> types.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=types.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,
) -> types.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=types.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) -> types.ReadResourceResult:
"""Read a resource from the server.

Args:
Expand All @@ -190,15 +199,15 @@ async def read_resource(self, uri: str | AnyUrl) -> types.ReadResourceResult:
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) -> types.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) -> types.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 @@ -207,7 +216,7 @@ async def call_tool(
read_timeout_seconds: float | None = None,
progress_callback: ProgressFnT | None = None,
*,
meta: dict[str, Any] | None = None,
meta: RequestParamsMeta | None = None,
) -> types.CallToolResult:
"""Call a tool on the server.

Expand All @@ -229,9 +238,14 @@ 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,
) -> types.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=types.PaginatedRequestParams(cursor=cursor, _meta=meta))

async def get_prompt(self, name: str, arguments: dict[str, str] | None = None) -> types.GetPromptResult:
"""Get a prompt from the server.
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
49 changes: 30 additions & 19 deletions src/mcp/client/session.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.

Adding the meta parameter in the methods here is also not a breaking change, because they have a default value. Which means is just a feature.

Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import anyio.lowlevel
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
from pydantic import AnyUrl, TypeAdapter
from pydantic import TypeAdapter

import mcp.types as types
from mcp.client.experimental import ExperimentalClientFeatures
Expand All @@ -12,6 +12,7 @@
from mcp.shared.message import SessionMessage
from mcp.shared.session import BaseSession, ProgressFnT, RequestResponder
from mcp.shared.version import SUPPORTED_PROTOCOL_VERSIONS
from mcp.types._types import RequestParamsMeta

DEFAULT_CLIENT_INFO = types.Implementation(name="mcp", version="0.1.0")

Expand Down Expand Up @@ -216,16 +217,18 @@ def experimental(self) -> ExperimentalClientFeatures:
self._experimental_features = ExperimentalClientFeatures(self)
return self._experimental_features

async def send_ping(self) -> types.EmptyResult:
async def send_ping(self, *, meta: RequestParamsMeta | None = None) -> types.EmptyResult:
"""Send a ping request."""
return await self.send_request(types.PingRequest(), types.EmptyResult)
return await self.send_request(types.PingRequest(params=types.RequestParams(_meta=meta)), types.EmptyResult)

async def send_progress_notification(
self,
progress_token: str | int,
progress: float,
total: float | None = None,
message: str | None = None,
*,
meta: RequestParamsMeta | None = None,
) -> None:
"""Send a progress notification."""
await self.send_notification(
Expand All @@ -235,14 +238,20 @@ async def send_progress_notification(
progress=progress,
total=total,
message=message,
_meta=meta,
),
)
)

async def set_logging_level(self, level: types.LoggingLevel) -> types.EmptyResult:
async def set_logging_level(
self,
level: types.LoggingLevel,
*,
meta: RequestParamsMeta | None = None,
) -> types.EmptyResult:
"""Send a logging/setLevel request."""
return await self.send_request( # pragma: no cover
types.SetLevelRequest(params=types.SetLevelRequestParams(level=level)),
types.SetLevelRequest(params=types.SetLevelRequestParams(level=level, _meta=meta)),
types.EmptyResult,
)

Expand All @@ -267,24 +276,24 @@ async def list_resource_templates(
types.ListResourceTemplatesResult,
)

async def read_resource(self, uri: str | AnyUrl) -> types.ReadResourceResult:
async def read_resource(self, uri: str, *, meta: RequestParamsMeta | None = None) -> types.ReadResourceResult:
"""Send a resources/read request."""
return await self.send_request(
types.ReadResourceRequest(params=types.ReadResourceRequestParams(uri=str(uri))),
types.ReadResourceRequest(params=types.ReadResourceRequestParams(uri=uri, _meta=meta)),
types.ReadResourceResult,
)

async def subscribe_resource(self, uri: str | AnyUrl) -> types.EmptyResult:
async def subscribe_resource(self, uri: str, *, meta: RequestParamsMeta | None = None) -> types.EmptyResult:
"""Send a resources/subscribe request."""
return await self.send_request( # pragma: no cover
types.SubscribeRequest(params=types.SubscribeRequestParams(uri=str(uri))),
types.SubscribeRequest(params=types.SubscribeRequestParams(uri=uri, _meta=meta)),
types.EmptyResult,
)

async def unsubscribe_resource(self, uri: str | AnyUrl) -> types.EmptyResult:
async def unsubscribe_resource(self, uri: str, *, meta: RequestParamsMeta | None = None) -> types.EmptyResult:
"""Send a resources/unsubscribe request."""
return await self.send_request( # pragma: no cover
types.UnsubscribeRequest(params=types.UnsubscribeRequestParams(uri=str(uri))),
types.UnsubscribeRequest(params=types.UnsubscribeRequestParams(uri=uri, _meta=meta)),
types.EmptyResult,
)

Expand All @@ -295,17 +304,13 @@ async def call_tool(
read_timeout_seconds: float | None = None,
progress_callback: ProgressFnT | None = None,
*,
meta: dict[str, Any] | None = None,
meta: RequestParamsMeta | None = None,
) -> types.CallToolResult:
"""Send a tools/call request with optional progress callback support."""

_meta: types.RequestParams.Meta | None = None
if meta is not None:
_meta = types.RequestParams.Meta(**meta)

result = await self.send_request(
types.CallToolRequest(
params=types.CallToolRequestParams(name=name, arguments=arguments, _meta=_meta),
params=types.CallToolRequestParams(name=name, arguments=arguments, _meta=meta),
),
types.CallToolResult,
request_read_timeout_seconds=read_timeout_seconds,
Expand Down Expand Up @@ -351,11 +356,17 @@ async def list_prompts(self, *, params: types.PaginatedRequestParams | None = No
"""
return await self.send_request(types.ListPromptsRequest(params=params), types.ListPromptsResult)

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,
) -> types.GetPromptResult:
"""Send a prompts/get request."""
return await self.send_request(
types.GetPromptRequest(
params=types.GetPromptRequestParams(name=name, arguments=arguments),
params=types.GetPromptRequestParams(name=name, arguments=arguments, _meta=meta),
),
types.GetPromptResult,
)
Expand Down
Loading
Loading