Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

test server updates

Jeremiah Lowin5079945310e3
diff --git a/tests/test_server.py b/tests/test_server.py
index 950cf2246..6303cbaea 100644
--- a/tests/test_server.py
+++ b/tests/test_server.py
@@ -7,7 +7,13 @@ from mcp.shared.exceptions import McpError
from mcp.shared.memory import (
create_connected_server_and_client_session as client_session,
)
-from mcp.types import ImageContent, TextContent
+from mcp.types import (
+ ImageContent,
+ TextContent,
+ TextResourceContents,
+ BlobResourceContents,
+)
+from pydantic import AnyUrl
from fastmcp import Context, FastMCP
from fastmcp.prompts.base import EmbeddedResource, Message, UserMessage
@@ -100,7 +106,7 @@ class TestServerTools:
mcp.add_tool(tool_fn)
async with client_session(mcp._mcp_server) as client:
result = await client.call_tool("my_tool", {"arg1": "value"})
- assert "error" not in result
+ assert not hasattr(result, "error")
assert len(result.content) > 0
async def test_tool_exception_handling(self):
@@ -109,29 +115,43 @@ class TestServerTools:
async with client_session(mcp._mcp_server) as client:
result = await client.call_tool("error_tool_fn", {})
assert len(result.content) == 1
- assert result.content[0].type == "text"
- assert "Test error" in result.content[0].text
+ content = result.content[0]
+ assert isinstance(content, TextContent)
+ assert "Test error" in content.text
+ assert result.isError is True
+
+ async def test_tool_error_handling(self):
+ mcp = FastMCP()
+ mcp.add_tool(error_tool_fn)
+ async with client_session(mcp._mcp_server) as client:
+ result = await client.call_tool("error_tool_fn", {})
+ assert len(result.content) == 1
+ content = result.content[0]
+ assert isinstance(content, TextContent)
+ assert "Test error" in content.text
assert result.isError is True
- async def test_tool_exception_content(self):
+ async def test_tool_error_details(self):
"""Test that exception details are properly formatted in the response"""
mcp = FastMCP()
mcp.add_tool(error_tool_fn)
async with client_session(mcp._mcp_server) as client:
result = await client.call_tool("error_tool_fn", {})
- assert result.content[0].type == "text"
- assert isinstance(result.content[0].text, str)
- assert "Test error" in result.content[0].text
+ content = result.content[0]
+ assert isinstance(content, TextContent)
+ assert isinstance(content.text, str)
+ assert "Test error" in content.text
assert result.isError is True
- async def test_tool_text_conversion(self):
+ async def test_tool_return_value_conversion(self):
mcp = FastMCP()
mcp.add_tool(tool_fn)
async with client_session(mcp._mcp_server) as client:
result = await client.call_tool("tool_fn", {"x": 1, "y": 2})
assert len(result.content) == 1
- assert result.content[0].type == "text"
- assert result.content[0].text == "3"
+ content = result.content[0]
+ assert isinstance(content, TextContent)
+ assert content.text == "3"
async def test_tool_image_helper(self, tmp_path: Path):
# Create a test image
@@ -143,10 +163,12 @@ class TestServerTools:
async with client_session(mcp._mcp_server) as client:
result = await client.call_tool("image_tool_fn", {"path": str(image_path)})
assert len(result.content) == 1
- assert result.content[0].type == "image"
- assert result.content[0].mimeType == "image/png"
+ content = result.content[0]
+ assert isinstance(content, ImageContent)
+ assert content.type == "image"
+ assert content.mimeType == "image/png"
# Verify base64 encoding
- decoded = base64.b64decode(result.content[0].data)
+ decoded = base64.b64decode(content.data)
assert decoded == b"fake png data"
async def test_tool_mixed_content(self):
@@ -155,11 +177,13 @@ class TestServerTools:
async with client_session(mcp._mcp_server) as client:
result = await client.call_tool("mixed_content_tool_fn", {})
assert len(result.content) == 2
- assert result.content[0].type == "text"
- assert result.content[0].text == "Hello"
- assert result.content[1].type == "image"
- assert result.content[1].mimeType == "image/png"
- assert result.content[1].data == "abc"
+ content1 = result.content[0]
+ content2 = result.content[1]
+ assert isinstance(content1, TextContent)
+ assert content1.text == "Hello"
+ assert isinstance(content2, ImageContent)
+ assert content2.mimeType == "image/png"
+ assert content2.data == "abc"
async def test_tool_mixed_list_with_image(self, tmp_path: Path):
"""Test that lists containing Image objects and other types are handled correctly"""
@@ -181,18 +205,22 @@ class TestServerTools:
result = await client.call_tool("mixed_list_fn", {})
assert len(result.content) == 4
# Check text conversion
- assert result.content[0].type == "text"
- assert "text message" in result.content[0].text
+ content1 = result.content[0]
+ assert isinstance(content1, TextContent)
+ assert content1.text == "text message"
# Check image conversion
- assert result.content[1].type == "image"
- assert result.content[1].mimeType == "image/png"
- assert base64.b64decode(result.content[1].data) == b"test image data"
+ content2 = result.content[1]
+ assert isinstance(content2, ImageContent)
+ assert content2.mimeType == "image/png"
+ assert base64.b64decode(content2.data) == b"test image data"
# Check dict conversion
- assert result.content[2].type == "text"
- assert '"key": "value"' in result.content[2].text
+ content3 = result.content[2]
+ assert isinstance(content3, TextContent)
+ assert '"key": "value"' in content3.text
# Check direct TextContent
- assert result.content[3].type == "text"
- assert result.content[3].text == "direct content"
+ content4 = result.content[3]
+ assert isinstance(content4, TextContent)
+ assert content4.text == "direct content"
class TestServerResources:
@@ -202,11 +230,14 @@ class TestServerResources:
def get_text():
return "Hello, world!"
- resource = FunctionResource(uri="resource://test", name="test", fn=get_text)
+ resource = FunctionResource(
+ uri=AnyUrl("resource://test"), name="test", fn=get_text
+ )
mcp.add_resource(resource)
async with client_session(mcp._mcp_server) as client:
- result = await client.read_resource("resource://test")
+ result = await client.read_resource(AnyUrl("resource://test"))
+ assert isinstance(result.contents[0], TextResourceContents)
assert result.contents[0].text == "Hello, world!"
async def test_binary_resource(self):
@@ -216,16 +247,16 @@ class TestServerResources:
return b"Binary data"
resource = FunctionResource(
- uri="resource://binary",
+ uri=AnyUrl("resource://binary"),
name="binary",
fn=get_binary,
- is_binary=True,
mime_type="application/octet-stream",
)
mcp.add_resource(resource)
async with client_session(mcp._mcp_server) as client:
- result = await client.read_resource("resource://binary")
+ result = await client.read_resource(AnyUrl("resource://binary"))
+ assert isinstance(result.contents[0], BlobResourceContents)
assert result.contents[0].blob == base64.b64encode(b"Binary data").decode()
async def test_file_resource_text(self, tmp_path: Path):
@@ -235,11 +266,14 @@ class TestServerResources:
text_file = tmp_path / "test.txt"
text_file.write_text("Hello from file!")
- resource = FileResource(uri="file://test.txt", name="test.txt", path=text_file)
+ resource = FileResource(
+ uri=AnyUrl("file://test.txt"), name="test.txt", path=text_file
+ )
mcp.add_resource(resource)
async with client_session(mcp._mcp_server) as client:
- result = await client.read_resource("file://test.txt")
+ result = await client.read_resource(AnyUrl("file://test.txt"))
+ assert isinstance(result.contents[0], TextResourceContents)
assert result.contents[0].text == "Hello from file!"
async def test_file_resource_binary(self, tmp_path: Path):
@@ -250,16 +284,16 @@ class TestServerResources:
binary_file.write_bytes(b"Binary file data")
resource = FileResource(
- uri="file://test.bin",
+ uri=AnyUrl("file://test.bin"),
name="test.bin",
path=binary_file,
- is_binary=True,
mime_type="application/octet-stream",
)
mcp.add_resource(resource)
async with client_session(mcp._mcp_server) as client:
- result = await client.read_resource("file://test.bin")
+ result = await client.read_resource(AnyUrl("file://test.bin"))
+ assert isinstance(result.contents[0], BlobResourceContents)
assert (
result.contents[0].blob
== base64.b64encode(b"Binary file data").decode()
@@ -275,7 +309,7 @@ class TestServerResourceTemplates:
with pytest.raises(ValueError, match="Mismatch between URI parameters"):
@mcp.resource("resource://data")
- def get_data(param: str) -> str:
+ def get_data_fn(param: str) -> str:
return f"Data: {param}"
async def test_resource_with_uri_params(self):
@@ -305,7 +339,8 @@ class TestServerResourceTemplates:
return f"Data for {name}"
async with client_session(mcp._mcp_server) as client:
- result = await client.read_resource("resource://test/data")
+ result = await client.read_resource(AnyUrl("resource://test/data"))
+ assert isinstance(result.contents[0], TextResourceContents)
assert result.contents[0].text == "Data for test"
async def test_resource_mismatched_params(self):
@@ -327,7 +362,10 @@ class TestServerResourceTemplates:
return f"Data for {org}/{repo}"
async with client_session(mcp._mcp_server) as client:
- result = await client.read_resource("resource://cursor/fastmcp/data")
+ result = await client.read_resource(
+ AnyUrl("resource://cursor/fastmcp/data")
+ )
+ assert isinstance(result.contents[0], TextResourceContents)
assert result.contents[0].text == "Data for cursor/fastmcp"
async def test_resource_multiple_mismatched_params(self):
@@ -337,18 +375,19 @@ class TestServerResourceTemplates:
with pytest.raises(ValueError, match="Mismatch between URI parameters"):
@mcp.resource("resource://{org}/{repo}/data")
- def get_data(org: str, repo_2: str) -> str:
+ def get_data_mismatched(org: str, repo_2: str) -> str:
return f"Data for {org}"
"""Test that a resource with no parameters works as a regular resource"""
mcp = FastMCP()
@mcp.resource("resource://static")
- def get_data() -> str:
+ def get_static_data() -> str:
return "Static data"
async with client_session(mcp._mcp_server) as client:
- result = await client.read_resource("resource://static")
+ result = await client.read_resource(AnyUrl("resource://static"))
+ assert isinstance(result.contents[0], TextResourceContents)
assert result.contents[0].text == "Static data"
async def test_template_to_resource_conversion(self):
@@ -395,8 +434,10 @@ class TestContextInjection:
async with client_session(mcp._mcp_server) as client:
result = await client.call_tool("tool_with_context", {"x": 42})
assert len(result.content) == 1
- assert "Request" in result.content[0].text
- assert "42" in result.content[0].text
+ content = result.content[0]
+ assert isinstance(content, TextContent)
+ assert "Request" in content.text
+ assert "42" in content.text
async def test_async_context(self):
"""Test that context works in async functions."""
@@ -410,8 +451,10 @@ class TestContextInjection:
async with client_session(mcp._mcp_server) as client:
result = await client.call_tool("async_tool", {"x": 42})
assert len(result.content) == 1
- assert "Async request" in result.content[0].text
- assert "42" in result.content[0].text
+ content = result.content[0]
+ assert isinstance(content, TextContent)
+ assert "Async request" in content.text
+ assert "42" in content.text
async def test_context_logging(self):
"""Test that context logging methods work."""
@@ -428,7 +471,9 @@ class TestContextInjection:
async with client_session(mcp._mcp_server) as client:
result = await client.call_tool("logging_tool", {"msg": "test"})
assert len(result.content) == 1
- assert "Logged messages for test" in result.content[0].text
+ content = result.content[0]
+ assert isinstance(content, TextContent)
+ assert "Logged messages for test" in content.text
async def test_optional_context(self):
"""Test that context is optional."""
@@ -441,7 +486,9 @@ class TestContextInjection:
async with client_session(mcp._mcp_server) as client:
result = await client.call_tool("no_context", {"x": 21})
assert len(result.content) == 1
- assert result.content[0].text == "42"
+ content = result.content[0]
+ assert isinstance(content, TextContent)
+ assert content.text == "42"
async def test_context_resource_access(self):
"""Test that context can access resources."""
@@ -459,7 +506,9 @@ class TestContextInjection:
async with client_session(mcp._mcp_server) as client:
result = await client.call_tool("tool_with_resource", {})
assert len(result.content) == 1
- assert "Read resource: resource data" in result.content[0].text
+ content = result.content[0]
+ assert isinstance(content, TextContent)
+ assert "Read resource: resource data" in content.text
class TestServerPrompts:
@@ -477,23 +526,26 @@ class TestServerPrompts:
assert len(prompts) == 1
assert prompts[0].name == "fn"
# Don't compare functions directly since validate_call wraps them
- assert await prompts[0].render() == [
- UserMessage(content=TextContent(type="text", text="Hello, world!"))
- ]
+ content = await prompts[0].render()
+ assert isinstance(content[0].content, TextContent)
+ assert content[0].content.text == "Hello, world!"
- def test_prompt_decorator_with_name(self):
+ async def test_prompt_decorator_with_name(self):
"""Test prompt decorator with custom name."""
mcp = FastMCP()
- @mcp.prompt(name="custom")
+ @mcp.prompt(name="custom_name")
def fn() -> str:
return "Hello, world!"
prompts = mcp._prompt_manager.list_prompts()
assert len(prompts) == 1
- assert prompts[0].name == "custom"
+ assert prompts[0].name == "custom_name"
+ content = await prompts[0].render()
+ assert isinstance(content[0].content, TextContent)
+ assert content[0].content.text == "Hello, world!"
- def test_prompt_decorator_with_description(self):
+ async def test_prompt_decorator_with_description(self):
"""Test prompt decorator with custom description."""
mcp = FastMCP()
@@ -504,13 +556,16 @@ class TestServerPrompts:
prompts = mcp._prompt_manager.list_prompts()
assert len(prompts) == 1
assert prompts[0].description == "A custom description"
+ content = await prompts[0].render()
+ assert isinstance(content[0].content, TextContent)
+ assert content[0].content.text == "Hello, world!"
def test_prompt_decorator_error(self):
"""Test error when decorator is used incorrectly."""
mcp = FastMCP()
with pytest.raises(TypeError, match="decorator was used incorrectly"):
- @mcp.prompt
+ @mcp.prompt # type: ignore
def fn() -> str:
return "Hello, world!"
@@ -524,13 +579,16 @@ class TestServerPrompts:
async with client_session(mcp._mcp_server) as client:
result = await client.list_prompts()
+ assert result.prompts is not None
assert len(result.prompts) == 1
- assert result.prompts[0].name == "fn"
- assert len(result.prompts[0].arguments) == 2
- assert result.prompts[0].arguments[0].name == "name"
- assert result.prompts[0].arguments[0].required is True
- assert result.prompts[0].arguments[1].name == "optional"
- assert result.prompts[0].arguments[1].required is False
+ prompt = result.prompts[0]
+ assert prompt.name == "fn"
+ assert prompt.arguments is not None
+ assert len(prompt.arguments) == 2
+ assert prompt.arguments[0].name == "name"
+ assert prompt.arguments[0].required is True
+ assert prompt.arguments[1].name == "optional"
+ assert prompt.arguments[1].required is False
async def test_get_prompt(self):
"""Test getting a prompt through MCP protocol."""
@@ -543,9 +601,11 @@ class TestServerPrompts:
async with client_session(mcp._mcp_server) as client:
result = await client.get_prompt("fn", {"name": "World"})
assert len(result.messages) == 1
- assert result.messages[0].role == "user"
- assert result.messages[0].content.type == "text"
- assert result.messages[0].content.text == "Hello, World!"
+ message = result.messages[0]
+ assert message.role == "user"
+ content = message.content
+ assert isinstance(content, TextContent)
+ assert content.text == "Hello, World!"
async def test_get_prompt_with_resource(self):
"""Test getting a prompt that returns resource content."""
@@ -556,22 +616,25 @@ class TestServerPrompts:
return UserMessage(
content=EmbeddedResource(
type="resource",
- resource={
- "uri": "file://test.txt",
- "text": "File contents",
- "mimeType": "text/plain",
- },
+ resource=TextResourceContents(
+ uri=AnyUrl("file://file.txt"),
+ text="File contents",
+ mimeType="text/plain",
+ ),
)
)
async with client_session(mcp._mcp_server) as client:
result = await client.get_prompt("fn")
assert len(result.messages) == 1
- assert result.messages[0].role == "user"
- assert result.messages[0].content.type == "resource"
- assert str(result.messages[0].content.resource.uri) == "file://test.txt/"
- assert result.messages[0].content.resource.text == "File contents"
- assert result.messages[0].content.resource.mimeType == "text/plain"
+ message = result.messages[0]
+ assert message.role == "user"
+ content = message.content
+ assert isinstance(content, EmbeddedResource)
+ resource = content.resource
+ assert isinstance(resource, TextResourceContents)
+ assert resource.text == "File contents"
+ assert resource.mimeType == "text/plain"
async def test_get_unknown_prompt(self):
"""Test error when getting unknown prompt."""
@@ -585,9 +648,9 @@ class TestServerPrompts:
mcp = FastMCP()
@mcp.prompt()
- def fn(name: str) -> str:
+ def prompt_fn(name: str) -> str:
return f"Hello, {name}!"
async with client_session(mcp._mcp_server) as client:
with pytest.raises(McpError, match="Missing required arguments"):
- await client.get_prompt("fn")
+ await client.get_prompt("prompt_fn")