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
1 change: 0 additions & 1 deletion docs/api.md

This file was deleted.

35 changes: 35 additions & 0 deletions docs/hooks/gen_ref_pages.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""Generate the code reference pages and navigation."""

from pathlib import Path

import mkdocs_gen_files

nav = mkdocs_gen_files.Nav()

root = Path(__file__).parent.parent.parent
src = root / "src"

for path in sorted(src.rglob("*.py")):
module_path = path.relative_to(src).with_suffix("")
doc_path = path.relative_to(src).with_suffix(".md")
full_doc_path = Path("api", doc_path)

parts = tuple(module_path.parts)

if parts[-1] == "__init__":
parts = parts[:-1]
doc_path = doc_path.with_name("index.md")
full_doc_path = full_doc_path.with_name("index.md")
elif parts[-1].startswith("_"):
continue

nav[parts] = doc_path.as_posix()

with mkdocs_gen_files.open(full_doc_path, "w") as fd:
ident = ".".join(parts)
fd.write(f"::: {ident}")

mkdocs_gen_files.set_edit_path(full_doc_path, path.relative_to(root))

with mkdocs_gen_files.open("api/SUMMARY.md", "w") as nav_file:
nav_file.writelines(nav.build_literate_nav())
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,4 @@ npx -y @modelcontextprotocol/inspector

## API Reference

Full API documentation is available in the [API Reference](api.md).
Full API documentation is available in the [API Reference](api/mcp/index.md).
26 changes: 25 additions & 1 deletion docs/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,30 @@ result = await session.list_resources(params=PaginatedRequestParams(cursor="next
result = await session.list_tools(params=PaginatedRequestParams(cursor="next_page_token"))
```

### `ClientSession.get_server_capabilities()` replaced by `initialize_result` property

`ClientSession` now stores the full `InitializeResult` via an `initialize_result` property. This provides access to `server_info`, `capabilities`, `instructions`, and the negotiated `protocol_version` through a single property. The `get_server_capabilities()` method has been removed.

**Before (v1):**

```python
capabilities = session.get_server_capabilities()
# server_info, instructions, protocol_version were not stored — had to capture initialize() return value
```

**After (v2):**

```python
result = session.initialize_result
if result is not None:
capabilities = result.capabilities
server_info = result.server_info
instructions = result.instructions
version = result.protocol_version
```

The high-level `Client.initialize_result` returns the same `InitializeResult` but is non-nullable — initialization is guaranteed inside the context manager, so no `None` check is needed. This replaces v1's `Client.server_capabilities`; use `client.initialize_result.capabilities` instead.

### `McpError` renamed to `MCPError`

The `McpError` exception class has been renamed to `MCPError` for consistent naming with the MCP acronym style used throughout the SDK.
Expand Down Expand Up @@ -859,6 +883,6 @@ The lowlevel `Server` also now exposes a `session_manager` property to access th

If you encounter issues during migration:

1. Check the [API Reference](api.md) for updated method signatures
1. Check the [API Reference](api/mcp/index.md) for updated method signatures
2. Review the [examples](https://github.com/modelcontextprotocol/python-sdk/tree/main/examples) for updated usage patterns
3. Open an issue on [GitHub](https://github.com/modelcontextprotocol/python-sdk/issues) if you find a bug or need further assistance
11 changes: 7 additions & 4 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ nav:
- Introduction: experimental/tasks.md
- Server Implementation: experimental/tasks-server.md
- Client Usage: experimental/tasks-client.md
- API Reference: api.md
- API Reference: api/

theme:
name: "material"
Expand Down Expand Up @@ -115,19 +115,22 @@ plugins:
- social:
enabled: !ENV [ENABLE_SOCIAL_CARDS, false]
- glightbox
- gen-files:
scripts:
- docs/hooks/gen_ref_pages.py
- literate-nav:
nav_file: SUMMARY.md
- mkdocstrings:
handlers:
python:
paths: [src/mcp]
paths: [src]
options:
relative_crossrefs: true
members_order: source
separate_signature: true
show_signature_annotations: true
signature_crossrefs: true
group_by_category: false
# 3 because docs are in pages with an H2 just above them
heading_level: 3
inventories:
- url: https://docs.python.org/3/objects.inv
- url: https://docs.pydantic.dev/latest/objects.inv
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ dev = [
]
docs = [
"mkdocs>=1.6.1",
"mkdocs-gen-files>=0.5.0",
"mkdocs-glightbox>=0.4.0",
"mkdocs-literate-nav>=0.6.1",
"mkdocs-material[imaging]>=9.5.45",
"mkdocstrings-python>=2.0.1",
]
Expand Down
15 changes: 11 additions & 4 deletions src/mcp/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
EmptyResult,
GetPromptResult,
Implementation,
InitializeResult,
ListPromptsResult,
ListResourcesResult,
ListResourceTemplatesResult,
Expand All @@ -29,7 +30,6 @@
ReadResourceResult,
RequestParamsMeta,
ResourceTemplateReference,
ServerCapabilities,
)


Expand Down Expand Up @@ -155,9 +155,16 @@ def session(self) -> ClientSession:
return self._session

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

Contains server_info, capabilities, instructions, and the negotiated protocol_version.
Raises RuntimeError if accessed outside the context manager.
"""
result = self.session.initialize_result
if result is None: # pragma: no cover
raise RuntimeError("Client must be used within an async context manager")
return result

