Python: [Bug]: MCP sampling sends data URIs where MCP requires base64, and crashes on spec-compliant blob resources
Observed Behavior
Two related problems in how _mcp.py converts content for MCP sampling (server → client sampling/createMessage):
1. Sampling responses put a data URI in ImageContent.data / AudioContent.data / BlobResourceContents.blob.
The MCP spec says these fields hold plain base64. When the chat client returns Content.from_data(...), _prepare_content_for_mcp copies content.uri (data:image/png;base64,...) straight into the field, and a real MCP server can't decode it:
draw -> type=image data[:30]='data:image/png;base64,iVBORw0K' NOT valid base64: Only base64 data is allowed
2. A sampling request that has an EmbeddedResource with BlobResourceContents crashes.
_parse_content_from_mcp passes the raw base64 blob to Content.from_uri. That raises ContentError because the string has no URI scheme, so the server's whole tools/call fails and the chat client is never called:
tool_loop raised: ToolExecutionException("Failed to call tool 'tool_loop'.", ExceptionGroup('unhandled errors in a TaskGroup', [ContentError('URI must contain a scheme (e.g., http://, data:, file://)')]))
chat client reached for tool_loop: False
Expected Behavior
ImageContent.data/AudioContent.data/BlobResourceContents.blobhold plain base64 (e.g.iVBORw0K...), so the server can decode them.- Blob resources in sampling messages become data
Content, the same way the tool-result path already handles them.
Steps to Reproduce
- Connect
MCPStdioToolwith a chat client andsampling_approval_callbackto an MCP server whose tool does sampling. - (1) The chat client returns image content, and the server tries to base64-decode it.
- (2) The server sends a sampling message with a
ToolResultContentthat contains aBlobResourceContentswith a plain-base64blob.
Minimal Reproduction
Offline, no API keys needed. Run with the repo's dev environment.
MCP server (sampling_server.py):
import base64, warnings
from typing import Annotated
warnings.simplefilter("ignore")
from mcp import types
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.resolve import Resolve, Sample
server = MCPServer("sampler")
def ask_image():
return Sample([types.SamplingMessage(role="user", content=types.TextContent(type="text", text="draw"))], max_tokens=10)
@server.tool()
async def draw(r: Annotated[types.CreateMessageResult, Resolve(ask_image)]) -> str:
c = r.content
try:
raw = base64.b64decode(c.data, validate=True)
return f"type={c.type} data[:30]={c.data[:30]!r} decoded_ok len={len(raw)}"
except Exception as e:
return f"type={c.type} data[:30]={c.data[:30]!r} NOT valid base64: {e}"
def ask_with_blob():
blob = base64.b64encode(b"%PDF-1.4 fake").decode() # spec: blob is plain base64
msgs = [
types.SamplingMessage(role="user", content=types.TextContent(type="text", text="read the file")),
types.SamplingMessage(role="assistant", content=[types.ToolUseContent(type="tool_use", id="t1", name="fetch", input={})]),
types.SamplingMessage(role="user", content=[types.ToolResultContent(type="tool_result", tool_use_id="t1",
content=[types.EmbeddedResource(type="resource", resource=types.BlobResourceContents(
uri="file:///a.pdf", mime_type="application/pdf", blob=blob))])]),
]
return Sample(msgs, max_tokens=10, tools=[types.Tool(name="fetch", input_schema={"type": "object"})])
@server.tool()
async def tool_loop(r: Annotated[types.CreateMessageResultWithTools, Resolve(ask_with_blob)]) -> str:
return f"ok: {r.content}"
if __name__ == "__main__":
server.run("stdio")
Client (sampling_repro.py, in the same directory; run python sampling_repro.py):
import asyncio, sys, os, warnings, logging
warnings.simplefilter("ignore"); logging.disable(logging.CRITICAL)
from agent_framework import MCPStdioTool, Content, Message, ChatResponse
HERE = os.path.dirname(os.path.abspath(__file__))
PNG = b"\x89PNG\r\n\x1a\n" + b"\0" * 8
class FakeChat:
def __init__(self): self.seen = None
async def get_response(self, messages, options=None, **kw):
self.seen = messages
return ChatResponse(messages=[Message(role="assistant", contents=[Content.from_data(data=PNG, media_type="image/png")])], model="fake")
async def main():
chat = FakeChat()
t = MCPStdioTool(name="s", command=sys.executable, args=[f"{HERE}/sampling_server.py"],
client=chat, sampling_approval_callback=lambda p: True, load_prompts=False)
async with t:
fns = {f.name: f for f in t.functions}
r = await fns["draw"].invoke(arguments={})
print("draw ->", [c.text for c in r])
chat.seen = None
try:
r = await fns["tool_loop"].invoke(arguments={})
print("tool_loop ->", [c.text for c in r])
except Exception as e:
print("tool_loop raised:", type(e).__name__, repr(e)[:300])
print("chat client reached for tool_loop:", chat.seen is not None)
r = await fns["draw"].invoke(arguments={})
print("draw again ->", [c.text for c in r])
asyncio.run(asyncio.wait_for(main(), 30))
Root cause (what I found)
In agent_framework/_mcp.py:
_prepare_content_for_mcp(~lines 1645-1653):data=content.uri/blob=content.urisends the full data URI._parse_content_from_mcp(~lines 1612-1619): theBlobResourceContentsbranch passesmcp_type.resource.blobtoContent.from_uri. The tool-result parser (_parse_tool_result_from_mcp, ~lines 1489-1493) already adds thedata:{mime};base64,prefix; this path is missing it.
The existing unit tests for these helpers (test_mcp.py ~2245 and ~2296-2315) assert the data-URI form and pass a data URI as blob. So they lock in the current behaviour instead of what the spec says.
Possible fix
- Outgoing: strip the
data:<mime>;base64,prefix (e.g. fromcontent.get_data_bytes(), re-encoded) before fillingdata/blob. - Incoming: reuse the tool-result path's normalization: if
blobdoesn't start withdata:, wrap it. - Update the existing tests to use spec-shaped values.
I can open a PR with regression tests if this looks right.
Package Versions
agent-framework-core 1.25.0 (main @ 22b5e752), mcp 2.3.0
Python Version
3.13.11
Operating System
macOS
Regression
Unknown
Additional Context
AI assistance: the issue analysis, the repro scripts and this write-up were prepared with an AI coding assistant (Claude Code). The output shown above comes from running the repros against main @ 22b5e752.
Reproduced both problems on main @ 22b5e752 with my own minimal tests (not the issue's scripts); details in the Actions run.
_prepare_content_for_mcpputs the full data URI intoImageContent.data; base64 validation fails (binascii.Error)._parse_content_from_mcppasses a plain-base64BlobResourceContents.blobtoContent.from_uri, raisingContentError(no scheme); the tool-result path already adds the `(redacted) prefix.
Source: python/packages/core/agent_framework/_mcp.py.
Support boundary: unclear. The MCP spec defines these fields as base64, but I found no Agent Framework document stating the promise, so a maintainer should decide. Regression status and a known-good version are unknown. Routed to the core package owner; the triage label stays for a maintainer.
Generated by Issue Routing for #10290 · copilot · auto · ~20 AIC · ⌖ ~1 AIC · ⊞ 5.2K · ◷
I reproduced both parts on current main and have a small fix ready that I'd like to open as a PR once the direction is confirmed.
Root cause (python/packages/core/agent_framework/_mcp.py)
_prepare_content_for_mcpcopiescontent.uri(the fulldata:…;base64,…URI) intoImageContent.data,AudioContent.dataandBlobResourceContents.blob. The MCP spec defines these fields as plain base64._parse_content_from_mcppasses a plain-base64BlobResourceContents.blobstraight toContent.from_uri, which raisesContentErrorbecause there's no scheme. The tool-result path in the same file already adds thedata:{mime};base64,prefix.
Proposed fix (+20/−8 in _mcp.py)
- Outbound: send the base64 payload from the data URI (via the existing
_get_data_bytes_as_strhelper) instead of the URI. - Inbound: add the
data:prefix to blobs that don't already have one, mirroring the tool-result path. Blobs that already arrive as data URIs keep working.
Tests: three new tests in tests/core/test_mcp.py fail on main and pass with the fix: a plain-base64 blob, a sampling tool result containing a blob, and a from_data round trip that checks the output decodes with base64.b64decode(validate=True). Three existing tests asserted the data-URI output and are updated to expect plain base64. The test_mcp.py + test_mcp_skills.py run gives 1233 passed. ruff and pyright are clean.
Branch: https://github.com/Poyraxx/agent-framework/compare/main...fix/mcp-sampling-base64
The outbound part changes what the client sends to MCP servers. It goes from a data URI to spec-compliant base64, so please confirm that's the intended direction. I prepared the fix and tests with AI assistance and reviewed and verified them myself.