Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 5 additions & 1 deletion docs/advanced/apps.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,11 @@ canonical pattern is one tool, two answers. Look at `get_time` again:
`io.modelcontextprotocol/ui` extension **and** listed `text/html;profile=mcp-app`
in its `mimeTypes` settings. The field is required, so a client that omits it
does not count. That is exactly what `main()` in the same file declares: the
client half of the negotiation, and the rich answer comes back.
client half of the negotiation, and the rich answer comes back. `main()` hands
`Client` the `mcp` object so the file runs as-is, the way a test does
([Testing](../get-started/testing.md)). In a real client that argument is a URL or
`StdioServerParameters`, and the `extensions=[...]` declaration stays exactly the
same.

!!! warning
Never return a placeholder like `"[Rendered UI]"` as the only content. If the
Expand Down
15 changes: 10 additions & 5 deletions docs/advanced/extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,17 @@ The smallest useful extension is one tool and a settings map:
* The extension never receives the server. It declares contributions as data;
`MCPServer` consumes them. There is no `self.server` to mutate.

And `main()` is the proof, an in-memory client straight against `mcp`:
And `main()` is the proof, an in-memory client straight against `mcp`, the way a test
connects ([Testing](../get-started/testing.md)):

```python title="server.py" hl_lines="29-34"
--8<-- "docs_src/extensions/tutorial003.py"
```

Every `main()` on this page connects that way, so each file runs as-is. In your own
program the first argument to `Client` is a URL or `StdioServerParameters` and nothing
else changes.

### Serving your own methods

An extension can register **new request methods**: its own verbs, served next to the
Expand Down Expand Up @@ -158,7 +163,7 @@ A **client extension** is the same contract from the consuming side: a bundle of
client-side behaviour behind one identifier. Pass instances to
`Client(extensions=[...])` and call tools normally:

```python title="client.py" hl_lines="66-68"
```python hl_lines="66-68"
--8<-- "docs_src/extensions/tutorial006.py"
```

Expand All @@ -180,15 +185,15 @@ the capability, the client does nothing, as in the search client above), use
```python
from mcp.client import advertise

client = Client(mcp, extensions=[advertise("com.example/search")])
client = Client("https://example.com/mcp", extensions=[advertise("com.example/search")])
```

## Writing a client extension

Subclass `ClientExtension` and override only what you need. Three contribution
kinds, each with a default: `settings()`, `claims()`, and `notifications()`.

```python title="client.py" hl_lines="17-18 43-44 46-47"
```python hl_lines="17-18 43-44 46-47"
--8<-- "docs_src/extensions/tutorial006.py"
```