async def send_ping(self, *, meta: RequestParamsMeta | None = None) -> EmptyResult:
"""Send a ping request to the server."""
Expand Down
13 changes: 7 additions & 6 deletions src/mcp/client/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def __init__(
self._logging_callback = logging_callback or _default_logging_callback
self._message_handler = message_handler or _default_message_handler
self._tool_output_schemas: dict[str, dict[str, Any] | None] = {}
self._server_capabilities: types.ServerCapabilities | None = None
self._initialize_result: types.InitializeResult | None = None
self._experimental_features: ExperimentalClientFeatures | None = None

# Experimental: Task handlers (use defaults if not provided)
Expand Down Expand Up @@ -185,18 +185,19 @@ async def initialize(self) -> types.InitializeResult:
if result.protocol_version not in SUPPORTED_PROTOCOL_VERSIONS:
raise RuntimeError(f"Unsupported protocol version from the server: {result.protocol_version}")

self._server_capabilities = result.capabilities
self._initialize_result = result

await self.send_notification(types.InitializedNotification())

return result

def get_server_capabilities(self) -> types.ServerCapabilities | None:
"""Return the server capabilities received during initialization.
@property
def initialize_result(self) -> types.InitializeResult | None:
"""The server's InitializeResult. None until initialize() has been called.

Returns None if the session has not been initialized yet.
Contains server_info, capabilities, instructions, and the negotiated protocol_version.
"""
return self._server_capabilities
return self._initialize_result

@property
def experimental(self) -> ExperimentalClientFeatures:
Expand Down
2 changes: 1 addition & 1 deletion src/mcp/server/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,7 @@ async def send_progress_notification(
related_request_id,
)

async def send_resource_list_changed(self) -> None: # pragma: no cover
async def send_resource_list_changed(self) -> None:
"""Send a resource list changed notification."""
await self.send_notification(types.ResourceListChangedNotification())

Expand Down
8 changes: 4 additions & 4 deletions src/mcp/server/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from mcp.shared.message import SessionMessage


@asynccontextmanager # pragma: no cover
@asynccontextmanager
async def websocket_server(scope: Scope, receive: Receive, send: Send):
"""WebSocket server transport for MCP. This is an ASGI application, suitable for use
with a framework like Starlette and a server like Hypercorn.
Expand All @@ -34,13 +34,13 @@ async def ws_reader():
async for msg in websocket.iter_text():
try:
client_message = types.jsonrpc_message_adapter.validate_json(msg, by_name=False)
except ValidationError as exc:
except ValidationError as exc: # pragma: no cover
await read_stream_writer.send(exc)
continue

session_message = SessionMessage(client_message)
await read_stream_writer.send(session_message)
except anyio.ClosedResourceError:
except anyio.ClosedResourceError: # pragma: no cover
await websocket.close()

async def ws_writer():
Expand All @@ -49,7 +49,7 @@ async def ws_writer():
async for session_message in write_stream_reader:
obj = session_message.message.model_dump_json(by_alias=True, exclude_unset=True)
await websocket.send_text(obj)
except anyio.ClosedResourceError:
except anyio.ClosedResourceError: # pragma: no cover
await websocket.close()

async with anyio.create_task_group() as tg:
Expand Down
20 changes: 18 additions & 2 deletions tests/client/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import pytest
from inline_snapshot import snapshot

from mcp import types
from mcp import MCPError, types
from mcp.client._memory import InMemoryTransport
from mcp.client.client import Client
from mcp.server import Server, ServerRequestContext
Expand Down Expand Up @@ -99,14 +99,15 @@ def greeting_prompt(name: str) -> str:
async def test_client_is_initialized(app: MCPServer):
"""Test that the client is initialized after entering context."""
async with Client(app) as client:
assert client.server_capabilities == snapshot(
assert client.initialize_result.capabilities == snapshot(
ServerCapabilities(
experimental={},
prompts=PromptsCapability(list_changed=False),
resources=ResourcesCapability(subscribe=False, list_changed=False),
tools=ToolsCapability(list_changed=False),
)
)
assert client.initialize_result.server_info.name == "test"


async def test_client_with_simple_server(simple_server: Server):
Expand Down Expand Up @@ -175,6 +176,21 @@ async def test_read_resource(app: MCPServer):
)


async def test_read_resource_error_propagates():
"""MCPError raised by a server handler propagates to the client with its code intact."""

async def handle_read_resource(
ctx: ServerRequestContext, params: types.ReadResourceRequestParams
) -> ReadResourceResult:
raise MCPError(code=404, message="no resource with that URI was found")

server = Server("test", on_read_resource=handle_read_resource)
async with Client(server) as client:
with pytest.raises(MCPError) as exc_info:
await client.read_resource("unknown://example")
assert exc_info.value.error.code == 404


async def test_get_prompt(app: MCPServer):
"""Test getting a prompt."""
async with Client(app) as client:
Expand Down
27 changes: 13 additions & 14 deletions tests/client/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,8 +540,8 @@ async def mock_server():


@pytest.mark.anyio
async def test_get_server_capabilities():
"""Test that get_server_capabilities returns None before init and capabilities after"""
async def test_initialize_result():
"""Test that initialize_result is None before init and contains the full result after."""
client_to_server_send, client_to_server_receive = anyio.create_memory_object_stream[SessionMessage](1)
server_to_client_send, server_to_client_receive = anyio.create_memory_object_stream[SessionMessage](1)

Expand All @@ -551,6 +551,8 @@ async def test_get_server_capabilities():
resources=types.ResourcesCapability(subscribe=True, list_changed=True),
tools=types.ToolsCapability(list_changed=False),
)
expected_server_info = Implementation(name="mock-server", version="0.1.0")
expected_instructions = "Use the tools wisely."

