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
2 changes: 1 addition & 1 deletion docs/client/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ That serves it at `http://localhost:8000/mcp`. The client is its own program. Sa
```

* `Client("http://localhost:8000/mcp")` is given a **URL**, so it connects over Streamable HTTP to the server you just started.
* `async with` is the **lifecycle**. Entering it connects and negotiates; leaving it disconnects. There is no `connect()` / `close()` pair, and a `Client` cannot be reused after the block ends.
* `async with` is the **lifecycle**. Entering the block connects and negotiates. Leaving it disconnects, including when an exception escapes the block. Create a new `Client` for another connection.
* Inside the block the connection facts are already there as plain properties.

### What you can pass to `Client`
Expand Down
8 changes: 5 additions & 3 deletions src/mcp/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,9 +479,11 @@ async def __aenter__(self) -> Client:

async def __aexit__(self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: Any) -> None:
"""Exit the async context manager."""
if self._exit_stack: # pragma: no branch
await self._exit_stack.__aexit__(exc_type, exc_val, exc_tb)
self._session = None
try:
if self._exit_stack: # pragma: no branch
await self._exit_stack.__aexit__(exc_type, exc_val, exc_tb)
finally:
self._session = None

@property
def session(self) -> ClientSession:
Expand Down
21 changes: 21 additions & 0 deletions tests/client/test_client_caching.py
Original file line number Diff line number Diff line change
Expand Up @@ -1572,3 +1572,24 @@ async def read(ctx: ServerRequestContext, params: types.ReadResourceRequestParam
await client.read_resource("memo://a")

assert len(fetched) == 5 # nothing was served from the cache and nothing reached the server


async def test_a_client_that_exits_with_an_exception_no_longer_serves_cached_tools() -> None:
"""SDK-defined: an exceptional exit propagates the error and ends cache access."""
server, fetches = _varying_tools_server()
client = Client(server, cache=CacheConfig(clock=_ManualClock()))
failure = RuntimeError("application error")

with pytest.RaisesGroup(
pytest.RaisesExc(RuntimeError, check=lambda exc: exc is failure), flatten_subgroups=True, allow_unwrapped=True
):
async with client:
assert _tool_names(await client.list_tools()) == ["t0"]
assert _tool_names(await client.list_tools()) == ["t0"]
assert fetches == [None]
raise failure

with pytest.raises(RuntimeError) as exc_info:
await client.list_tools()
assert str(exc_info.value) == snapshot("Client must be used within an async context manager")
assert fetches == [None]
Loading