mirror of
https://github.com/aljazceru/mcp-python-sdk.git
synced 2025-12-19 06:54:18 +01:00
refactor: standardize resource response format
Introduce ReadResourceContents type to properly handle MIME types in resource responses. Breaking change in FastMCP read_resource() return type. Github-Issue:#152
This commit is contained in:
@@ -6,6 +6,7 @@ from pydantic import AnyUrl
|
||||
from mcp import types
|
||||
from mcp.server.fastmcp import FastMCP
|
||||
from mcp.server.lowlevel import Server
|
||||
from mcp.server.lowlevel.helper_types import ReadResourceContents
|
||||
from mcp.shared.memory import (
|
||||
create_connected_server_and_client_session as client_session,
|
||||
)
|
||||
@@ -98,9 +99,11 @@ async def test_lowlevel_resource_mime_type():
|
||||
@server.read_resource()
|
||||
async def handle_read_resource(uri: AnyUrl):
|
||||
if str(uri) == "test://image":
|
||||
return (base64_string, "image/png")
|
||||
return ReadResourceContents(content=base64_string, mime_type="image/png")
|
||||
elif str(uri) == "test://image_bytes":
|
||||
return (bytes(image_bytes), "image/png")
|
||||
return ReadResourceContents(
|
||||
content=bytes(image_bytes), mime_type="image/png"
|
||||
)
|
||||
raise Exception(f"Resource not found: {uri}")
|
||||
|
||||
# Test that resources are listed with correct mime type
|
||||
|
||||
@@ -88,10 +88,10 @@ async def test_list_resources(mcp: FastMCP):
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_read_resource_dir(mcp: FastMCP):
|
||||
files, mime_type = await mcp.read_resource("dir://test_dir")
|
||||
assert mime_type == "text/plain"
|
||||
res = await mcp.read_resource("dir://test_dir")
|
||||
assert res.mime_type == "text/plain"
|
||||
|
||||
files = json.loads(files)
|
||||
files = json.loads(res.content)
|
||||
|
||||
assert sorted([Path(f).name for f in files]) == [
|
||||
"config.json",
|
||||
@@ -102,8 +102,8 @@ async def test_read_resource_dir(mcp: FastMCP):
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_read_resource_file(mcp: FastMCP):
|
||||
result, _ = await mcp.read_resource("file://test_dir/example.py")
|
||||
assert result == "print('hello world')"
|
||||
res = await mcp.read_resource("file://test_dir/example.py")
|
||||
assert res.content == "print('hello world')"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -119,5 +119,5 @@ async def test_delete_file_and_check_resources(mcp: FastMCP, test_dir: Path):
|
||||
await mcp.call_tool(
|
||||
"delete_file", arguments=dict(path=str(test_dir / "example.py"))
|
||||
)
|
||||
result, _ = await mcp.read_resource("file://test_dir/example.py")
|
||||
assert result == "File not found"
|
||||
res = await mcp.read_resource("file://test_dir/example.py")
|
||||
assert res.content == "File not found"
|
||||
|
||||
@@ -581,8 +581,8 @@ class TestContextInjection:
|
||||
|
||||
@mcp.tool()
|
||||
async def tool_with_resource(ctx: Context) -> str:
|
||||
data, mime_type = await ctx.read_resource("test://data")
|
||||
return f"Read resource: {data} with mime type {mime_type}"
|
||||
r = await ctx.read_resource("test://data")
|
||||
return f"Read resource: {r.content} with mime type {r.mime_type}"
|
||||
|
||||
async with client_session(mcp._mcp_server) as client:
|
||||
result = await client.call_tool("tool_with_resource", {})
|
||||
|
||||
109
tests/server/test_read_resource.py
Normal file
109
tests/server/test_read_resource.py
Normal file
@@ -0,0 +1,109 @@
|
||||
from pathlib import Path
|
||||
from tempfile import NamedTemporaryFile
|
||||
|
||||
import pytest
|
||||
from pydantic import AnyUrl, FileUrl
|
||||
|
||||
import mcp.types as types
|
||||
from mcp.server.lowlevel.server import ReadResourceContents, Server
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_file():
|
||||
"""Create a temporary file for testing."""
|
||||
with NamedTemporaryFile(mode="w", delete=False) as f:
|
||||
f.write("test content")
|
||||
path = Path(f.name).resolve()
|
||||
yield path
|
||||
try:
|
||||
path.unlink()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_read_resource_text(temp_file: Path):
|
||||
server = Server("test")
|
||||
|
||||
@server.read_resource()
|
||||
async def read_resource(uri: AnyUrl) -> ReadResourceContents:
|
||||
return ReadResourceContents(content="Hello World", mime_type="text/plain")
|
||||
|
||||
# Get the handler directly from the server
|
||||
handler = server.request_handlers[types.ReadResourceRequest]
|
||||
|
||||
# Create a request
|
||||
request = types.ReadResourceRequest(
|
||||
method="resources/read",
|
||||
params=types.ReadResourceRequestParams(uri=FileUrl(temp_file.as_uri())),
|
||||
)
|
||||
|
||||
# Call the handler
|
||||
result = await handler(request)
|
||||
assert isinstance(result.root, types.ReadResourceResult)
|
||||
assert len(result.root.contents) == 1
|
||||
|
||||
content = result.root.contents[0]
|
||||
assert isinstance(content, types.TextResourceContents)
|
||||
assert content.text == "Hello World"
|
||||
assert content.mimeType == "text/plain"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_read_resource_binary(temp_file: Path):
|
||||
server = Server("test")
|
||||
|
||||
@server.read_resource()
|
||||
async def read_resource(uri: AnyUrl) -> ReadResourceContents:
|
||||
return ReadResourceContents(
|
||||
content=b"Hello World", mime_type="application/octet-stream"
|
||||
)
|
||||
|
||||
# Get the handler directly from the server
|
||||
handler = server.request_handlers[types.ReadResourceRequest]
|
||||
|
||||
# Create a request
|
||||
request = types.ReadResourceRequest(
|
||||
method="resources/read",
|
||||
params=types.ReadResourceRequestParams(uri=FileUrl(temp_file.as_uri())),
|
||||
)
|
||||
|
||||
# Call the handler
|
||||
result = await handler(request)
|
||||
assert isinstance(result.root, types.ReadResourceResult)
|
||||
assert len(result.root.contents) == 1
|
||||
|
||||
content = result.root.contents[0]
|
||||
assert isinstance(content, types.BlobResourceContents)
|
||||
assert content.mimeType == "application/octet-stream"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_read_resource_default_mime(temp_file: Path):
|
||||
server = Server("test")
|
||||
|
||||
@server.read_resource()
|
||||
async def read_resource(uri: AnyUrl) -> ReadResourceContents:
|
||||
return ReadResourceContents(
|
||||
content="Hello World",
|
||||
# No mime_type specified, should default to text/plain
|
||||
)
|
||||
|
||||
# Get the handler directly from the server
|
||||
handler = server.request_handlers[types.ReadResourceRequest]
|
||||
|
||||
# Create a request
|
||||
request = types.ReadResourceRequest(
|
||||
method="resources/read",
|
||||
params=types.ReadResourceRequestParams(uri=FileUrl(temp_file.as_uri())),
|
||||
)
|
||||
|
||||
# Call the handler
|
||||
result = await handler(request)
|
||||
assert isinstance(result.root, types.ReadResourceResult)
|
||||
assert len(result.root.contents) == 1
|
||||
|
||||
content = result.root.contents[0]
|
||||
assert isinstance(content, types.TextResourceContents)
|
||||
assert content.text == "Hello World"
|
||||
assert content.mimeType == "text/plain"
|
||||
Reference in New Issue
Block a user