Expand Down Expand Up @@ -231,7 +236,7 @@ as in [Serving your own methods](#serving-your-own-methods). One addition: when
params key must ride the `Mcp-Name` header (extension specs such as tasks require
this for their verbs), the request type declares `name_param`:

```python title="client.py" hl_lines="22-25 46-47"
```python hl_lines="22-25 46-47"
--8<-- "docs_src/extensions/tutorial007.py"
```

Expand Down
18 changes: 12 additions & 6 deletions docs/advanced/low-level-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,22 @@ Three things changed, and they are the whole low-level API:

### Try it

There is no Inspector for this one: `mcp dev` and `mcp run` only accept an `MCPServer`. The in-memory `Client` doesn't care; it takes a low-level `Server` exactly like it takes an `MCPServer`:
`mcp dev` and `mcp run` only accept an `MCPServer`, so you serve this one yourself. The last line of `server.py` builds an ordinary ASGI app from it, and uvicorn runs that:

```python title="main.py"
```console
uvicorn server:app --port 8000
```

Point the Inspector, or any client, at `http://localhost:8000/mcp`:

```python title="client.py"
import asyncio

from mcp import Client

from server import server


async def main() -> None:
async with Client(server) as client:
async with Client("http://localhost:8000/mcp") as client:
result = await client.call_tool("search_books", {"query": "dune", "limit": 5})
print(result.content)

Expand All @@ -59,6 +63,8 @@ The same text the `@mcp.tool()` version produced. Two honest differences:
* `result.structured_content` is `None`. The high-level server wraps a `-> str` into `{"result": ...}` for you; here nobody builds what you didn't build.
* `list_tools` returns the schema **you** typed, character for character. The high-level version had `"title": "Query"` on every property and a `"title": "search_booksArguments"` at the root: Pydantic artifacts. Down here, if it's on the wire, you put it there.

In a test you skip uvicorn and the port: `Client(server)` takes a low-level `Server` in-process exactly like it takes an `MCPServer`, and **[Testing](../get-started/testing.md)** is that pattern.

## Nothing is checked for you

`MCPServer` rejects a bad argument before your function ever runs, validating the call against the schema it generated (**[Tools](../servers/tools.md)**).
Expand Down Expand Up @@ -210,4 +216,4 @@ Each of these is one idea you now have the vocabulary for; each has its own page
* `add_request_handler(method, params_type, handler)` serves any method. `initialize` is reserved.
* The capabilities a `Server` advertises are derived from which handlers you registered.

`Client(server)` treated both servers identically because they *are* the same protocol, which is the whole point. The next layer down isn't a class at all: it's **[Middleware](middleware.md)**.
The client treated both servers identically because they *are* the same protocol, which is the whole point. The next layer down isn't a class at all: it's **[Middleware](middleware.md)**.
4 changes: 2 additions & 2 deletions docs/advanced/pagination.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ Pagination is for the server whose resource list is really a database: thousands

### Try it

`Client(server)` connects to a low-level `Server` in memory exactly as it connects to an `MCPServer`.
In a test, `Client(server)` connects to a low-level `Server` in memory exactly as it connects to an `MCPServer` ([Testing](../get-started/testing.md)), and that is how the client loop below runs. In your own program you hand `Client` a URL or `StdioServerParameters` instead, and every call reads the same.

Call `list_resources()` with no arguments. You get ten resources, `book-1` through `book-10`, and `next_cursor` is the string `"10"`.

Expand All @@ -38,7 +38,7 @@ The tenth page comes back with `next_cursor` set to `None`. Done.

Every `list_*` method on `Client` (`list_tools`, `list_resources`, `list_resource_templates`, `list_prompts`) takes a `cursor=` keyword. Draining a paged list is one `while True`:

```python title="client.py" hl_lines="26-32"
```python hl_lines="26-32"
--8<-- "docs_src/pagination/tutorial002.py"
```

Expand Down
6 changes: 3 additions & 3 deletions docs/client/caching.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ One caveat on paginated lists: the protocol requires the **same `cacheScope` on

## What the client sees

On a 2026-07-28 session, `Client` honors the hints for you: it has a built-in response cache, on by default. A result that arrives carrying a `ttlMs` is stored, and an identical call within that TTL is served from the cache with no round trip. A result that carries *no* hint is not cached: hint-less results get `CacheConfig.default_ttl_ms`, which defaults to `0` (immediately stale), so a server that declares nothing sees exactly the call-for-call traffic it always did.
On a 2026-07-28 session, `Client` honors the hints for you: it has a built-in response cache, on by default. A result that arrives carrying a `ttlMs` is stored, and an identical call within that TTL is served from the cache with no round trip. A result that carries *no* hint is not cached: hint-less results get `CacheConfig.default_ttl_ms`, which defaults to `0` (immediately stale), so a server that declares nothing sees exactly the call-for-call traffic it always did. The demo below hands `Client` the server object and an injected clock so it runs as-is, the way a test does ([Testing](../get-started/testing.md)). In your own program that first argument is a URL or `StdioServerParameters`, and the calls read the same.
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved

```python title="client.py" hl_lines="33 35 38"
```python hl_lines="33 35 38"
--8<-- "docs_src/caching/tutorial003.py"
```

Expand All @@ -51,7 +51,7 @@ Four calls, three fetches. The second call found a fresh entry and never reached

One rule sits above `"use"`: **calls carrying `meta` always reach the server.** A request with `meta` set (a progress token, tracing fields) expects a wire request, so under `cache_mode="use"` it is treated as `"refresh"`: the cache read is skipped, and the fetched result still replaces the cached entry. `"bypass"` and an explicit `"refresh"` behave as they always do.

To turn caching off entirely, construct with `Client(server, cache=None)`: every call is a round trip again, and `cache_mode`, while still accepted, does nothing.
To turn caching off entirely, pass `cache=None` when constructing the `Client`: every call is a round trip again, and `cache_mode`, while still accepted, does nothing.

Scope is honored automatically too: `"private"` entries are keyed to the cache's *partition* (below), while `"public"` ones may opt into wider sharing. And **notifications beat TTL** for the exact entries they name: a `list_changed` notification evicts the matching cached listing, and `resources/updated` evicts the cached read stored under exactly its URI, however fresh they were. On a 2026-07-28 connection those notifications arrive on a `subscriptions/listen` stream you open with `client.listen(...)`, and eviction completes before your watcher sees the event; **[Subscriptions](subscriptions.md)** is that page.

Expand Down
4 changes: 2 additions & 2 deletions docs/client/callbacks.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ One `tools/call` from you, one `elicitation/create` back from the server, answer
`mode="legacy"` on the `Client(...)` call is doing real work. By default `Client(...)` negotiates the modern
protocol path, and that path has no back-channel for server-to-client requests: `ctx.elicit`
fails before your callback ever runs. The transport doesn't decide that; the negotiated
protocol does, in-memory and over a URL alike. Pin `mode="legacy"` whenever your client has
protocol does. Pin `mode="legacy"` whenever your client has
to answer one; every test behind this page does. **[Protocol versions](../protocol-versions.md)** has the whole story.

On a 2026-07-28 session the callback isn't dead, it's fed differently: when a tool returns an
Expand Down Expand Up @@ -146,4 +146,4 @@ Two more. Neither declares anything.
* `sampling_callback` and `list_roots_callback` work the same way but serve deprecated features; modern servers use multi-round-trip requests instead.
* `logging_callback` and `message_handler` receive notifications. They declare nothing.

The first argument to `Client(...)` is a transport object. **[Client transports](transports.md)** covers every kind.
The first argument to `Client(...)` picks the transport. **[Client transports](transports.md)** covers every kind.
30 changes: 21 additions & 9 deletions docs/client/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,39 @@ It is one object with one lifecycle: construct it, enter `async with`, call meth

## Your first client

```python title="client.py" hl_lines="14-18"
A client needs a server to talk to. This small one will do. Save it as `server.py` and leave it running over HTTP:

```python title="server.py"
--8<-- "docs_src/client/tutorial001.py"
```

The server at the top is only there so you have something to connect to. The client is the five highlighted lines.
```console
uv run mcp run server.py --transport streamable-http
```

The client is its own program:

* `Client(mcp)` is given the **server object itself**. That is the in-memory transport: no subprocess, no port, no HTTP. It is how every example on this page, and every test you write, connects.
```python title="client.py" hl_lines="7-11"
--8<-- "docs_src/client/tutorial001_client.py"
```

* `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.
* Inside the block the connection facts are already there as plain properties.

### What you can pass to `Client`

`Client` takes one positional argument and resolves the transport from its type:

* An `MCPServer` (or low-level `Server`) instance: connected **in-process**.
* A URL string (`Client("http://localhost:8000/mcp")`): Streamable HTTP, the production path.
* A `StdioServerParameters`: the command to launch as a **subprocess**, spoken to over its stdin and stdout.
* A URL string (`Client("http://localhost:8000/mcp")`): Streamable HTTP, the transport you deploy behind.
* A `StdioServerParameters`: the command to launch as a local **subprocess**, spoken to over its stdin and stdout.
* A **transport**: anything you can `async with ... as (read, write)`, such as `streamable_http_client(url, http_client=...)` around your own HTTP client.
* An `MCPServer` (or low-level `Server`) instance: connected **in-process**, with no subprocess and no port. That one is for tests, and **[Testing](../get-started/testing.md)** builds on it.

Everything else on this page is identical across all four. Headers, subprocesses, timeouts, and the `Transport` protocol get their own page: **[Client transports](transports.md)**.

The snippets below use the last form so that each one runs as-is: it builds its Bookshop server inline and hands it to `Client`, the way a test would. In your own program that argument is the URL or `StdioServerParameters` above.

### What's on a connected client

Four read-only properties, populated the moment you enter the block:
Expand Down Expand Up @@ -197,13 +209,13 @@ This loop is correct against every server. `MCPServer` returns everything in one

## In tests

`Client(mcp)` with no process and no port is already a test harness for your server.
`Client(mcp)`, the form the snippets above use, is already a test harness for your server: no process, no port.

There is one constructor flag built for that: `Client(mcp, raise_exceptions=True)`. It only has an effect on in-memory connections, and **[Testing](../get-started/testing.md)** is the page that explains it and builds the whole pattern around it.
There is one constructor flag built for that: `Client(mcp, raise_exceptions=True)`. It only has an effect on in-process connections, and **[Testing](../get-started/testing.md)** is the page that explains it and builds the whole pattern around it.

## Recap

* `Client(x)` connects in-memory to a server object, over Streamable HTTP to a URL string, and over anything else via a transport.
* `Client(x)` connects over Streamable HTTP to a URL string, launches a subprocess for a `StdioServerParameters`, enters a transport directly, and in tests takes the server object itself.
* `async with` is the whole lifecycle. Inside it, `server_capabilities` and `protocol_version` are already populated; `server_info` and `instructions` are too when the server provides them.
* `list_tools()` gives you each tool's `name`, `title`, `description` and `input_schema`.
* `call_tool()` returns `content` for the model, `structured_content` for your code, and `is_error`. A raising tool is a result, not an exception.
Expand Down
2 changes: 1 addition & 1 deletion docs/client/oauth-clients.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ You wrote none of it. Two keyword arguments remain (`client_metadata_url` and `v

### Try it

Most examples in these docs you can check with an in-memory `Client(server)`. Not this: the whole point of the flow is an HTTP `401`, and there is no HTTP between an in-memory client and its server.
The in-memory `Client(server)` your tests use is no help here: the whole point of the flow is an HTTP `401`, and there is no HTTP between an in-memory client and its server.

The repository ships the live version. `examples/servers/simple-auth/` runs a standalone authorization server and a protected MCP server; `examples/clients/simple-auth-client/` is this page's client grown into a small CLI. Its README has the two commands: start the servers, run the client against them, and you watch the four steps go by.

Expand Down
2 changes: 1 addition & 1 deletion docs/client/session-groups.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ If you already hold a connected `ClientSession` (`Client.session` is one), hand
## Recap

* `ClientSessionGroup` holds many server connections and merges their tools, resources, and prompts into one `dict` each.
* `connect_to_server(params)` per server. It takes transport parameters, never the server object or URL a `Client` takes.
* `connect_to_server(params)` per server. It takes transport parameters, never the URL or `Transport` a `Client` takes.
* `group.call_tool(name, arguments)` routes to the owning server for you.
* Names must be unique across the whole group; two servers with a `search` tool cannot coexist on their own.
* `component_name_hook=` rewrites every registered name. The dict key changes, the wire name does not.
Expand Down
Loading
Loading