Skip to content

Commit 3a6f299

Browse files
authored
docs: load media examples from disk instead of inline base64 (#3108)
1 parent ebcc4dc commit 3a6f299

6 files changed

Lines changed: 108 additions & 50 deletions

File tree

docs/servers/media.md

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,17 @@ The SDK ships two helpers for binary results (**`Image`** and **`Audio`**) and a
66

77
## Returning an image
88

9-
Annotate the return type as `Image` and return one:
9+
Annotate the return type as `Image`, point it at a file, and return it:
1010

11-
```python title="server.py" hl_lines="14 16"
11+
```python title="server.py" hl_lines="8 12 14"
1212
--8<-- "docs_src/media/tutorial001.py"
1313
```
1414

15-
* `Image` takes exactly one of `data` (raw bytes) or `path` (a file to read).
16-
* `format="png"` becomes the MIME type the client sees: `image/png`.
17-
* The bytes here are a one-pixel placeholder so the file runs on its own. In a real server they come from Pillow, matplotlib, a headless browser, or anything else that hands you `bytes`.
15+
* `Image` takes exactly one of `path` (a file to read) or `data` (raw bytes).
16+
* The MIME type the client sees is guessed from the suffix: `logo.png` is announced as `image/png`.
17+
* Nothing here is special about logos. Any PNG next to `server.py` works: a chart your code rendered, a diagram, a photo.
1818

19-
`Image` is an SDK convenience, not a protocol type. On the wire your return value becomes an **`ImageContent`** block (your bytes base64-encoded, plus the MIME type):
19+
`Image` is an SDK convenience, not a protocol type. On the wire your return value becomes an **`ImageContent`** block (the file's bytes base64-encoded, plus the MIME type):
2020

2121
```python
2222
result.content # [ImageContent(type="image", data="iVBORw0KGgoAAAANSUhEUg...", mime_type="image/png")]
@@ -25,7 +25,7 @@ result.structured_content # None
2525

2626
Two things to notice:
2727

28-
* `data` is base64. You returned raw `bytes`; the SDK did the encoding.
28+
* `data` is base64. You never touched the bytes; the SDK read the file and did the encoding.
2929
* `structured_content` is `None`. An `Image` is content for the model to look at, not data for the application to parse: there is no output schema. (Contrast **[Structured Output](structured-output.md)**, where the return annotation *is* the schema.)
3030

3131
!!! info
@@ -35,32 +35,40 @@ Two things to notice:
3535

3636
### Try it
3737

38+
Drop any PNG next to `server.py`, name it `logo.png`, and run:
39+
3840
```console
3941
uv run mcp dev server.py
4042
```
4143

42-
Open the **Tools** tab and call `logo`. The result is not a string: it is an `image` content block, and the Inspector renders it as a picture. You returned `bytes`; everything between that and the pixels on screen was the SDK.
44+
Open the **Tools** tab and call `logo`. The result is not a string: it is an `image` content block, and the Inspector renders your picture. Everything between the file on disk and the pixels on screen was the SDK.
4345

4446
## Returning audio
4547

46-
`Audio` is the same shape:
48+
`Audio` is the same shape. Keep `logo.png` where it was, and put any WAV beside it as `chime.wav`:
4749

48-
```python title="server.py" hl_lines="21-24"
50+
```python title="server.py" hl_lines="18-21"
4951
--8<-- "docs_src/media/tutorial002.py"
5052
```
5153

5254
The result is an **`AudioContent`** block:
5355

5456
```python
55-
result.content # [AudioContent(type="audio", data="UklGRjQAAABXQVZFZm1...", mime_type="audio/wav")]
57+
result.content # [AudioContent(type="audio", data="UklGR...", mime_type="audio/wav")]
5658
result.structured_content # None
5759
```
5860

59-
Same deal: raw bytes in, base64 and a MIME type out, no output schema.
61+
Same deal: a file on disk in, base64 and a MIME type out, no output schema.
6062

6163
## Bytes or a file
6264

63-
Both helpers also accept `path=` instead of `data=`. The file is read when the result is built, and the MIME type is guessed from the suffix:
65+
Both helpers also accept `data=` (raw bytes) instead of `path=`. That is the mode for bytes that never came from a file of their own — a database column, an HTTP response, something Pillow just drew:
66+
67+
```python title="server.py" hl_lines="14 15"
68+
--8<-- "docs_src/media/tutorial003.py"
69+
```
70+
71+
With `path=` there is nothing to declare: the file is read when the result is built, and the MIME type is guessed from the suffix:
6472

6573
* `Image`: `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`.
6674
* `Audio`: `.wav`, `.mp3`, `.ogg`, `.flac`, `.aac`, `.m4a`.
@@ -78,7 +86,7 @@ A suffix it doesn't recognise falls back to `application/octet-stream`.
7886
An `Icon` is metadata, not content. It doesn't carry the image; it points at one with a URI, and a client may fetch it and show it next to your server's name, a tool, a resource, or a prompt.
7987

8088
```python title="server.py" hl_lines="5-6 8 11 17"
81-
--8<-- "docs_src/media/tutorial003.py"
89+
--8<-- "docs_src/media/tutorial004.py"
8290
```
8391

8492
* `src` is a URI the client can resolve: `https:`, or a `data:` URI if you want the icon embedded with no extra fetch.
@@ -100,7 +108,7 @@ A tool's icons are on the `Tool` object from `tools/list`, a resource's on the `
100108
## Recap
101109

102110
* Return an `Image` or `Audio` from a tool and the client receives an `ImageContent` / `AudioContent` block: your bytes base64-encoded, with a MIME type.
103-
* Build one from in-memory `data=` plus an explicit `format=`, or from a `path=` and let the suffix decide.
111+
* Build one from a `path=` and let the suffix decide the MIME type, or from in-memory `data=` plus an explicit `format=`.
104112
* Media results carry no `structured_content` and no output schema.
105113
* An `Icon` is a pointer: a `src` URI plus optional `mime_type`, `sizes`, and `theme`.
106114
* `icons=[...]` works on the server, on tools, on resources, and on prompts, and clients find them on the matching objects.

docs_src/media/tutorial001.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
1-
import base64
1+
from pathlib import Path
22

33
from mcp.server import MCPServer
44
from mcp.server.mcpserver import Image
55

66
mcp = MCPServer("Brand kit")
77

8-
LOGO_PNG = base64.b64decode(
9-
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGOQ9bsBAAHPAURf8l/aAAAAAElFTkSuQmCC"
10-
)
8+
LOGO_FILE = Path(__file__).parent / "logo.png" # or the path to your file on disk
119

1210

1311
@mcp.tool()
1412
def logo() -> Image:
1513
"""The brand logo as a PNG."""
16-
return Image(data=LOGO_PNG, format="png")
14+
return Image(path=LOGO_FILE)

docs_src/media/tutorial002.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,21 @@
1-
import base64
1+
from pathlib import Path
22

33
from mcp.server import MCPServer
44
from mcp.server.mcpserver import Audio, Image
55

66
mcp = MCPServer("Brand kit")
77

8-
LOGO_PNG = base64.b64decode(
9-
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGOQ9bsBAAHPAURf8l/aAAAAAElFTkSuQmCC"
10-
)
11-
12-
CHIME_WAV = base64.b64decode("UklGRjQAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YRAAAAAAAAAAAAAAAAAAAAAAAAAA")
8+
LOGO_FILE = Path(__file__).parent / "logo.png"
9+
CHIME_FILE = Path(__file__).parent / "chime.wav"
1310

1411

1512
@mcp.tool()
1613
def logo() -> Image:
1714
"""The brand logo as a PNG."""
18-
return Image(data=LOGO_PNG, format="png")
15+
return Image(path=LOGO_FILE)
1916

2017

2118
@mcp.tool()
2219
def chime() -> Audio:
2320
"""The notification chime as a WAV."""
24-
return Audio(data=CHIME_WAV, format="wav")
21+
return Audio(path=CHIME_FILE)

docs_src/media/tutorial003.py

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,15 @@
1-
from mcp_types import Icon
1+
from pathlib import Path
22

33
from mcp.server import MCPServer
4+
from mcp.server.mcpserver import Image
45

5-
LOGO = Icon(src="https://example.com/brand-kit.png", mime_type="image/png", sizes=["48x48"])
6-
PALETTE = Icon(src="https://example.com/palette.svg", mime_type="image/svg+xml", sizes=["any"])
6+
mcp = MCPServer("Brand kit")
77

8-
mcp = MCPServer("Brand kit", icons=[LOGO])
8+
LOGO_FILE = Path(__file__).parent / "logo.png"
99

1010

11-
@mcp.tool(icons=[PALETTE])
12-
def palette() -> list[str]:
13-
"""The brand colour palette as hex codes."""
14-
return ["#1d4ed8", "#f59e0b", "#10b981"]
15-
16-
17-
@mcp.resource("brand://guidelines", icons=[LOGO])
18-
def guidelines() -> str:
19-
"""How to use the brand assets."""
20-
return "Use the primary colour for calls to action."
11+
@mcp.tool()
12+
def logo_from_bytes() -> Image:
13+
"""The brand logo as a PNG."""
14+
png = LOGO_FILE.read_bytes() # a database read, an HTTP response, Pillow output...
15+
return Image(data=png, format="png")

docs_src/media/tutorial004.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from mcp_types import Icon
2+
3+
from mcp.server import MCPServer
4+
5+
LOGO = Icon(src="https://example.com/brand-kit.png", mime_type="image/png", sizes=["48x48"])
6+
PALETTE = Icon(src="https://example.com/palette.svg", mime_type="image/svg+xml", sizes=["any"])
7+
8+
mcp = MCPServer("Brand kit", icons=[LOGO])
9+
10+
11+
@mcp.tool(icons=[PALETTE])
12+
def palette() -> list[str]:
13+
"""The brand colour palette as hex codes."""
14+
return ["#1d4ed8", "#f59e0b", "#10b981"]
15+
16+
17+
@mcp.resource("brand://guidelines", icons=[LOGO])
18+
def guidelines() -> str:
19+
"""How to use the brand assets."""
20+
return "Use the primary colour for calls to action."

tests/docs_src/test_media.py

Lines changed: 48 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,45 @@
11
"""`docs/servers/media.md`: every claim the page makes, proved against the real SDK."""
22

33
import base64
4+
from pathlib import Path
45

56
import pytest
67
from mcp_types import AudioContent, Icon, ImageContent
78

8-
from docs_src.media import tutorial001, tutorial002, tutorial003
9+
from docs_src.media import tutorial001, tutorial002, tutorial003, tutorial004
910
from mcp import Client
1011
from mcp.server.mcpserver import Audio, Image
1112

1213
# See test_index.py for why this is a per-module mark and not a conftest hook.
1314
pytestmark = [pytest.mark.anyio, pytest.mark.filterwarnings("error::mcp.MCPDeprecationWarning")]
1415

1516

16-
async def test_image_return_becomes_an_image_content_block() -> None:
17-
"""tutorial001: `-> Image` reaches the client as a base64 `ImageContent` block, not text."""
17+
@pytest.fixture
18+
def logo_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
19+
"""The PNG the tutorials expect next to `server.py`, fabricated on disk.
20+
21+
The SDK never parses the contents, so opaque bytes suffice.
22+
"""
23+
path = tmp_path / "logo.png"
24+
path.write_bytes(b"fake png data")
25+
monkeypatch.setattr(tutorial001, "LOGO_FILE", path)
26+
monkeypatch.setattr(tutorial002, "LOGO_FILE", path)
27+
monkeypatch.setattr(tutorial003, "LOGO_FILE", path)
28+
return path
29+
30+
31+
async def test_image_return_becomes_an_image_content_block(logo_file: Path) -> None:
32+
"""tutorial001: `-> Image` reaches the client as a base64 `ImageContent` block, not text,
33+
with the MIME type guessed from the `.png` suffix."""
1834
async with Client(tutorial001.mcp) as client:
1935
result = await client.call_tool("logo", {})
2036
assert not result.is_error
2137
assert result.content == [
22-
ImageContent(type="image", data=base64.b64encode(tutorial001.LOGO_PNG).decode(), mime_type="image/png")
38+
ImageContent(type="image", data=base64.b64encode(logo_file.read_bytes()).decode(), mime_type="image/png")
2339
]
2440

2541

42+
@pytest.mark.usefixtures("logo_file")
2643
async def test_image_result_has_no_structured_content_and_no_output_schema() -> None:
2744
"""tutorial001: media is content for the model, not data for the application."""
2845
async with Client(tutorial001.mcp) as client:
@@ -32,27 +49,50 @@ async def test_image_result_has_no_structured_content_and_no_output_schema() ->
3249
assert result.structured_content is None
3350

3451

35-
async def test_audio_return_becomes_an_audio_content_block() -> None:
52+
async def test_audio_return_becomes_an_audio_content_block(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
3653
"""tutorial002: `Audio` is the same shape as `Image`."""
54+
chime_file = tmp_path / "chime.wav"
55+
chime_file.write_bytes(b"fake wav data")
56+
monkeypatch.setattr(tutorial002, "CHIME_FILE", chime_file)
57+
3758
async with Client(tutorial002.mcp) as client:
3859
result = await client.call_tool("chime", {})
3960
assert not result.is_error
4061
assert result.content == [
41-
AudioContent(type="audio", data=base64.b64encode(tutorial002.CHIME_WAV).decode(), mime_type="audio/wav")
62+
AudioContent(type="audio", data=base64.b64encode(chime_file.read_bytes()).decode(), mime_type="audio/wav")
4263
]
4364
assert result.structured_content is None
4465

4566

67+
async def test_in_memory_bytes_with_a_format_become_the_same_image_content_block(logo_file: Path) -> None:
68+
"""tutorial003: `data=` plus `format=` produces the same wire block as `path=`."""
69+
async with Client(tutorial003.mcp) as client:
70+
result = await client.call_tool("logo_from_bytes", {})
71+
assert not result.is_error
72+
assert result.content == [
73+
ImageContent(type="image", data=base64.b64encode(logo_file.read_bytes()).decode(), mime_type="image/png")
74+
]
75+
76+
77+
def test_path_file_is_read_when_the_result_is_built() -> None:
78+
"""The page's `path=` claim (SDK-defined): the file is opened when the result is built,
79+
not when the helper is constructed — `server.py` can name a file that appears later."""
80+
image = Image(path="does-not-exist.png")
81+
with pytest.raises(FileNotFoundError):
82+
image.to_image_content()
83+
84+
4685
def test_raw_data_without_a_format_falls_back_to_a_default_mime_type() -> None:
4786
"""The `!!! check`: with `data=` there is no suffix to guess from, so `format=` decides."""
4887
assert Image(data=b"\x89PNG\r\n\x1a\n", format="png").to_image_content().mime_type == "image/png"
4988
assert Image(data=b"\x89PNG\r\n\x1a\n").to_image_content().mime_type == "image/png"
89+
assert Audio(data=b"\xff\xfb", format="wav").to_audio_content().mime_type == "audio/wav"
5090
assert Audio(data=b"\xff\xfb").to_audio_content().mime_type == "audio/wav"
5191

5292

5393
async def test_icons_are_visible_where_they_were_declared() -> None:
54-
"""tutorial003: server icons land on `server_info`, tool icons on the `Tool`, resource icons on the `Resource`."""
55-
async with Client(tutorial003.mcp) as client:
94+
"""tutorial004: server icons land on `server_info`, tool icons on the `Tool`, resource icons on the `Resource`."""
95+
async with Client(tutorial004.mcp) as client:
5696
assert client.server_info.icons == [
5797
Icon(src="https://example.com/brand-kit.png", mime_type="image/png", sizes=["48x48"])
5898
]

0 commit comments

Comments
 (0)