async def mock_server():
session_message = await client_to_server_receive.receive()
Expand All @@ -564,7 +566,8 @@ async def mock_server():
result = InitializeResult(
protocol_version=LATEST_PROTOCOL_VERSION,
capabilities=expected_capabilities,
server_info=Implementation(name="mock-server", version="0.1.0"),
server_info=expected_server_info,
instructions=expected_instructions,
)

async with server_to_client_send:
Expand All @@ -590,21 +593,17 @@ async def mock_server():
server_to_client_send,
server_to_client_receive,
):
assert session.get_server_capabilities() is None
assert session.initialize_result is None

tg.start_soon(mock_server)
await session.initialize()

capabilities = session.get_server_capabilities()
assert capabilities is not None
assert capabilities == expected_capabilities
assert capabilities.logging is not None
assert capabilities.prompts is not None
assert capabilities.prompts.list_changed is True
assert capabilities.resources is not None
assert capabilities.resources.subscribe is True
assert capabilities.tools is not None
assert capabilities.tools.list_changed is False
result = session.initialize_result
assert result is not None
assert result.server_info == expected_server_info
assert result.capabilities == expected_capabilities
assert result.instructions == expected_instructions
assert result.protocol_version == LATEST_PROTOCOL_VERSION


@pytest.mark.anyio
Expand Down
2 changes: 1 addition & 1 deletion tests/client/transports/test_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ async def test_with_mcpserver(mcpserver_server: MCPServer):
async def test_server_is_running(mcpserver_server: MCPServer):
"""Test that the server is running and responding to requests."""
async with Client(mcpserver_server) as client:
assert client.server_capabilities is not None
assert client.initialize_result.capabilities.tools is not None


async def test_list_tools(mcpserver_server: MCPServer):
Expand Down
Loading
Loading