Skip to content

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

Convert provider tests to use direct server calls (#2748)

Jeremiah Lowin5f1aa274cc55
diff --git a/tests/server/providers/test_local_provider_prompts.py b/tests/server/providers/test_local_provider_prompts.py
index 57df3b11b..2afbd7d01 100644
--- a/tests/server/providers/test_local_provider_prompts.py
+++ b/tests/server/providers/test_local_provider_prompts.py
@@ -9,7 +9,8 @@ import pytest
from mcp.types import TextContent
from fastmcp import Client, Context, FastMCP
-from fastmcp.prompts.prompt import FunctionPrompt, Prompt
+from fastmcp.exceptions import NotFoundError
+from fastmcp.prompts.prompt import FunctionPrompt, Prompt, PromptResult
class TestPromptContext:
@@ -71,11 +72,11 @@ class TestPromptDecorator:
prompts = await mcp.get_prompts()
assert any(p.name == "fn" for p in prompts)
- async with Client(mcp) as client:
- result = await client.get_prompt("fn")
- assert len(result.messages) == 1
- assert isinstance(result.messages[0].content, TextContent)
- assert result.messages[0].content.text == "Hello, world!"
+ result = await mcp.render_prompt("fn")
+ assert isinstance(result, PromptResult)
+ assert len(result.messages) == 1
+ assert isinstance(result.messages[0].content, TextContent)
+ assert result.messages[0].content.text == "Hello, world!"
async def test_prompt_decorator_with_name(self):
mcp = FastMCP()
@@ -124,20 +125,21 @@ class TestPromptDecorator:
assert prompt.arguments[1].name == "greeting"
assert prompt.arguments[1].required is False
- async with Client(mcp) as client:
- result = await client.get_prompt("test_prompt", {"name": "World"})
- assert len(result.messages) == 1
- message = result.messages[0]
- assert isinstance(message.content, TextContent)
- assert message.content.text == "Hello, World!"
-
- result = await client.get_prompt(
- "test_prompt", {"name": "World", "greeting": "Hi"}
- )
- assert len(result.messages) == 1
- message = result.messages[0]
- assert isinstance(message.content, TextContent)
- assert message.content.text == "Hi, World!"
+ result = await mcp.render_prompt("test_prompt", {"name": "World"})
+ assert isinstance(result, PromptResult)
+ assert len(result.messages) == 1
+ message = result.messages[0]
+ assert isinstance(message.content, TextContent)
+ assert message.content.text == "Hello, World!"
+
+ result = await mcp.render_prompt(
+ "test_prompt", {"name": "World", "greeting": "Hi"}
+ )
+ assert isinstance(result, PromptResult)
+ assert len(result.messages) == 1
+ message = result.messages[0]
+ assert isinstance(message.content, TextContent)
+ assert message.content.text == "Hi, World!"
async def test_prompt_decorator_instance_method(self):
mcp = FastMCP()
@@ -152,12 +154,12 @@ class TestPromptDecorator:
obj = MyClass("My prefix:")
mcp.add_prompt(Prompt.from_function(obj.test_prompt, name="test_prompt"))
- async with Client(mcp) as client:
- result = await client.get_prompt("test_prompt")
- assert len(result.messages) == 1
- message = result.messages[0]
- assert isinstance(message.content, TextContent)
- assert message.content.text == "My prefix: Hello, world!"
+ result = await mcp.render_prompt("test_prompt")
+ assert isinstance(result, PromptResult)
+ assert len(result.messages) == 1
+ message = result.messages[0]
+ assert isinstance(message.content, TextContent)
+ assert message.content.text == "My prefix: Hello, world!"
async def test_prompt_decorator_classmethod(self):
mcp = FastMCP()
@@ -171,12 +173,12 @@ class TestPromptDecorator:
mcp.add_prompt(Prompt.from_function(MyClass.test_prompt, name="test_prompt"))
- async with Client(mcp) as client:
- result = await client.get_prompt("test_prompt")
- assert len(result.messages) == 1
- message = result.messages[0]
- assert isinstance(message.content, TextContent)
- assert message.content.text == "Class prefix: Hello, world!"
+ result = await mcp.render_prompt("test_prompt")
+ assert isinstance(result, PromptResult)
+ assert len(result.messages) == 1
+ message = result.messages[0]
+ assert isinstance(message.content, TextContent)
+ assert message.content.text == "Class prefix: Hello, world!"
async def test_prompt_decorator_classmethod_error(self):
mcp = FastMCP()
@@ -198,12 +200,12 @@ class TestPromptDecorator:
def test_prompt() -> str:
return "Static Hello, world!"
- async with Client(mcp) as client:
- result = await client.get_prompt("test_prompt")
- assert len(result.messages) == 1
- message = result.messages[0]
- assert isinstance(message.content, TextContent)
- assert message.content.text == "Static Hello, world!"
+ result = await mcp.render_prompt("test_prompt")
+ assert isinstance(result, PromptResult)
+ assert len(result.messages) == 1
+ message = result.messages[0]
+ assert isinstance(message.content, TextContent)
+ assert message.content.text == "Static Hello, world!"
async def test_prompt_decorator_async_function(self):
mcp = FastMCP()
@@ -212,12 +214,12 @@ class TestPromptDecorator:
async def test_prompt() -> str:
return "Async Hello, world!"
- async with Client(mcp) as client:
- result = await client.get_prompt("test_prompt")
- assert len(result.messages) == 1
- message = result.messages[0]
- assert isinstance(message.content, TextContent)
- assert message.content.text == "Async Hello, world!"
+ result = await mcp.render_prompt("test_prompt")
+ assert isinstance(result, PromptResult)
+ assert len(result.messages) == 1
+ message = result.messages[0]
+ assert isinstance(message.content, TextContent)
+ assert message.content.text == "Async Hello, world!"
async def test_prompt_decorator_with_tags(self):
"""Test that the prompt decorator properly sets tags."""
@@ -245,11 +247,11 @@ class TestPromptDecorator:
assert any(p.name == "string_named_prompt" for p in prompts)
assert not any(p.name == "my_function" for p in prompts)
- async with Client(mcp) as client:
- result = await client.get_prompt("string_named_prompt")
- assert len(result.messages) == 1
- assert isinstance(result.messages[0].content, TextContent)
- assert result.messages[0].content.text == "Hello from string named prompt!"
+ result = await mcp.render_prompt("string_named_prompt")
+ assert isinstance(result, PromptResult)
+ assert len(result.messages) == 1
+ assert isinstance(result.messages[0].content, TextContent)
+ assert result.messages[0].content.text == "Hello from string named prompt!"
async def test_prompt_direct_function_call(self):
"""Test that prompts can be registered via direct function call."""
@@ -267,11 +269,11 @@ class TestPromptDecorator:
prompt = next(p for p in prompts if p.name == "direct_call_prompt")
assert prompt is result_fn
- async with Client(mcp) as client:
- result = await client.get_prompt("direct_call_prompt")
- assert len(result.messages) == 1
- assert isinstance(result.messages[0].content, TextContent)
- assert result.messages[0].content.text == "Hello from direct call!"
+ result = await mcp.render_prompt("direct_call_prompt")
+ assert isinstance(result, PromptResult)
+ assert len(result.messages) == 1
+ assert isinstance(result.messages[0].content, TextContent)
+ assert result.messages[0].content.text == "Hello from direct call!"
async def test_prompt_decorator_conflicting_names_error(self):
"""Test that providing both positional and keyword names raises an error."""
@@ -296,12 +298,12 @@ class TestPromptDecorator:
def test_prompt() -> str:
return "Static Hello, world!"
- async with Client(mcp) as client:
- result = await client.get_prompt("test_prompt")
- assert len(result.messages) == 1
- message = result.messages[0]
- assert isinstance(message.content, TextContent)
- assert message.content.text == "Static Hello, world!"
+ result = await mcp.render_prompt("test_prompt")
+ assert isinstance(result, PromptResult)
+ assert len(result.messages) == 1
+ message = result.messages[0]
+ assert isinstance(message.content, TextContent)
+ assert message.content.text == "Static Hello, world!"
async def test_prompt_decorator_with_meta(self):
"""Test that meta parameter is passed through the prompt decorator."""
@@ -317,3 +319,155 @@ class TestPromptDecorator:
prompt = next(p for p in prompts if p.name == "test_prompt")
assert prompt.meta == meta_data
+
+
+class TestPromptEnabled:
+ async def test_toggle_enabled(self):
+ mcp = FastMCP()
+
+ @mcp.prompt
+ def sample_prompt() -> str:
+ return "Hello, world!"
+
+ prompts = await mcp.get_prompts()
+ assert any(p.name == "sample_prompt" for p in prompts)
+
+ mcp.disable(keys=["prompt:sample_prompt"])
+
+ prompts = await mcp.get_prompts()
+ assert not any(p.name == "sample_prompt" for p in prompts)
+
+ mcp.enable(keys=["prompt:sample_prompt"])
+
+ prompts = await mcp.get_prompts()
+ assert any(p.name == "sample_prompt" for p in prompts)
+
+ async def test_prompt_disabled(self):
+ mcp = FastMCP()
+
+ @mcp.prompt
+ def sample_prompt() -> str:
+ return "Hello, world!"
+
+ mcp.disable(keys=["prompt:sample_prompt"])
+ prompts = await mcp.get_prompts()
+ assert len(prompts) == 0
+
+ with pytest.raises(NotFoundError, match="Unknown prompt"):
+ await mcp.get_prompt("sample_prompt")
+
+ async def test_prompt_toggle_enabled(self):
+ mcp = FastMCP()
+
+ @mcp.prompt
+ def sample_prompt() -> str:
+ return "Hello, world!"
+
+ mcp.disable(keys=["prompt:sample_prompt"])
+ prompts = await mcp.get_prompts()
+ assert not any(p.name == "sample_prompt" for p in prompts)
+
+ mcp.enable(keys=["prompt:sample_prompt"])
+ prompts = await mcp.get_prompts()
+ assert len(prompts) == 1
+
+ async def test_prompt_toggle_disabled(self):
+ mcp = FastMCP()
+
+ @mcp.prompt
+ def sample_prompt() -> str:
+ return "Hello, world!"
+
+ mcp.disable(keys=["prompt:sample_prompt"])
+ prompts = await mcp.get_prompts()
+ assert len(prompts) == 0
+
+ with pytest.raises(NotFoundError, match="Unknown prompt"):
+ await mcp.get_prompt("sample_prompt")
+
+ async def test_get_prompt_and_disable(self):
+ mcp = FastMCP()
+
+ @mcp.prompt
+ def sample_prompt() -> str:
+ return "Hello, world!"
+
+ prompt = await mcp.get_prompt("sample_prompt")
+ assert prompt is not None
+
+ mcp.disable(keys=["prompt:sample_prompt"])
+ prompts = await mcp.get_prompts()
+ assert len(prompts) == 0
+
+ with pytest.raises(NotFoundError, match="Unknown prompt"):
+ await mcp.get_prompt("sample_prompt")
+
+ async def test_cant_get_disabled_prompt(self):
+ mcp = FastMCP()
+
+ @mcp.prompt
+ def sample_prompt() -> str:
+ return "Hello, world!"
+
+ mcp.disable(keys=["prompt:sample_prompt"])
+
+ with pytest.raises(NotFoundError, match="Unknown prompt"):
+ await mcp.get_prompt("sample_prompt")
+
+
+class TestPromptTags:
+ def create_server(self, include_tags=None, exclude_tags=None):
+ mcp = FastMCP(include_tags=include_tags, exclude_tags=exclude_tags)
+
+ @mcp.prompt(tags={"a", "b"})
+ def prompt_1() -> str:
+ return "1"
+
+ @mcp.prompt(tags={"b", "c"})
+ def prompt_2() -> str:
+ return "2"
+
+ return mcp
+
+ async def test_include_tags_all_prompts(self):
+ mcp = self.create_server(include_tags={"a", "b"})
+ prompts = await mcp.get_prompts()
+ assert {p.name for p in prompts} == {"prompt_1", "prompt_2"}
+
+ async def test_include_tags_some_prompts(self):
+ mcp = self.create_server(include_tags={"a"})
+ prompts = await mcp.get_prompts()
+ assert {p.name for p in prompts} == {"prompt_1"}
+
+ async def test_exclude_tags_all_prompts(self):
+ mcp = self.create_server(exclude_tags={"a", "b"})
+ prompts = await mcp.get_prompts()
+ assert {p.name for p in prompts} == set()
+
+ async def test_exclude_tags_some_prompts(self):
+ mcp = self.create_server(exclude_tags={"a"})
+ prompts = await mcp.get_prompts()
+ assert {p.name for p in prompts} == {"prompt_2"}
+
+ async def test_exclude_takes_precedence_over_include(self):
+ mcp = self.create_server(exclude_tags={"a"}, include_tags={"b"})
+ prompts = await mcp.get_prompts()
+ assert {p.name for p in prompts} == {"prompt_2"}
+
+ async def test_read_prompt_includes_tags(self):
+ mcp = self.create_server(include_tags={"a"})
+ prompt = await mcp.get_prompt("prompt_1")
+ result = await prompt.render({})
+ assert result.messages[0].content.text == "1"
+
+ with pytest.raises(NotFoundError, match="Unknown prompt"):
+ await mcp.get_prompt("prompt_2")
+
+ async def test_read_prompt_excludes_tags(self):
+ mcp = self.create_server(exclude_tags={"a"})
+ with pytest.raises(NotFoundError, match="Unknown prompt"):
+ await mcp.get_prompt("prompt_1")
+
+ prompt = await mcp.get_prompt("prompt_2")
+ result = await prompt.render({})
+ assert result.messages[0].content.text == "2"
diff --git a/tests/server/providers/test_local_provider_resources.py b/tests/server/providers/test_local_provider_resources.py
index 7b26c00fc..af42f8ddb 100644
--- a/tests/server/providers/test_local_provider_resources.py
+++ b/tests/server/providers/test_local_provider_resources.py
@@ -9,11 +9,11 @@ Tests cover:
"""
import pytest
-from mcp import McpError
-from mcp.types import BlobResourceContents, TextResourceContents
+from mcp.types import TextResourceContents
from pydantic import AnyUrl
from fastmcp import Client, Context, FastMCP
+from fastmcp.exceptions import NotFoundError
from fastmcp.resources import (
Resource,
ResourceContent,
@@ -81,10 +81,9 @@ class TestResourceTemplates:
def get_data(name: str) -> str:
return f"Data for {name}"
- async with Client(mcp) as client:
- result = await client.read_resource(AnyUrl("resource://test/data"))
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Data for test"
+ result = await mcp.read_resource("resource://test/data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Data for test"
async def test_resource_mismatched_params(self):
"""Test that mismatched parameters raise an error"""
@@ -107,12 +106,9 @@ class TestResourceTemplates:
def get_data(org: str, repo: str) -> str:
return f"Data for {org}/{repo}"
- async with Client(mcp) as client:
- result = await client.read_resource(
- AnyUrl("resource://cursor/fastmcp/data")
- )
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Data for cursor/fastmcp"
+ result = await mcp.read_resource("resource://cursor/fastmcp/data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Data for cursor/fastmcp"
async def test_resource_multiple_mismatched_params(self):
"""Test that mismatched parameters raise an error"""
@@ -135,10 +131,9 @@ class TestResourceTemplates:
def func(**kwargs: int) -> str:
return str(sum(int(v) for v in kwargs.values()))
- async with Client(mcp) as client:
- result = await client.read_resource(AnyUrl("test://1/2/3"))
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "6"
+ result = await mcp.read_resource("test://1/2/3")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "6"
async def test_template_with_default_params(self):
"""Test that a template can have default parameters."""
@@ -152,14 +147,13 @@ class TestResourceTemplates:
assert len(templates) == 1
assert templates[0].uri_template == "math://add/{x}"
- async with Client(mcp) as client:
- result = await client.read_resource(AnyUrl("math://add/5"))
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "15"
+ result = await mcp.read_resource("math://add/5")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "15"
- result2 = await client.read_resource(AnyUrl("math://add/7"))
- assert isinstance(result2[0], TextResourceContents)
- assert result2[0].text == "17"
+ result2 = await mcp.read_resource("math://add/7")
+ assert isinstance(result2, ResourceResult)
+ assert result2.contents[0].content == "17"
async def test_template_to_resource_conversion(self):
"""Test that a template can be converted to a resource."""
@@ -173,10 +167,9 @@ class TestResourceTemplates:
assert len(templates) == 1
assert templates[0].uri_template == "resource://{name}/data"
- async with Client(mcp) as client:
- result = await client.read_resource(AnyUrl("resource://test/data"))
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Data for test"
+ result = await mcp.read_resource("resource://test/data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Data for test"
async def test_template_decorator_with_tags(self):
mcp = FastMCP()
@@ -196,10 +189,9 @@ class TestResourceTemplates:
def template_resource(param: str) -> str:
return f"Template resource: {param}"
- async with Client(mcp) as client:
- result = await client.read_resource(AnyUrl("resource://test/data"))
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Template resource: test/data"
+ result = await mcp.read_resource("resource://test/data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Template resource: test/data"
async def test_template_with_query_params(self):
"""Test RFC 6570 query parameters in resource templates."""
@@ -209,20 +201,17 @@ class TestResourceTemplates:
def get_data(id: str, format: str = "json", limit: int = 10) -> str:
return f"id={id}, format={format}, limit={limit}"
- async with Client(mcp) as client:
- result = await client.read_resource(AnyUrl("data://123"))
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "id=123, format=json, limit=10"
+ result = await mcp.read_resource("data://123")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "id=123, format=json, limit=10"
- result = await client.read_resource(AnyUrl("data://123?format=xml"))
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "id=123, format=xml, limit=10"
+ result = await mcp.read_resource("data://123?format=xml")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "id=123, format=xml, limit=10"
- result = await client.read_resource(
- AnyUrl("data://123?format=csv&limit=50")
- )
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "id=123, format=csv, limit=50"
+ result = await mcp.read_resource("data://123?format=csv&limit=50")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "id=123, format=csv, limit=50"
async def test_templates_match_in_order_of_definition(self):
"""If a wildcard template is defined first, it will take priority."""
@@ -236,14 +225,13 @@ class TestResourceTemplates:
def template_resource_with_params(x: str, y: str) -> str:
return f"Template resource 2: {x}/{y}"
- async with Client(mcp) as client:
- result = await client.read_resource(AnyUrl("resource://a/b/c"))
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Template resource 1: a/b/c"
+ result = await mcp.read_resource("resource://a/b/c")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Template resource 1: a/b/c"
- result = await client.read_resource(AnyUrl("resource://a/b"))
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Template resource 1: a/b"
+ result = await mcp.read_resource("resource://a/b")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Template resource 1: a/b"
async def test_templates_shadow_each_other_reorder(self):
"""If a wildcard template is defined second, it will *not* take priority."""
@@ -257,17 +245,16 @@ class TestResourceTemplates:
def template_resource(param: str) -> str:
return f"Template resource 2: {param}"
- async with Client(mcp) as client:
- result = await client.read_resource(AnyUrl("resource://a/b/c"))
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Template resource 2: a/b/c"
+ result = await mcp.read_resource("resource://a/b/c")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Template resource 2: a/b/c"
- result = await client.read_resource(AnyUrl("resource://a/b"))
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Template resource 1: a/b"
+ result = await mcp.read_resource("resource://a/b")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Template resource 1: a/b"
async def test_resource_template_with_annotations(self):
- """Test that resource template annotations are visible to clients."""
+ """Test that resource template annotations are visible."""
mcp = FastMCP()
@mcp.resource(
@@ -277,18 +264,17 @@ class TestResourceTemplates:
def get_user(user_id: str) -> str:
return f"User {user_id} data"
- async with Client(mcp) as client:
- templates = await client.list_resource_templates()
- assert len(templates) == 1
+ templates = await mcp.get_resource_templates()
+ assert len(templates) == 1
- template = templates[0]
- assert template.uriTemplate == "api://users/{user_id}"
+ template = templates[0]
+ assert template.uri_template == "api://users/{user_id}"
- assert template.annotations is not None
- assert hasattr(template.annotations, "httpMethod")
- assert getattr(template.annotations, "httpMethod") == "GET"
- assert hasattr(template.annotations, "Cache-Control")
- assert getattr(template.annotations, "Cache-Control") == "no-cache"
+ assert template.annotations is not None
+ assert hasattr(template.annotations, "httpMethod")
+ assert getattr(template.annotations, "httpMethod") == "GET"
+ assert hasattr(template.annotations, "Cache-Control")
+ assert getattr(template.annotations, "Cache-Control") == "no-cache"
class TestResourceTemplateContext:
@@ -327,9 +313,8 @@ class TestResourceDecorator:
async def test_no_resources_before_decorator(self):
mcp = FastMCP()
- with pytest.raises(McpError, match="Unknown resource"):
- async with Client(mcp) as client:
- await client.read_resource("resource://data")
+ with pytest.raises(NotFoundError, match="Unknown resource"):
+ await mcp.read_resource("resource://data")
async def test_resource_decorator(self):
mcp = FastMCP()
@@ -338,10 +323,9 @@ class TestResourceDecorator:
def get_data() -> str:
return "Hello, world!"
- async with Client(mcp) as client:
- result = await client.read_resource("resource://data")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Hello, world!"
+ result = await mcp.read_resource("resource://data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Hello, world!"
async def test_resource_decorator_incorrect_usage(self):
mcp = FastMCP()
@@ -365,10 +349,9 @@ class TestResourceDecorator:
assert len(resources) == 1
assert resources[0].name == "custom-data"
- async with Client(mcp) as client:
- result = await client.read_resource("resource://data")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Hello, world!"
+ result = await mcp.read_resource("resource://data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Hello, world!"
async def test_resource_decorator_with_description(self):
mcp = FastMCP()
@@ -411,10 +394,9 @@ class TestResourceDecorator:
)
)
- async with Client(mcp) as client:
- result = await client.read_resource("resource://data")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "My prefix: Hello, world!"
+ result = await mcp.read_resource("resource://data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "My prefix: Hello, world!"
async def test_resource_decorator_classmethod(self):
mcp = FastMCP()
@@ -432,10 +414,9 @@ class TestResourceDecorator:
)
)
- async with Client(mcp) as client:
- result = await client.read_resource("resource://data")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Class prefix: Hello, world!"
+ result = await mcp.read_resource("resource://data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Class prefix: Hello, world!"
async def test_resource_decorator_classmethod_error(self):
mcp = FastMCP()
@@ -457,10 +438,9 @@ class TestResourceDecorator:
def get_data() -> str:
return "Static Hello, world!"
- async with Client(mcp) as client:
- result = await client.read_resource("resource://data")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Static Hello, world!"
+ result = await mcp.read_resource("resource://data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Static Hello, world!"
async def test_resource_decorator_async_function(self):
mcp = FastMCP()
@@ -469,10 +449,9 @@ class TestResourceDecorator:
async def get_data() -> str:
return "Async Hello, world!"
- async with Client(mcp) as client:
- result = await client.read_resource("resource://data")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Async Hello, world!"
+ result = await mcp.read_resource("resource://data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Async Hello, world!"
async def test_resource_decorator_staticmethod_order(self):
"""Test that both decorator orders work for static methods"""
@@ -484,10 +463,9 @@ class TestResourceDecorator:
def get_data() -> str:
return "Static Hello, world!"
- async with Client(mcp) as client:
- result = await client.read_resource("resource://data")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Static Hello, world!"
+ result = await mcp.read_resource("resource://data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Static Hello, world!"
async def test_resource_decorator_with_meta(self):
"""Test that meta parameter is passed through the resource decorator."""
@@ -505,7 +483,7 @@ class TestResourceDecorator:
assert resource.meta == meta_data
async def test_resource_content_with_meta_in_response(self):
- """Test that ResourceContent meta is passed through to MCP response."""
+ """Test that ResourceContent meta is passed through."""
mcp = FastMCP()
@mcp.resource("resource://widget")
@@ -520,14 +498,12 @@ class TestResourceDecorator:
]
)
- async with Client(mcp) as client:
- result = await client.read_resource("resource://widget")
- assert len(result) == 1
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "<widget>content</widget>"
- assert result[0].mimeType == "text/html"
- assert isinstance(result[0], TextResourceContents)
- assert result[0].meta == {"csp": "script-src 'self'", "version": "1.0"}
+ result = await mcp.read_resource("resource://widget")
+ assert isinstance(result, ResourceResult)
+ assert len(result.contents) == 1
+ assert result.contents[0].content == "<widget>content</widget>"
+ assert result.contents[0].mime_type == "text/html"
+ assert result.contents[0].meta == {"csp": "script-src 'self'", "version": "1.0"}
async def test_resource_content_binary_with_meta(self):
"""Test that ResourceContent with binary content and meta works."""
@@ -544,12 +520,11 @@ class TestResourceDecorator:
]
)
- async with Client(mcp) as client:
- result = await client.read_resource("resource://binary")
- assert len(result) == 1
- assert hasattr(result[0], "blob")
- assert isinstance(result[0], BlobResourceContents)
- assert result[0].meta == {"encoding": "raw"}
+ result = await mcp.read_resource("resource://binary")
+ assert isinstance(result, ResourceResult)
+ assert len(result.contents) == 1
+ assert result.contents[0].content == b"\x00\x01\x02"
+ assert result.contents[0].meta == {"encoding": "raw"}
async def test_resource_content_without_meta(self):
"""Test that ResourceContent without meta works (meta is None)."""
@@ -559,13 +534,11 @@ class TestResourceDecorator:
def get_plain() -> ResourceResult:
return ResourceResult([ResourceContent(content="plain content")])
- async with Client(mcp) as client:
- result = await client.read_resource("resource://plain")
- assert len(result) == 1
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "plain content"
- assert isinstance(result[0], TextResourceContents)
- assert result[0].meta is None
+ result = await mcp.read_resource("resource://plain")
+ assert isinstance(result, ResourceResult)
+ assert len(result.contents) == 1
+ assert result.contents[0].content == "plain content"
+ assert result.contents[0].meta is None
class TestTemplateDecorator:
@@ -581,10 +554,9 @@ class TestTemplateDecorator:
assert templates[0].name == "get_data"
assert templates[0].uri_template == "resource://{name}/data"
- async with Client(mcp) as client:
- result = await client.read_resource("resource://test/data")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Data for test"
+ result = await mcp.read_resource("resource://test/data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Data for test"
async def test_template_decorator_incorrect_usage(self):
mcp = FastMCP()
@@ -608,10 +580,9 @@ class TestTemplateDecorator:
assert len(templates) == 1
assert templates[0].name == "custom-template"
- async with Client(mcp) as client:
- result = await client.read_resource("resource://test/data")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Data for test"
+ result = await mcp.read_resource("resource://test/data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Data for test"
async def test_template_decorator_with_description(self):
mcp = FastMCP()
@@ -642,10 +613,9 @@ class TestTemplateDecorator:
)
mcp.add_template(template)
- async with Client(mcp) as client:
- result = await client.read_resource("resource://test/data")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "My prefix: Data for test"
+ result = await mcp.read_resource("resource://test/data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "My prefix: Data for test"
async def test_template_decorator_classmethod(self):
mcp = FastMCP()
@@ -664,10 +634,9 @@ class TestTemplateDecorator:
)
mcp.add_template(template)
- async with Client(mcp) as client:
- result = await client.read_resource("resource://test/data")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Class prefix: Data for test"
+ result = await mcp.read_resource("resource://test/data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Class prefix: Data for test"
async def test_template_decorator_staticmethod(self):
mcp = FastMCP()
@@ -678,10 +647,9 @@ class TestTemplateDecorator:
def get_data(name: str) -> str:
return f"Static Data for {name}"
- async with Client(mcp) as client:
- result = await client.read_resource("resource://test/data")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Static Data for test"
+ result = await mcp.read_resource("resource://test/data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Static Data for test"
async def test_template_decorator_async_function(self):
mcp = FastMCP()
@@ -690,10 +658,9 @@ class TestTemplateDecorator:
async def get_data(name: str) -> str:
return f"Async Data for {name}"
- async with Client(mcp) as client:
- result = await client.read_resource("resource://test/data")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Async Data for test"
+ result = await mcp.read_resource("resource://test/data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "Async Data for test"
async def test_template_decorator_with_tags(self):
"""Test that the template decorator properly sets tags."""
@@ -735,3 +702,303 @@ class TestTemplateDecorator:
)
assert template.meta == meta_data
+
+
+class TestResourceTags:
+ def create_server(self, include_tags=None, exclude_tags=None):
+ mcp = FastMCP(include_tags=include_tags, exclude_tags=exclude_tags)
+
+ @mcp.resource("resource://1", tags={"a", "b"})
+ def resource_1() -> str:
+ return "1"
+
+ @mcp.resource("resource://2", tags={"b", "c"})
+ def resource_2() -> str:
+ return "2"
+
+ return mcp
+
+ async def test_include_tags_all_resources(self):
+ mcp = self.create_server(include_tags={"a", "b"})
+ resources = await mcp.get_resources()
+ assert {r.name for r in resources} == {"resource_1", "resource_2"}
+
+ async def test_include_tags_some_resources(self):
+ mcp = self.create_server(include_tags={"a", "z"})
+ resources = await mcp.get_resources()
+ assert {r.name for r in resources} == {"resource_1"}
+
+ async def test_exclude_tags_all_resources(self):
+ mcp = self.create_server(exclude_tags={"a", "b"})
+ resources = await mcp.get_resources()
+ assert {r.name for r in resources} == set()
+
+ async def test_exclude_tags_some_resources(self):
+ mcp = self.create_server(exclude_tags={"a"})
+ resources = await mcp.get_resources()
+ assert {r.name for r in resources} == {"resource_2"}
+
+ async def test_exclude_precedence(self):
+ mcp = self.create_server(exclude_tags={"a"}, include_tags={"b"})
+ resources = await mcp.get_resources()
+ assert {r.name for r in resources} == {"resource_2"}
+
+ async def test_read_included_resource(self):
+ mcp = self.create_server(include_tags={"a"})
+ result = await mcp.read_resource("resource://1")
+ assert result.contents[0].content == "1"
+
+ with pytest.raises(NotFoundError, match="Unknown resource"):
+ await mcp.read_resource("resource://2")
+
+ async def test_read_excluded_resource(self):
+ mcp = self.create_server(exclude_tags={"a"})
+ with pytest.raises(NotFoundError, match="Unknown resource"):
+ await mcp.read_resource("resource://1")
+
+
+class TestResourceEnabled:
+ async def test_toggle_enabled(self):
+ mcp = FastMCP()
+
+ @mcp.resource("resource://data")
+ def sample_resource() -> str:
+ return "Hello, world!"
+
+ resources = await mcp.get_resources()
+ assert any(str(r.uri) == "resource://data" for r in resources)
+
+ mcp.disable(keys=["resource:resource://data"])
+
+ resources = await mcp.get_resources()
+ assert not any(str(r.uri) == "resource://data" for r in resources)
+
+ mcp.enable(keys=["resource:resource://data"])
+
+ resources = await mcp.get_resources()
+ assert any(str(r.uri) == "resource://data" for r in resources)
+
+ async def test_resource_disabled(self):
+ mcp = FastMCP()
+
+ @mcp.resource("resource://data")
+ def sample_resource() -> str:
+ return "Hello, world!"
+
+ mcp.disable(keys=["resource:resource://data"])
+ resources = await mcp.get_resources()
+ assert len(resources) == 0
+
+ with pytest.raises(NotFoundError, match="Unknown resource"):
+ await mcp.read_resource("resource://data")
+
+ async def test_resource_toggle_enabled(self):
+ mcp = FastMCP()
+
+ @mcp.resource("resource://data")
+ def sample_resource() -> str:
+ return "Hello, world!"
+
+ mcp.disable(keys=["resource:resource://data"])
+ resources = await mcp.get_resources()
+ assert not any(str(r.uri) == "resource://data" for r in resources)
+
+ mcp.enable(keys=["resource:resource://data"])
+ resources = await mcp.get_resources()
+ assert len(resources) == 1
+
+ async def test_resource_toggle_disabled(self):
+ mcp = FastMCP()
+
+ @mcp.resource("resource://data")
+ def sample_resource() -> str:
+ return "Hello, world!"
+
+ mcp.disable(keys=["resource:resource://data"])
+ resources = await mcp.get_resources()
+ assert len(resources) == 0
+
+ with pytest.raises(NotFoundError, match="Unknown resource"):
+ await mcp.read_resource("resource://data")
+
+ async def test_get_resource_and_disable(self):
+ mcp = FastMCP()
+
+ @mcp.resource("resource://data")
+ def sample_resource() -> str:
+ return "Hello, world!"
+
+ resource = await mcp.get_resource("resource://data")
+ assert resource is not None
+
+ mcp.disable(keys=["resource:resource://data"])
+ resources = await mcp.get_resources()
+ assert len(resources) == 0
+
+ with pytest.raises(NotFoundError, match="Unknown resource"):
+ await mcp.read_resource("resource://data")
+
+ async def test_cant_read_disabled_resource(self):
+ mcp = FastMCP()
+
+ @mcp.resource("resource://data")
+ def sample_resource() -> str:
+ return "Hello, world!"
+
+ mcp.disable(keys=["resource:resource://data"])
+
+ with pytest.raises(NotFoundError, match="Unknown resource"):
+ await mcp.read_resource("resource://data")
+
+
+class TestResourceTemplatesTags:
+ def create_server(self, include_tags=None, exclude_tags=None):
+ mcp = FastMCP(include_tags=include_tags, exclude_tags=exclude_tags)
+
+ @mcp.resource("resource://1/{param}", tags={"a", "b"})
+ def template_resource_1(param: str) -> str:
+ return f"Template resource 1: {param}"
+
+ @mcp.resource("resource://2/{param}", tags={"b", "c"})
+ def template_resource_2(param: str) -> str:
+ return f"Template resource 2: {param}"
+
+ return mcp
+
+ async def test_include_tags_all_resources(self):
+ mcp = self.create_server(include_tags={"a", "b"})
+ templates = await mcp.get_resource_templates()
+ assert {t.name for t in templates} == {
+ "template_resource_1",
+ "template_resource_2",
+ }
+
+ async def test_include_tags_some_resources(self):
+ mcp = self.create_server(include_tags={"a"})
+ templates = await mcp.get_resource_templates()
+ assert {t.name for t in templates} == {"template_resource_1"}
+
+ async def test_exclude_tags_all_resources(self):
+ mcp = self.create_server(exclude_tags={"a", "b"})
+ templates = await mcp.get_resource_templates()
+ assert {t.name for t in templates} == set()
+
+ async def test_exclude_tags_some_resources(self):
+ mcp = self.create_server(exclude_tags={"a"})
+ templates = await mcp.get_resource_templates()
+ assert {t.name for t in templates} == {"template_resource_2"}
+
+ async def test_exclude_takes_precedence_over_include(self):
+ mcp = self.create_server(exclude_tags={"a"}, include_tags={"b"})
+ templates = await mcp.get_resource_templates()
+ assert {t.name for t in templates} == {"template_resource_2"}
+
+ async def test_read_resource_template_includes_tags(self):
+ mcp = self.create_server(include_tags={"a"})
+ result = await mcp.read_resource("resource://1/x")
+ assert result.contents[0].content == "Template resource 1: x"
+
+ with pytest.raises(NotFoundError, match="Unknown resource"):
+ await mcp.read_resource("resource://2/x")
+
+ async def test_read_resource_template_excludes_tags(self):
+ mcp = self.create_server(exclude_tags={"a"})
+ with pytest.raises(NotFoundError, match="Unknown resource"):
+ await mcp.read_resource("resource://1/x")
+
+ result = await mcp.read_resource("resource://2/x")
+ assert result.contents[0].content == "Template resource 2: x"
+
+
+class TestResourceTemplateEnabled:
+ async def test_toggle_enabled(self):
+ mcp = FastMCP()
+
+ @mcp.resource("resource://{param}")
+ def sample_template(param: str) -> str:
+ return f"Template: {param}"
+
+ templates = await mcp.get_resource_templates()
+ assert any(t.uri_template == "resource://{param}" for t in templates)
+
+ mcp.disable(keys=["template:resource://{param}"])
+
+ templates = await mcp.get_resource_templates()
+ assert not any(t.uri_template == "resource://{param}" for t in templates)
+
+ mcp.enable(keys=["template:resource://{param}"])
+
+ templates = await mcp.get_resource_templates()
+ assert any(t.uri_template == "resource://{param}" for t in templates)
+
+ async def test_template_disabled(self):
+ mcp = FastMCP()
+
+ @mcp.resource("resource://{param}")
+ def sample_template(param: str) -> str:
+ return f"Template: {param}"
+
+ mcp.disable(keys=["template:resource://{param}"])
+ templates = await mcp.get_resource_templates()
+ assert len(templates) == 0
+
+ with pytest.raises(NotFoundError, match="Unknown resource"):
+ await mcp.read_resource("resource://test")
+
+ async def test_template_toggle_enabled(self):
+ mcp = FastMCP()
+
+ @mcp.resource("resource://{param}")
+ def sample_template(param: str) -> str:
+ return f"Template: {param}"
+
+ mcp.disable(keys=["template:resource://{param}"])
+ templates = await mcp.get_resource_templates()
+ assert not any(t.uri_template == "resource://{param}" for t in templates)
+
+ mcp.enable(keys=["template:resource://{param}"])
+ templates = await mcp.get_resource_templates()
+ assert len(templates) == 1
+
+ async def test_template_toggle_disabled(self):
+ mcp = FastMCP()
+
+ @mcp.resource("resource://{param}")
+ def sample_template(param: str) -> str:
+ return f"Template: {param}"
+
+ mcp.disable(keys=["template:resource://{param}"])
+ templates = await mcp.get_resource_templates()
+ assert len(templates) == 0
+
+ with pytest.raises(NotFoundError, match="Unknown resource"):
+ await mcp.read_resource("resource://test")
+
+ async def test_get_template_and_disable(self):
+ mcp = FastMCP()
+
+ @mcp.resource("resource://{param}")
+ def sample_template(param: str) -> str:
+ return f"Template: {param}"
+
+ template = await mcp.get_resource_template("resource://{param}")
+ assert template is not None
+
+ mcp.disable(keys=["template:resource://{param}"])
+ templates = await mcp.get_resource_templates()
+ assert len(templates) == 0
+
+ with pytest.raises(NotFoundError, match="Unknown resource"):
+ await mcp.read_resource("resource://test")
+
+ async def test_cant_read_disabled_template(self):
+ mcp = FastMCP()
+
+ @mcp.resource("resource://{param}")
+ def sample_template(param: str) -> str:
+ return f"Template: {param}"
+
+ mcp.disable(keys=["template:resource://{param}"])
+
+ with pytest.raises(NotFoundError, match="Unknown resource"):
+ await mcp.read_resource("resource://test")
diff --git a/tests/server/providers/test_local_provider_tools.py b/tests/server/providers/test_local_provider_tools.py
index b7527224f..9cca754c4 100644
--- a/tests/server/providers/test_local_provider_tools.py
+++ b/tests/server/providers/test_local_provider_tools.py
@@ -19,7 +19,6 @@ from pathlib import Path
from typing import Annotated, Any, Literal
import pytest
-from inline_snapshot import snapshot
from mcp.types import (
AudioContent,
BlobResourceContents,
@@ -30,9 +29,8 @@ from mcp.types import (
from pydantic import AnyUrl, BaseModel, Field, TypeAdapter
from typing_extensions import TypedDict
-from fastmcp import Client, Context, FastMCP
-from fastmcp.client.client import CallToolResult
-from fastmcp.exceptions import ToolError
+from fastmcp import Context, FastMCP
+from fastmcp.exceptions import NotFoundError
from fastmcp.tools.tool import Tool, ToolResult
from fastmcp.utilities.json_schema import compress_schema
from fastmcp.utilities.types import Audio, File, Image
@@ -151,9 +149,9 @@ class TestToolReturnTypes:
def string_tool() -> str:
return "Hello, world!"
- async with Client(mcp) as client:
- result = await client.call_tool("string_tool", {})
- assert result.data == "Hello, world!"
+ result = await mcp.call_tool("string_tool", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "Hello, world!"}
async def test_bytes(self, tmp_path: Path):
mcp = FastMCP()
@@ -162,9 +160,9 @@ class TestToolReturnTypes:
def bytes_tool() -> bytes:
return b"Hello, world!"
- async with Client(mcp) as client:
- result = await client.call_tool("bytes_tool", {})
- assert result.data == "Hello, world!"
+ result = await mcp.call_tool("bytes_tool", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "Hello, world!"}
async def test_uuid(self):
mcp = FastMCP()
@@ -175,9 +173,9 @@ class TestToolReturnTypes:
def uuid_tool() -> uuid.UUID:
return test_uuid
- async with Client(mcp) as client:
- result = await client.call_tool("uuid_tool", {})
- assert result.data == str(test_uuid)
+ result = await mcp.call_tool("uuid_tool", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": str(test_uuid)}
async def test_path(self):
mcp = FastMCP()
@@ -188,9 +186,9 @@ class TestToolReturnTypes:
def path_tool() -> Path:
return test_path
- async with Client(mcp) as client:
- result = await client.call_tool("path_tool", {})
- assert result.data == str(test_path)
+ result = await mcp.call_tool("path_tool", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": str(test_path)}
async def test_datetime(self):
mcp = FastMCP()
@@ -201,9 +199,9 @@ class TestToolReturnTypes:
def datetime_tool() -> datetime.datetime:
return dt
- async with Client(mcp) as client:
- result = await client.call_tool("datetime_tool", {})
- assert result.data == dt
+ result = await mcp.call_tool("datetime_tool", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": dt.isoformat()}
async def test_image(self, tmp_path: Path):
mcp = FastMCP()
@@ -215,15 +213,16 @@ class TestToolReturnTypes:
image_path = tmp_path / "test.png"
image_path.write_bytes(b"fake png data")
- async with Client(mcp) as client:
- result = await client.call_tool("image_tool", {"path": str(image_path)})
- assert result.structured_content is None
- content = result.content[0]
- assert isinstance(content, ImageContent)
- assert content.type == "image"
- assert content.mimeType == "image/png"
- decoded = base64.b64decode(content.data)
- assert decoded == b"fake png data"
+ result = await mcp.call_tool("image_tool", {"path": str(image_path)})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content is None
+ assert isinstance(result.content, list)
+ content = result.content[0]
+ assert isinstance(content, ImageContent)
+ assert content.type == "image"
+ assert content.mimeType == "image/png"
+ decoded = base64.b64decode(content.data)
+ assert decoded == b"fake png data"
async def test_audio(self, tmp_path: Path):
mcp = FastMCP()
@@ -235,14 +234,15 @@ class TestToolReturnTypes:
audio_path = tmp_path / "test.wav"
audio_path.write_bytes(b"fake wav data")
- async with Client(mcp) as client:
- result = await client.call_tool("audio_tool", {"path": str(audio_path)})
- content = result.content[0]
- assert isinstance(content, AudioContent)
- assert content.type == "audio"
- assert content.mimeType == "audio/wav"
- decoded = base64.b64decode(content.data)
- assert decoded == b"fake wav data"
+ result = await mcp.call_tool("audio_tool", {"path": str(audio_path)})
+ assert isinstance(result, ToolResult)
+ assert isinstance(result.content, list)
+ content = result.content[0]
+ assert isinstance(content, AudioContent)
+ assert content.type == "audio"
+ assert content.mimeType == "audio/wav"
+ decoded = base64.b64decode(content.data)
+ assert decoded == b"fake wav data"
async def test_file(self, tmp_path: Path):
mcp = FastMCP()
@@ -254,39 +254,41 @@ class TestToolReturnTypes:
file_path = tmp_path / "test.bin"
file_path.write_bytes(b"test file data")
- async with Client(mcp) as client:
- result = await client.call_tool("file_tool", {"path": str(file_path)})
- content = result.content[0]
- assert isinstance(content, EmbeddedResource)
- assert content.type == "resource"
- resource = content.resource
- assert resource.mimeType == "application/octet-stream"
- assert hasattr(resource, "blob")
- blob_data = getattr(resource, "blob")
- decoded = base64.b64decode(blob_data)
- assert decoded == b"test file data"
- assert str(resource.uri) == file_path.resolve().as_uri()
+ result = await mcp.call_tool("file_tool", {"path": str(file_path)})
+ assert isinstance(result, ToolResult)
+ assert isinstance(result.content, list)
+ content = result.content[0]
+ assert isinstance(content, EmbeddedResource)
+ assert content.type == "resource"
+ resource = content.resource
+ assert resource.mimeType == "application/octet-stream"
+ assert hasattr(resource, "blob")
+ blob_data = getattr(resource, "blob")
+ decoded = base64.b64decode(blob_data)
+ assert decoded == b"test file data"
+ assert str(resource.uri) == file_path.resolve().as_uri()
async def test_tool_mixed_content(self, tool_server: FastMCP):
- async with Client(tool_server) as client:
- result = await client.call_tool("mixed_content_tool", {})
- assert len(result.content) == 3
- content1 = result.content[0]
- content2 = result.content[1]
- content3 = result.content[2]
- assert isinstance(content1, TextContent)
- assert content1.text == "Hello"
- assert isinstance(content2, ImageContent)
- assert content2.mimeType == "application/octet-stream"
- assert content2.data == "abc"
- assert isinstance(content3, EmbeddedResource)
- assert content3.type == "resource"
- resource = content3.resource
- assert resource.mimeType == "application/octet-stream"
- assert hasattr(resource, "blob")
- blob_data = getattr(resource, "blob")
- decoded = base64.b64decode(blob_data)
- assert decoded == b"abc"
+ result = await tool_server.call_tool("mixed_content_tool", {})
+ assert isinstance(result, ToolResult)
+ assert isinstance(result.content, list)
+ assert len(result.content) == 3
+ content1 = result.content[0]
+ content2 = result.content[1]
+ content3 = result.content[2]
+ assert isinstance(content1, TextContent)
+ assert content1.text == "Hello"
+ assert isinstance(content2, ImageContent)
+ assert content2.mimeType == "application/octet-stream"
+ assert content2.data == "abc"
+ assert isinstance(content3, EmbeddedResource)
+ assert content3.type == "resource"
+ resource = content3.resource
+ assert resource.mimeType == "application/octet-stream"
+ assert hasattr(resource, "blob")
+ blob_data = getattr(resource, "blob")
+ decoded = base64.b64decode(blob_data)
+ assert decoded == b"abc"
async def test_tool_mixed_list_with_image(
self, tool_server: FastMCP, tmp_path: Path
@@ -296,24 +298,25 @@ class TestToolReturnTypes:
image_path = tmp_path / "test.png"
image_path.write_bytes(b"test image data")
- async with Client(tool_server) as client:
- result = await client.call_tool(
- "mixed_list_fn", {"image_path": str(image_path)}
- )
- assert len(result.content) == 4
- content1 = result.content[0]
- assert isinstance(content1, TextContent)
- assert content1.text == "text message"
- content2 = result.content[1]
- assert isinstance(content2, ImageContent)
- assert content2.mimeType == "image/png"
- assert base64.b64decode(content2.data) == b"test image data"
- content3 = result.content[2]
- assert isinstance(content3, TextContent)
- assert json.loads(content3.text) == {"key": "value"}
- content4 = result.content[3]
- assert isinstance(content4, TextContent)
- assert content4.text == "direct content"
+ result = await tool_server.call_tool(
+ "mixed_list_fn", {"image_path": str(image_path)}
+ )
+ assert isinstance(result, ToolResult)
+ assert isinstance(result.content, list)
+ assert len(result.content) == 4
+ content1 = result.content[0]
+ assert isinstance(content1, TextContent)
+ assert content1.text == "text message"
+ content2 = result.content[1]
+ assert isinstance(content2, ImageContent)
+ assert content2.mimeType == "image/png"
+ assert base64.b64decode(content2.data) == b"test image data"
+ content3 = result.content[2]
+ assert isinstance(content3, TextContent)
+ assert json.loads(content3.text) == {"key": "value"}
+ content4 = result.content[3]
+ assert isinstance(content4, TextContent)
+ assert content4.text == "direct content"
async def test_tool_mixed_list_with_audio(
self, tool_server: FastMCP, tmp_path: Path
@@ -323,24 +326,25 @@ class TestToolReturnTypes:
audio_path = tmp_path / "test.wav"
audio_path.write_bytes(b"test audio data")
- async with Client(tool_server) as client:
- result = await client.call_tool(
- "mixed_audio_list_fn", {"audio_path": str(audio_path)}
- )
- assert len(result.content) == 4
- content1 = result.content[0]
- assert isinstance(content1, TextContent)
- assert content1.text == "text message"
- content2 = result.content[1]
- assert isinstance(content2, AudioContent)
- assert content2.mimeType == "audio/wav"
- assert base64.b64decode(content2.data) == b"test audio data"
- content3 = result.content[2]
- assert isinstance(content3, TextContent)
- assert json.loads(content3.text) == {"key": "value"}
- content4 = result.content[3]
- assert isinstance(content4, TextContent)
- assert content4.text == "direct content"
+ result = await tool_server.call_tool(
+ "mixed_audio_list_fn", {"audio_path": str(audio_path)}
+ )
+ assert isinstance(result, ToolResult)
+ assert isinstance(result.content, list)
+ assert len(result.content) == 4
+ content1 = result.content[0]
+ assert isinstance(content1, TextContent)
+ assert content1.text == "text message"
+ content2 = result.content[1]
+ assert isinstance(content2, AudioContent)
+ assert content2.mimeType == "audio/wav"
+ assert base64.b64decode(content2.data) == b"test audio data"
+ content3 = result.content[2]
+ assert isinstance(content3, TextContent)
+ assert json.loads(content3.text) == {"key": "value"}
+ content4 = result.content[3]
+ assert isinstance(content4, TextContent)
+ assert content4.text == "direct content"
async def test_tool_mixed_list_with_file(
self, tool_server: FastMCP, tmp_path: Path
@@ -350,28 +354,29 @@ class TestToolReturnTypes:
file_path = tmp_path / "test.bin"
file_path.write_bytes(b"test file data")
- async with Client(tool_server) as client:
- result = await client.call_tool(
- "mixed_file_list_fn", {"file_path": str(file_path)}
- )
- assert len(result.content) == 4
- content1 = result.content[0]
- assert isinstance(content1, TextContent)
- assert content1.text == "text message"
- content2 = result.content[1]
- assert isinstance(content2, EmbeddedResource)
- assert content2.type == "resource"
- resource = content2.resource
- assert resource.mimeType == "application/octet-stream"
- assert hasattr(resource, "blob")
- blob_data = getattr(resource, "blob")
- assert base64.b64decode(blob_data) == b"test file data"
- content3 = result.content[2]
- assert isinstance(content3, TextContent)
- assert json.loads(content3.text) == {"key": "value"}
- content4 = result.content[3]
- assert isinstance(content4, TextContent)
- assert content4.text == "direct content"
+ result = await tool_server.call_tool(
+ "mixed_file_list_fn", {"file_path": str(file_path)}
+ )
+ assert isinstance(result, ToolResult)
+ assert isinstance(result.content, list)
+ assert len(result.content) == 4
+ content1 = result.content[0]
+ assert isinstance(content1, TextContent)
+ assert content1.text == "text message"
+ content2 = result.content[1]
+ assert isinstance(content2, EmbeddedResource)
+ assert content2.type == "resource"
+ resource = content2.resource
+ assert resource.mimeType == "application/octet-stream"
+ assert hasattr(resource, "blob")
+ blob_data = getattr(resource, "blob")
+ assert base64.b64decode(blob_data) == b"test file data"
+ content3 = result.content[2]
+ assert isinstance(content3, TextContent)
+ assert json.loads(content3.text) == {"key": "value"}
+ content4 = result.content[3]
+ assert isinstance(content4, TextContent)
+ assert content4.text == "direct content"
class TestToolParameters:
@@ -386,18 +391,17 @@ class TestToolParameters:
"""A greeting tool"""
return f"Hello {title} {name}"
- async with Client(mcp) as client:
- tools = await client.list_tools()
- assert len(tools) == 1
- tool = tools[0]
+ tools = await mcp.get_tools()
+ assert len(tools) == 1
+ tool = tools[0]
- properties = tool.inputSchema["properties"]
- assert "name" in properties
- assert properties["name"]["description"] == "The name to greet"
- assert "title" in properties
- assert properties["title"]["description"] == "Optional title"
- assert properties["title"]["default"] == ""
- assert tool.inputSchema["required"] == ["name"]
+ properties = tool.parameters["properties"]
+ assert "name" in properties
+ assert properties["name"]["description"] == "The name to greet"
+ assert "title" in properties
+ assert properties["title"]["description"] == "Optional title"
+ assert properties["title"]["default"] == ""
+ assert tool.parameters["required"] == ["name"]
async def test_parameter_descriptions_with_field_defaults(self):
mcp = FastMCP("Test Server")
@@ -410,18 +414,17 @@ class TestToolParameters:
"""A greeting tool"""
return f"Hello {title} {name}"
- async with Client(mcp) as client:
- tools = await client.list_tools()
- assert len(tools) == 1
- tool = tools[0]
+ tools = await mcp.get_tools()
+ assert len(tools) == 1
+ tool = tools[0]
- properties = tool.inputSchema["properties"]
- assert "name" in properties
- assert properties["name"]["description"] == "The name to greet"
- assert "title" in properties
- assert properties["title"]["description"] == "Optional title"
- assert properties["title"]["default"] == ""
- assert tool.inputSchema["required"] == ["name"]
+ properties = tool.parameters["properties"]
+ assert "name" in properties
+ assert properties["name"]["description"] == "The name to greet"
+ assert "title" in properties
+ assert properties["title"]["description"] == "Optional title"
+ assert properties["title"]["default"] == ""
+ assert tool.parameters["required"] == ["name"]
async def test_tool_with_bytes_input(self):
mcp = FastMCP()
@@ -430,28 +433,28 @@ class TestToolParameters:
def process_image(image: bytes) -> Image:
return Image(data=image)
- async with Client(mcp) as client:
- result = await client.call_tool(
- "process_image", {"image": b"fake png data"}
- )
- assert result.structured_content is None
- assert isinstance(result.content[0], ImageContent)
- assert result.content[0].mimeType == "image/png"
- assert result.content[0].data == base64.b64encode(b"fake png data").decode()
+ result = await mcp.call_tool("process_image", {"image": b"fake png data"})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content is None
+ assert isinstance(result.content, list)
+ assert isinstance(result.content[0], ImageContent)
+ assert result.content[0].mimeType == "image/png"
+ assert result.content[0].data == base64.b64encode(b"fake png data").decode()
async def test_tool_with_invalid_input(self):
+ from pydantic import ValidationError
+
mcp = FastMCP()
@mcp.tool
def my_tool(x: int) -> int:
return x + 1
- async with Client(mcp) as client:
- with pytest.raises(
- ToolError,
- match="Input should be a valid integer",
- ):
- await client.call_tool("my_tool", {"x": "not an int"})
+ with pytest.raises(
+ ValidationError,
+ match="Input should be a valid integer",
+ ):
+ await mcp.call_tool("my_tool", {"x": "not an int"})
async def test_tool_int_coercion(self):
"""Test that string ints are coerced by default."""
@@ -461,9 +464,9 @@ class TestToolParameters:
def add_one(x: int) -> int:
return x + 1
- async with Client(mcp) as client:
- result = await client.call_tool("add_one", {"x": "42"})
- assert result.data == 43
+ result = await mcp.call_tool("add_one", {"x": "42"})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": 43}
async def test_tool_bool_coercion(self):
"""Test that string bools are coerced by default."""
@@ -473,65 +476,70 @@ class TestToolParameters:
def toggle(flag: bool) -> bool:
return not flag
- async with Client(mcp) as client:
- result = await client.call_tool("toggle", {"flag": "true"})
- assert result.data is False
+ result = await mcp.call_tool("toggle", {"flag": "true"})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": False}
- result = await client.call_tool("toggle", {"flag": "false"})
- assert result.data is True
+ result = await mcp.call_tool("toggle", {"flag": "false"})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": True}
async def test_annotated_field_validation(self):
+ from pydantic import ValidationError
+
mcp = FastMCP()
@mcp.tool
def analyze(x: Annotated[int, Field(ge=1)]) -> None:
pass
- async with Client(mcp) as client:
- with pytest.raises(
- ToolError,
- match="Input should be greater than or equal to 1",
- ):
- await client.call_tool("analyze", {"x": 0})
+ with pytest.raises(
+ ValidationError,
+ match="Input should be greater than or equal to 1",
+ ):
+ await mcp.call_tool("analyze", {"x": 0})
async def test_default_field_validation(self):
+ from pydantic import ValidationError
+
mcp = FastMCP()
@mcp.tool
def analyze(x: int = Field(ge=1)) -> None:
pass
- async with Client(mcp) as client:
- with pytest.raises(
- ToolError,
- match="Input should be greater than or equal to 1",
- ):
- await client.call_tool("analyze", {"x": 0})
+ with pytest.raises(
+ ValidationError,
+ match="Input should be greater than or equal to 1",
+ ):
+ await mcp.call_tool("analyze", {"x": 0})
async def test_default_field_is_still_required_if_no_default_specified(self):
+ from pydantic import ValidationError
+
mcp = FastMCP()
@mcp.tool
def analyze(x: int = Field()) -> None:
pass
- async with Client(mcp) as client:
- with pytest.raises(ToolError, match="Missing required argument"):
- await client.call_tool("analyze", {})
+ with pytest.raises(ValidationError, match="missing"):
+ await mcp.call_tool("analyze", {})
async def test_literal_type_validation_error(self):
+ from pydantic import ValidationError
+
mcp = FastMCP()
@mcp.tool
def analyze(x: Literal["a", "b"]) -> None:
pass
- async with Client(mcp) as client:
- with pytest.raises(
- ToolError,
- match="Input should be 'a' or 'b'",
- ):
- await client.call_tool("analyze", {"x": "c"})
+ with pytest.raises(
+ ValidationError,
+ match="Input should be 'a' or 'b'",
+ ):
+ await mcp.call_tool("analyze", {"x": "c"})
async def test_literal_type_validation_success(self):
mcp = FastMCP()
@@ -540,11 +548,13 @@ class TestToolParameters:
def analyze(x: Literal["a", "b"]) -> str:
return x
- async with Client(mcp) as client:
- result = await client.call_tool("analyze", {"x": "a"})
- assert result.data == "a"
+ result = await mcp.call_tool("analyze", {"x": "a"})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "a"}
async def test_enum_type_validation_error(self):
+ from pydantic import ValidationError
+
mcp = FastMCP()
class MyEnum(Enum):
@@ -556,12 +566,11 @@ class TestToolParameters:
def analyze(x: MyEnum) -> str:
return x.value
- async with Client(mcp) as client:
- with pytest.raises(
- ToolError,
- match="Input should be 'red', 'green' or 'blue'",
- ):
- await client.call_tool("analyze", {"x": "some-color"})
+ with pytest.raises(
+ ValidationError,
+ match="Input should be 'red', 'green' or 'blue'",
+ ):
+ await mcp.call_tool("analyze", {"x": "some-color"})
async def test_enum_type_validation_success(self):
mcp = FastMCP()
@@ -575,29 +584,32 @@ class TestToolParameters:
def analyze(x: MyEnum) -> str:
return x.value
- async with Client(mcp) as client:
- result = await client.call_tool("analyze", {"x": "red"})
- assert result.data == "red"
+ result = await mcp.call_tool("analyze", {"x": "red"})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "red"}
async def test_union_type_validation(self):
+ from pydantic import ValidationError
+
mcp = FastMCP()
@mcp.tool
def analyze(x: int | float) -> str:
return str(x)
- async with Client(mcp) as client:
- result = await client.call_tool("analyze", {"x": 1})
- assert result.data == "1"
+ result = await mcp.call_tool("analyze", {"x": 1})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "1"}
- result = await client.call_tool("analyze", {"x": 1.0})
- assert result.data == "1.0"
+ result = await mcp.call_tool("analyze", {"x": 1.0})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "1.0"}
- with pytest.raises(
- ToolError,
- match="Input should be a valid",
- ):
- await client.call_tool("analyze", {"x": "not a number"})
+ with pytest.raises(
+ ValidationError,
+ match="Input should be a valid",
+ ):
+ await mcp.call_tool("analyze", {"x": "not a number"})
async def test_path_type(self):
mcp = FastMCP()
@@ -609,20 +621,21 @@ class TestToolParameters:
test_path = Path("tmp") / "test.txt"
- async with Client(mcp) as client:
- result = await client.call_tool("send_path", {"path": str(test_path)})
- assert result.data == str(test_path)
+ result = await mcp.call_tool("send_path", {"path": str(test_path)})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": str(test_path)}
async def test_path_type_error(self):
+ from pydantic import ValidationError
+
mcp = FastMCP()
@mcp.tool
def send_path(path: Path) -> str:
return str(path)
- async with Client(mcp) as client:
- with pytest.raises(ToolError, match="Input is not a valid path"):
- await client.call_tool("send_path", {"path": 1})
+ with pytest.raises(ValidationError, match="Input is not a valid path"):
+ await mcp.call_tool("send_path", {"path": 1})
async def test_uuid_type(self):
mcp = FastMCP()
@@ -634,20 +647,21 @@ class TestToolParameters:
test_uuid = uuid.uuid4()
- async with Client(mcp) as client:
- result = await client.call_tool("send_uuid", {"x": test_uuid})
- assert result.data == str(test_uuid)
+ result = await mcp.call_tool("send_uuid", {"x": test_uuid})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": str(test_uuid)}
async def test_uuid_type_error(self):
+ from pydantic import ValidationError
+
mcp = FastMCP()
@mcp.tool
def send_uuid(x: uuid.UUID) -> str:
return str(x)
- async with Client(mcp) as client:
- with pytest.raises(ToolError, match="Input should be a valid UUID"):
- await client.call_tool("send_uuid", {"x": "not a uuid"})
+ with pytest.raises(ValidationError, match="Input should be a valid UUID"):
+ await mcp.call_tool("send_uuid", {"x": "not a uuid"})
async def test_datetime_type(self):
mcp = FastMCP()
@@ -658,9 +672,9 @@ class TestToolParameters:
dt = datetime.datetime(2025, 4, 25, 1, 2, 3)
- async with Client(mcp) as client:
- result = await client.call_tool("send_datetime", {"x": dt})
- assert result.data == dt.isoformat()
+ result = await mcp.call_tool("send_datetime", {"x": dt})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": dt.isoformat()}
async def test_datetime_type_parse_string(self):
mcp = FastMCP()
@@ -669,22 +683,21 @@ class TestToolParameters:
def send_datetime(x: datetime.datetime) -> str:
return x.isoformat()
- async with Client(mcp) as client:
- result = await client.call_tool(
- "send_datetime", {"x": "2021-01-01T00:00:00"}
- )
- assert result.data == "2021-01-01T00:00:00"
+ result = await mcp.call_tool("send_datetime", {"x": "2021-01-01T00:00:00"})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "2021-01-01T00:00:00"}
async def test_datetime_type_error(self):
+ from pydantic import ValidationError
+
mcp = FastMCP()
@mcp.tool
def send_datetime(x: datetime.datetime) -> str:
return x.isoformat()
- async with Client(mcp) as client:
- with pytest.raises(ToolError, match="Input should be a valid datetime"):
- await client.call_tool("send_datetime", {"x": "not a datetime"})
+ with pytest.raises(ValidationError, match="Input should be a valid datetime"):
+ await mcp.call_tool("send_datetime", {"x": "not a datetime"})
async def test_date_type(self):
mcp = FastMCP()
@@ -693,9 +706,11 @@ class TestToolParameters:
def send_date(x: datetime.date) -> str:
return x.isoformat()
- async with Client(mcp) as client:
- result = await client.call_tool("send_date", {"x": datetime.date.today()})
- assert result.data == datetime.date.today().isoformat()
+ result = await mcp.call_tool("send_date", {"x": datetime.date.today()})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {
+ "result": datetime.date.today().isoformat()
+ }
async def test_date_type_parse_string(self):
mcp = FastMCP()
@@ -704,9 +719,9 @@ class TestToolParameters:
def send_date(x: datetime.date) -> str:
return x.isoformat()
- async with Client(mcp) as client:
- result = await client.call_tool("send_date", {"x": "2021-01-01"})
- assert result.data == "2021-01-01"
+ result = await mcp.call_tool("send_date", {"x": "2021-01-01"})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "2021-01-01"}
async def test_timedelta_type(self):
mcp = FastMCP()
@@ -715,11 +730,11 @@ class TestToolParameters:
def send_timedelta(x: datetime.timedelta) -> str:
return str(x)
- async with Client(mcp) as client:
- result = await client.call_tool(
- "send_timedelta", {"x": datetime.timedelta(days=1)}
- )
- assert result.data == "1 day, 0:00:00"
+ result = await mcp.call_tool(
+ "send_timedelta", {"x": datetime.timedelta(days=1)}
+ )
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "1 day, 0:00:00"}
async def test_timedelta_type_parse_int(self):
"""Test that int input is coerced to timedelta (seconds)."""
@@ -729,11 +744,13 @@ class TestToolParameters:
def send_timedelta(x: datetime.timedelta) -> str:
return str(x)
- async with Client(mcp) as client:
- result = await client.call_tool("send_timedelta", {"x": 1000})
- assert (
- "0:16:40" in result.data or "16:40" in result.data
- ) # 1000 seconds = 16 minutes 40 seconds
+ result = await mcp.call_tool("send_timedelta", {"x": 1000})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content is not None
+ result_str = result.structured_content["result"]
+ assert (
+ "0:16:40" in result_str or "16:40" in result_str
+ ) # 1000 seconds = 16 minutes 40 seconds
async def test_annotated_string_description(self):
mcp = FastMCP()
@@ -742,10 +759,9 @@ class TestToolParameters:
def f(x: Annotated[int, "A number"]):
return x
- async with Client(mcp) as client:
- tools = await client.list_tools()
- assert len(tools) == 1
- assert tools[0].inputSchema["properties"]["x"]["description"] == "A number"
+ tools = await mcp.get_tools()
+ assert len(tools) == 1
+ assert tools[0].parameters["properties"]["x"]["description"] == "A number"
class TestToolOutputSchema:
@@ -757,18 +773,17 @@ class TestToolOutputSchema:
def f() -> annotation:
return "hello"
- async with Client(mcp) as client:
- tools = await client.list_tools()
- assert len(tools) == 1
+ tools = await mcp.get_tools()
+ assert len(tools) == 1
- type_schema = TypeAdapter(annotation).json_schema()
- type_schema = compress_schema(type_schema, prune_titles=True)
- assert tools[0].outputSchema == {
- "type": "object",
- "properties": {"result": type_schema},
- "required": ["result"],
- "x-fastmcp-wrap-result": True,
- }
+ type_schema = TypeAdapter(annotation).json_schema()
+ type_schema = compress_schema(type_schema, prune_titles=True)
+ assert tools[0].output_schema == {
+ "type": "object",
+ "properties": {"result": type_schema},
+ "required": ["result"],
+ "x-fastmcp-wrap-result": True,
+ }
@pytest.mark.parametrize(
"annotation",
@@ -781,17 +796,16 @@ class TestToolOutputSchema:
def f() -> annotation:
return {"name": "John", "age": 30}
- async with Client(mcp) as client:
- tools = await client.list_tools()
+ tools = await mcp.get_tools()
- type_schema = compress_schema(
- TypeAdapter(annotation).json_schema(), prune_titles=True
- )
- assert len(tools) == 1
+ type_schema = compress_schema(
+ TypeAdapter(annotation).json_schema(), prune_titles=True
+ )
+ assert len(tools) == 1
- actual_schema = _normalize_anyof_order(tools[0].outputSchema)
- expected_schema = _normalize_anyof_order(type_schema)
- assert actual_schema == expected_schema
+ actual_schema = _normalize_anyof_order(tools[0].output_schema)
+ expected_schema = _normalize_anyof_order(type_schema)
+ assert actual_schema == expected_schema
async def test_disabled_output_schema_no_structured_content(self):
mcp = FastMCP()
@@ -800,12 +814,12 @@ class TestToolOutputSchema:
def f() -> int:
return 42
- async with Client(mcp) as client:
- result = await client.call_tool("f", {})
- assert isinstance(result.content[0], TextContent)
- assert result.content[0].text == "42"
- assert result.structured_content is None
- assert result.data is None
+ result = await mcp.call_tool("f", {})
+ assert isinstance(result, ToolResult)
+ assert isinstance(result.content, list)
+ assert isinstance(result.content[0], TextContent)
+ assert result.content[0].text == "42"
+ assert result.structured_content is None
async def test_manual_structured_content(self):
mcp = FastMCP()
@@ -818,36 +832,34 @@ class TestToolOutputSchema:
assert f.output_schema is None
- async with Client(mcp) as client:
- result = await client.call_tool("f", {})
- assert isinstance(result.content[0], TextContent)
- assert result.content[0].text == "Hello, world!"
- assert result.structured_content == {"message": "Hello, world!"}
- assert result.data == {"message": "Hello, world!"}
+ result = await mcp.call_tool("f", {})
+ assert isinstance(result, ToolResult)
+ assert isinstance(result.content, list)
+ assert isinstance(result.content[0], TextContent)
+ assert result.content[0].text == "Hello, world!"
+ assert result.structured_content == {"message": "Hello, world!"}
- async def test_output_schema_none_full_handshake(self):
- """Test that output_schema=None works through full client/server
- handshake. We test this by returning a scalar, which requires an output
- schema to serialize."""
+ async def test_output_schema_none(self):
+ """Test that output_schema=None works correctly."""
mcp = FastMCP()
@mcp.tool(output_schema=None)
def simple_tool() -> int:
return 42
- async with Client(mcp) as client:
- tools = await client.list_tools()
- tool = next(t for t in tools if t.name == "simple_tool")
- assert tool.outputSchema is None
+ tools = await mcp.get_tools()
+ tool = next(t for t in tools if t.name == "simple_tool")
+ assert tool.output_schema is None
- result = await client.call_tool("simple_tool", {})
- assert result.structured_content is None
- assert result.data is None
- assert isinstance(result.content[0], TextContent)
- assert result.content[0].text == "42"
+ result = await mcp.call_tool("simple_tool", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content is None
+ assert isinstance(result.content, list)
+ assert isinstance(result.content[0], TextContent)
+ assert result.content[0].text == "42"
- async def test_output_schema_explicit_object_full_handshake(self):
- """Test explicit object output schema through full client/server handshake."""
+ async def test_output_schema_explicit_object(self):
+ """Test explicit object output schema."""
mcp = FastMCP()
@mcp.tool(
@@ -863,77 +875,72 @@ class TestToolOutputSchema:
def explicit_tool() -> dict[str, Any]:
return {"greeting": "Hello", "count": 42}
- async with Client(mcp) as client:
- tools = await client.list_tools()
- tool = next(t for t in tools if t.name == "explicit_tool")
- expected_schema = {
- "type": "object",
- "properties": {
- "greeting": {"type": "string"},
- "count": {"type": "integer"},
- },
- "required": ["greeting"],
- }
- assert tool.outputSchema == expected_schema
+ tools = await mcp.get_tools()
+ tool = next(t for t in tools if t.name == "explicit_tool")
+ expected_schema = {
+ "type": "object",
+ "properties": {
+ "greeting": {"type": "string"},
+ "count": {"type": "integer"},
+ },
+ "required": ["greeting"],
+ }
+ assert tool.output_schema == expected_schema
- result = await client.call_tool("explicit_tool", {})
- assert result.structured_content == {"greeting": "Hello", "count": 42}
- assert result.data is not None
- assert result.data.greeting == "Hello" # type: ignore[attr-defined]
- assert result.data.count == 42 # type: ignore[attr-defined]
+ result = await mcp.call_tool("explicit_tool", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"greeting": "Hello", "count": 42}
- async def test_output_schema_wrapped_primitive_full_handshake(self):
- """Test wrapped primitive output schema through full client/server handshake."""
+ async def test_output_schema_wrapped_primitive(self):
+ """Test wrapped primitive output schema."""
mcp = FastMCP()
@mcp.tool
def primitive_tool() -> str:
return "Hello, primitives!"
- async with Client(mcp) as client:
- tools = await client.list_tools()
- tool = next(t for t in tools if t.name == "primitive_tool")
- expected_schema = {
- "type": "object",
- "properties": {"result": {"type": "string"}},
- "required": ["result"],
- "x-fastmcp-wrap-result": True,
- }
- assert tool.outputSchema == expected_schema
+ tools = await mcp.get_tools()
+ tool = next(t for t in tools if t.name == "primitive_tool")
+ expected_schema = {
+ "type": "object",
+ "properties": {"result": {"type": "string"}},
+ "required": ["result"],
+ "x-fastmcp-wrap-result": True,
+ }
+ assert tool.output_schema == expected_schema
- result = await client.call_tool("primitive_tool", {})
- assert result.structured_content == {"result": "Hello, primitives!"}
- assert result.data == "Hello, primitives!"
+ result = await mcp.call_tool("primitive_tool", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "Hello, primitives!"}
- async def test_output_schema_complex_type_full_handshake(self):
- """Test complex type output schema through full client/server handshake."""
+ async def test_output_schema_complex_type(self):
+ """Test complex type output schema."""
mcp = FastMCP()
@mcp.tool
def complex_tool() -> list[dict[str, int]]:
return [{"a": 1, "b": 2}, {"c": 3, "d": 4}]
- async with Client(mcp) as client:
- tools = await client.list_tools()
- tool = next(t for t in tools if t.name == "complex_tool")
- expected_inner_schema = compress_schema(
- TypeAdapter(list[dict[str, int]]).json_schema(), prune_titles=True
- )
- expected_schema = {
- "type": "object",
- "properties": {"result": expected_inner_schema},
- "required": ["result"],
- "x-fastmcp-wrap-result": True,
- }
- assert tool.outputSchema == expected_schema
+ tools = await mcp.get_tools()
+ tool = next(t for t in tools if t.name == "complex_tool")
+ expected_inner_schema = compress_schema(
+ TypeAdapter(list[dict[str, int]]).json_schema(), prune_titles=True
+ )
+ expected_schema = {
+ "type": "object",
+ "properties": {"result": expected_inner_schema},
+ "required": ["result"],
+ "x-fastmcp-wrap-result": True,
+ }
+ assert tool.output_schema == expected_schema
- result = await client.call_tool("complex_tool", {})
- expected_data = [{"a": 1, "b": 2}, {"c": 3, "d": 4}]
- assert result.structured_content == {"result": expected_data}
- assert result.data is not None
+ result = await mcp.call_tool("complex_tool", {})
+ assert isinstance(result, ToolResult)
+ expected_data = [{"a": 1, "b": 2}, {"c": 3, "d": 4}]
+ assert result.structured_content == {"result": expected_data}
- async def test_output_schema_dataclass_full_handshake(self):
- """Test dataclass output schema through full client/server handshake."""
+ async def test_output_schema_dataclass(self):
+ """Test dataclass output schema."""
mcp = FastMCP()
@dataclass
@@ -945,22 +952,17 @@ class TestToolOutputSchema:
def dataclass_tool() -> User:
return User(name="Alice", age=30)
- async with Client(mcp) as client:
- tools = await client.list_tools()
- tool = next(t for t in tools if t.name == "dataclass_tool")
- expected_schema = compress_schema(
- TypeAdapter(User).json_schema(), prune_titles=True
- )
- assert tool.outputSchema == expected_schema
- assert (
- tool.outputSchema and "x-fastmcp-wrap-result" not in tool.outputSchema
- )
+ tools = await mcp.get_tools()
+ tool = next(t for t in tools if t.name == "dataclass_tool")
+ expected_schema = compress_schema(
+ TypeAdapter(User).json_schema(), prune_titles=True
+ )
+ assert tool.output_schema == expected_schema
+ assert tool.output_schema and "x-fastmcp-wrap-result" not in tool.output_schema
- result = await client.call_tool("dataclass_tool", {})
- assert result.structured_content == {"name": "Alice", "age": 30}
- assert result.data is not None
- assert result.data.name == "Alice" # type: ignore[attr-defined]
- assert result.data.age == 30 # type: ignore[attr-defined]
+ result = await mcp.call_tool("dataclass_tool", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"name": "Alice", "age": 30}
async def test_output_schema_mixed_content_types(self):
"""Test tools with mixed content and output schemas."""
@@ -974,41 +976,16 @@ class TestToolOutputSchema:
TextContent(type="text", text="direct MCP content"),
]
- async with Client(mcp) as client:
- result = await client.call_tool("mixed_output", {})
-
- assert result == snapshot(
- CallToolResult(
- content=[
- TextContent(type="text", text="text message"),
- TextContent(type="text", text='{"structured":"data"}'),
- TextContent(type="text", text="direct MCP content"),
- ],
- structured_content={
- "result": [
- "text message",
- {"structured": "data"},
- {
- "type": "text",
- "text": "direct MCP content",
- "annotations": None,
- "_meta": None,
- },
- ]
- },
- data=[
- "text message",
- {"structured": "data"},
- {
- "type": "text",
- "text": "direct MCP content",
- "annotations": None,
- "_meta": None,
- },
- ],
- meta=None,
- )
- )
+ result = await mcp.call_tool("mixed_output", {})
+ assert isinstance(result, ToolResult)
+ assert isinstance(result.content, list)
+ assert len(result.content) == 3
+ assert isinstance(result.content[0], TextContent)
+ assert result.content[0].text == "text message"
+ assert isinstance(result.content[1], TextContent)
+ assert result.content[1].text == '{"structured":"data"}'
+ assert isinstance(result.content[2], TextContent)
+ assert result.content[2].text == "direct MCP content"
async def test_output_schema_serialization_edge_cases(self):
"""Test edge cases in output schema serialization."""
@@ -1018,46 +995,45 @@ class TestToolOutputSchema:
def edge_case_tool() -> tuple[int, str]:
return (42, "hello")
- async with Client(mcp) as client:
- tools = await client.list_tools()
- tool = next(t for t in tools if t.name == "edge_case_tool")
+ tools = await mcp.get_tools()
+ tool = next(t for t in tools if t.name == "edge_case_tool")
- assert tool.outputSchema and "x-fastmcp-wrap-result" in tool.outputSchema
+ assert tool.output_schema and "x-fastmcp-wrap-result" in tool.output_schema
- result = await client.call_tool("edge_case_tool", {})
- assert result.structured_content == {"result": [42, "hello"]}
- assert result.data == [42, "hello"]
+ result = await mcp.call_tool("edge_case_tool", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": [42, "hello"]}
class TestToolContextInjection:
"""Test context injection in tools."""
async def test_context_detection(self):
- """Test that context parameters are properly detected."""
+ """Test that context parameters are properly detected and excluded from schema."""
mcp = FastMCP()
@mcp.tool
def tool_with_context(x: int, ctx: Context) -> str:
- return f"Request {ctx.request_id}: {x}"
+ return f"Request: {x}"
- async with Client(mcp) as client:
- tools = await client.list_tools()
- assert len(tools) == 1
- assert tools[0].name == "tool_with_context"
+ tools = await mcp.get_tools()
+ assert len(tools) == 1
+ assert tools[0].name == "tool_with_context"
+ # Context param should not appear in schema
+ assert "ctx" not in tools[0].parameters.get("properties", {})
- async def test_context_injection(self):
+ async def test_context_injection_basic(self):
"""Test that context is properly injected into tool calls."""
mcp = FastMCP()
@mcp.tool
def tool_with_context(x: int, ctx: Context) -> str:
assert isinstance(ctx, Context)
- assert ctx.request_id is not None
- return ctx.request_id
+ return f"Got context with x={x}"
- async with Client(mcp) as client:
- result = await client.call_tool("tool_with_context", {"x": 42})
- assert result.data == "1"
+ result = await mcp.call_tool("tool_with_context", {"x": 42})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "Got context with x=42"}
async def test_async_context(self):
"""Test that context works in async functions."""
@@ -1065,12 +1041,12 @@ class TestToolContextInjection:
@mcp.tool
async def async_tool(x: int, ctx: Context) -> str:
- assert ctx.request_id is not None
- return f"Async request {ctx.request_id}: {x}"
+ assert isinstance(ctx, Context)
+ return f"Async with x={x}"
- async with Client(mcp) as client:
- result = await client.call_tool("async_tool", {"x": 42})
- assert result.data == "Async request 1: 42"
+ result = await mcp.call_tool("async_tool", {"x": 42})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "Async with x=42"}
async def test_optional_context(self):
"""Test that context is optional."""
@@ -1080,9 +1056,9 @@ class TestToolContextInjection:
def no_context(x: int) -> int:
return x * 2
- async with Client(mcp) as client:
- result = await client.call_tool("no_context", {"x": 21})
- assert result.data == 42
+ result = await mcp.call_tool("no_context", {"x": 21})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": 42}
async def test_context_resource_access(self):
"""Test that context can access resources."""
@@ -1099,11 +1075,11 @@ class TestToolContextInjection:
r = result.contents[0]
return f"Read resource: {r.content} with mime type {r.mime_type}"
- async with Client(mcp) as client:
- result = await client.call_tool("tool_with_resource", {})
- assert (
- result.data == "Read resource: resource data with mime type text/plain"
- )
+ result = await mcp.call_tool("tool_with_resource", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {
+ "result": "Read resource: resource data with mime type text/plain"
+ }
async def test_tool_decorator_with_tags(self):
"""Test that the tool decorator properly sets tags."""
@@ -1113,9 +1089,9 @@ class TestToolContextInjection:
def sample_tool(x: int) -> int:
return x * 2
- async with Client(mcp) as client:
- tools = await client.list_tools()
- assert len(tools) == 1
+ tools = await mcp.get_tools()
+ assert len(tools) == 1
+ assert tools[0].tags == {"example", "test-tag"}
async def test_callable_object_with_context(self):
"""Test that a callable object can be used as a tool with context."""
@@ -1123,13 +1099,14 @@ class TestToolContextInjection:
class MyTool:
async def __call__(self, x: int, ctx: Context) -> int:
- return x + int(ctx.request_id)
+ assert isinstance(ctx, Context)
+ return x + 1
mcp.add_tool(Tool.from_function(MyTool(), name="MyTool"))
- async with Client(mcp) as client:
- result = await client.call_tool("MyTool", {"x": 2})
- assert result.data == 3
+ result = await mcp.call_tool("MyTool", {"x": 2})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": 3}
async def test_decorated_tool_with_functools_wraps(self):
"""Regression test for #2524: @mcp.tool with functools.wraps decorator."""
@@ -1149,23 +1126,23 @@ class TestToolContextInjection:
assert isinstance(ctx, Context)
return f"query: {query}"
- async with Client(mcp) as client:
- tools = await client.list_tools()
- tool = next(t for t in tools if t.name == "decorated_tool")
- assert "ctx" not in tool.inputSchema.get("properties", {})
+ tools = await mcp.get_tools()
+ tool = next(t for t in tools if t.name == "decorated_tool")
+ assert "ctx" not in tool.parameters.get("properties", {})
- result = await client.call_tool("decorated_tool", {"query": "test"})
- assert result.data == "query: test"
+ result = await mcp.call_tool("decorated_tool", {"query": "test"})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "query: test"}
class TestToolDecorator:
async def test_no_tools_before_decorator(self):
- mcp = FastMCP()
-
from fastmcp.exceptions import NotFoundError
+ mcp = FastMCP()
+
with pytest.raises(NotFoundError, match="Unknown tool: 'add'"):
- await mcp._call_tool_mcp("add", {"x": 1, "y": 2})
+ await mcp.call_tool("add", {"x": 1, "y": 2})
async def test_tool_decorator(self):
mcp = FastMCP()
@@ -1174,9 +1151,9 @@ class TestToolDecorator:
def add(x: int, y: int) -> int:
return x + y
- async with Client(mcp) as client:
- result = await client.call_tool("add", {"x": 1, "y": 2})
- assert result.data == 3
+ result = await mcp.call_tool("add", {"x": 1, "y": 2})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": 3}
async def test_tool_decorator_without_parentheses(self):
"""Test that @tool decorator works without parentheses."""
@@ -1189,9 +1166,9 @@ class TestToolDecorator:
tools = await mcp.get_tools()
assert any(t.name == "add" for t in tools)
- async with Client(mcp) as client:
- result = await client.call_tool("add", {"x": 1, "y": 2})
- assert result.data == 3
+ result = await mcp.call_tool("add", {"x": 1, "y": 2})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": 3}
async def test_tool_decorator_with_name(self):
mcp = FastMCP()
@@ -1200,9 +1177,9 @@ class TestToolDecorator:
def add(x: int, y: int) -> int:
return x + y
- async with Client(mcp) as client:
- result = await client.call_tool("custom-add", {"x": 1, "y": 2})
- assert result.data == 3
+ result = await mcp.call_tool("custom-add", {"x": 1, "y": 2})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": 3}
async def test_tool_decorator_with_description(self):
mcp = FastMCP()
@@ -1211,7 +1188,7 @@ class TestToolDecorator:
def add(x: int, y: int) -> int:
return x + y
- tools = await mcp._list_tools_mcp()
+ tools = await mcp.get_tools()
assert len(tools) == 1
tool = tools[0]
assert tool.description == "Add two numbers"
@@ -1228,9 +1205,9 @@ class TestToolDecorator:
obj = MyClass(10)
mcp.add_tool(Tool.from_function(obj.add))
- async with Client(mcp) as client:
- result = await client.call_tool("add", {"y": 2})
- assert result.data == 12
+ result = await mcp.call_tool("add", {"y": 2})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": 12}
async def test_tool_decorator_classmethod(self):
mcp = FastMCP()
@@ -1243,9 +1220,9 @@ class TestToolDecorator:
return cls.x + y
mcp.add_tool(Tool.from_function(MyClass.add))
- async with Client(mcp) as client:
- result = await client.call_tool("add", {"y": 2})
- assert result.data == 12
+ result = await mcp.call_tool("add", {"y": 2})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": 12}
async def test_tool_decorator_staticmethod(self):
mcp = FastMCP()
@@ -1256,9 +1233,9 @@ class TestToolDecorator:
def add(x: int, y: int) -> int:
return x + y
- async with Client(mcp) as client:
- result = await client.call_tool("add", {"x": 1, "y": 2})
- assert result.data == 3
+ result = await mcp.call_tool("add", {"x": 1, "y": 2})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": 3}
async def test_tool_decorator_async_function(self):
mcp = FastMCP()
@@ -1267,9 +1244,9 @@ class TestToolDecorator:
async def add(x: int, y: int) -> int:
return x + y
- async with Client(mcp) as client:
- result = await client.call_tool("add", {"x": 1, "y": 2})
- assert result.data == 3
+ result = await mcp.call_tool("add", {"x": 1, "y": 2})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": 3}
async def test_tool_decorator_classmethod_error(self):
mcp = FastMCP()
@@ -1293,9 +1270,9 @@ class TestToolDecorator:
return cls.x + y
mcp.add_tool(Tool.from_function(MyClass.add))
- async with Client(mcp) as client:
- result = await client.call_tool("add", {"y": 2})
- assert result.data == 12
+ result = await mcp.call_tool("add", {"y": 2})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": 12}
async def test_tool_decorator_staticmethod_async_function(self):
mcp = FastMCP()
@@ -1306,9 +1283,9 @@ class TestToolDecorator:
return x + y
mcp.add_tool(Tool.from_function(MyClass.add))
- async with Client(mcp) as client:
- result = await client.call_tool("add", {"x": 1, "y": 2})
- assert result.data == 3
+ result = await mcp.call_tool("add", {"x": 1, "y": 2})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": 3}
async def test_tool_decorator_staticmethod_order(self):
"""Test that the recommended decorator order works for static methods"""
@@ -1320,9 +1297,9 @@ class TestToolDecorator:
def add_v1(x: int, y: int) -> int:
return x + y
- async with Client(mcp) as client:
- result = await client.call_tool("add_v1", {"x": 1, "y": 2})
- assert result.data == 3
+ result = await mcp.call_tool("add_v1", {"x": 1, "y": 2})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": 3}
async def test_tool_decorator_with_tags(self):
"""Test that the tool decorator properly sets tags."""
@@ -1349,9 +1326,9 @@ class TestToolDecorator:
tools = await mcp.get_tools()
assert any(t.name == "custom_multiply" for t in tools)
- async with Client(mcp) as client:
- result = await client.call_tool("custom_multiply", {"a": 5, "b": 3})
- assert result.data == 15
+ result = await mcp.call_tool("custom_multiply", {"a": 5, "b": 3})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": 15}
assert not any(t.name == "multiply" for t in tools)
@@ -1389,14 +1366,14 @@ class TestToolDecorator:
async def test_tool_direct_function_call(self):
"""Test that tools can be registered via direct function call."""
+ from fastmcp.tools import FunctionTool
+
mcp = FastMCP()
def standalone_function(x: int, y: int) -> int:
"""A standalone function to be registered."""
return x + y
- from fastmcp.tools import FunctionTool
-
result_fn = mcp.tool(standalone_function, name="direct_call_tool")
assert isinstance(result_fn, FunctionTool)
@@ -1405,9 +1382,9 @@ class TestToolDecorator:
tool = next(t for t in tools if t.name == "direct_call_tool")
assert tool is result_fn
- async with Client(mcp) as client:
- result = await client.call_tool("direct_call_tool", {"x": 5, "y": 3})
- assert result.data == 8
+ result = await mcp.call_tool("direct_call_tool", {"x": 5, "y": 3})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": 8}
async def test_tool_decorator_with_string_name(self):
"""Test that @tool("custom_name") syntax works correctly."""
@@ -1422,9 +1399,9 @@ class TestToolDecorator:
assert any(t.name == "string_named_tool" for t in tools)
assert not any(t.name == "my_function" for t in tools)
- async with Client(mcp) as client:
- result = await client.call_tool("string_named_tool", {"x": 42})
- assert result.data == "Result: 42"
+ result = await mcp.call_tool("string_named_tool", {"x": 42})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "Result: 42"}
async def test_tool_decorator_conflicting_names_error(self):
"""Test that providing both positional and keyword name raises an error."""
@@ -1465,3 +1442,153 @@ class TestToolDecorator:
tool = next(t for t in tools if t.name == "multiply")
assert tool.meta == meta_data
+
+
+class TestToolTags:
+ def create_server(self, include_tags=None, exclude_tags=None):
+ mcp = FastMCP(include_tags=include_tags, exclude_tags=exclude_tags)
+
+ @mcp.tool(tags={"a", "b"})
+ def tool_1() -> int:
+ return 1
+
+ @mcp.tool(tags={"b", "c"})
+ def tool_2() -> int:
+ return 2
+
+ return mcp
+
+ async def test_include_tags_all_tools(self):
+ mcp = self.create_server(include_tags={"a", "b"})
+ tools = await mcp.get_tools()
+ assert {t.name for t in tools} == {"tool_1", "tool_2"}
+
+ async def test_include_tags_some_tools(self):
+ mcp = self.create_server(include_tags={"a", "z"})
+ tools = await mcp.get_tools()
+ assert {t.name for t in tools} == {"tool_1"}
+
+ async def test_exclude_tags_all_tools(self):
+ mcp = self.create_server(exclude_tags={"a", "b"})
+ tools = await mcp.get_tools()
+ assert {t.name for t in tools} == set()
+
+ async def test_exclude_tags_some_tools(self):
+ mcp = self.create_server(exclude_tags={"a", "z"})
+ tools = await mcp.get_tools()
+ assert {t.name for t in tools} == {"tool_2"}
+
+ async def test_exclude_precedence(self):
+ mcp = self.create_server(exclude_tags={"a"}, include_tags={"b"})
+ tools = await mcp.get_tools()
+ assert {t.name for t in tools} == {"tool_2"}
+
+ async def test_call_included_tool(self):
+ mcp = self.create_server(include_tags={"a"})
+ result_1 = await mcp.call_tool("tool_1", {})
+ assert result_1.structured_content == {"result": 1}
+
+ with pytest.raises(NotFoundError, match="Unknown tool"):
+ await mcp.call_tool("tool_2", {})
+
+ async def test_call_excluded_tool(self):
+ mcp = self.create_server(exclude_tags={"a"})
+ with pytest.raises(NotFoundError, match="Unknown tool"):
+ await mcp.call_tool("tool_1", {})
+
+ result_2 = await mcp.call_tool("tool_2", {})
+ assert result_2.structured_content == {"result": 2}
+
+
+class TestToolEnabled:
+ async def test_toggle_enabled(self):
+ mcp = FastMCP()
+
+ @mcp.tool
+ def sample_tool(x: int) -> int:
+ return x * 2
+
+ # Tool is enabled by default
+ tools = await mcp.get_tools()
+ assert any(t.name == "sample_tool" for t in tools)
+
+ # Disable via server
+ mcp.disable(keys=["tool:sample_tool"])
+
+ # Tool should not be in list when disabled
+ tools = await mcp.get_tools()
+ assert not any(t.name == "sample_tool" for t in tools)
+
+ # Re-enable via server
+ mcp.enable(keys=["tool:sample_tool"])
+ tools = await mcp.get_tools()
+ assert any(t.name == "sample_tool" for t in tools)
+
+ async def test_tool_disabled_via_server(self):
+ mcp = FastMCP()
+
+ @mcp.tool
+ def sample_tool(x: int) -> int:
+ return x * 2
+
+ mcp.disable(keys=["tool:sample_tool"])
+ tools = await mcp.get_tools()
+ assert len(tools) == 0
+
+ with pytest.raises(NotFoundError, match="Unknown tool"):
+ await mcp.call_tool("sample_tool", {"x": 5})
+
+ async def test_tool_toggle_enabled(self):
+ mcp = FastMCP()
+
+ @mcp.tool
+ def sample_tool(x: int) -> int:
+ return x * 2
+
+ mcp.disable(keys=["tool:sample_tool"])
+ mcp.enable(keys=["tool:sample_tool"])
+ tools = await mcp.get_tools()
+ assert len(tools) == 1
+
+ async def test_tool_toggle_disabled(self):
+ mcp = FastMCP()
+
+ @mcp.tool
+ def sample_tool(x: int) -> int:
+ return x * 2
+
+ mcp.disable(keys=["tool:sample_tool"])
+ tools = await mcp.get_tools()
+ assert len(tools) == 0
+
+ with pytest.raises(NotFoundError, match="Unknown tool"):
+ await mcp.call_tool("sample_tool", {"x": 5})
+
+ async def test_get_tool_and_disable(self):
+ mcp = FastMCP()
+
+ @mcp.tool
+ def sample_tool(x: int) -> int:
+ return x * 2
+
+ tool = await mcp.get_tool(name="sample_tool")
+ assert tool is not None
+
+ mcp.disable(keys=["tool:sample_tool"])
+ tools = await mcp.get_tools()
+ assert len(tools) == 0
+
+ with pytest.raises(NotFoundError, match="Unknown tool"):
+ await mcp.call_tool("sample_tool", {"x": 5})
+
+ async def test_cant_call_disabled_tool(self):
+ mcp = FastMCP()
+
+ @mcp.tool
+ def sample_tool(x: int) -> int:
+ return x * 2
+
+ mcp.disable(keys=["tool:sample_tool"])
+
+ with pytest.raises(NotFoundError, match="Unknown tool"):
+ await mcp.call_tool("sample_tool", {"x": 5})
diff --git a/tests/server/test_dependencies.py b/tests/server/test_dependencies.py
index 330a89649..38676d51a 100644
--- a/tests/server/test_dependencies.py
+++ b/tests/server/test_dependencies.py
@@ -8,7 +8,10 @@ from mcp.types import TextContent, TextResourceContents
from fastmcp import FastMCP
from fastmcp.client import Client
from fastmcp.dependencies import CurrentContext, Depends
+from fastmcp.prompts import PromptResult
+from fastmcp.resources import ResourceResult
from fastmcp.server.context import Context
+from fastmcp.tools.tool import ToolResult
HUZZAH = "huzzah!"
@@ -52,13 +55,12 @@ async def test_depends_with_sync_function(mcp: FastMCP):
f"Fetching '{query}' from {config['endpoint']} with key {config['api_key']}"
)
- async with Client(mcp) as client:
- result = await client.call_tool("fetch_data", {"query": "users"})
- assert len(result.content) == 1
- content = result.content[0]
- assert isinstance(content, TextContent)
- assert "Fetching 'users' from https://api.example.com" in content.text
- assert "secret123" in content.text
+ result = await mcp.call_tool("fetch_data", {"query": "users"})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content is not None
+ text = result.structured_content["result"]
+ assert "Fetching 'users' from https://api.example.com" in text
+ assert "secret123" in text
async def test_depends_with_async_function(mcp: FastMCP):
@@ -71,12 +73,10 @@ async def test_depends_with_async_function(mcp: FastMCP):
async def greet_user(name: str, user_id: int = Depends(get_user_id)) -> str: # type: ignore[assignment]
return f"Hello {name}, your ID is {user_id}"
- async with Client(mcp) as client:
- result = await client.call_tool("greet_user", {"name": "Alice"})
- assert len(result.content) == 1
- content = result.content[0]
- assert isinstance(content, TextContent)
- assert content.text == "Hello Alice, your ID is 42"
+ result = await mcp.call_tool("greet_user", {"name": "Alice"})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content is not None
+ assert result.structured_content["result"] == "Hello Alice, your ID is 42"
async def test_depends_with_async_context_manager(mcp: FastMCP):
@@ -96,13 +96,14 @@ async def test_depends_with_async_context_manager(mcp: FastMCP):
async def query_db(sql: str, db: str = Depends(get_database)) -> str: # type: ignore[assignment]
return f"Executing '{sql}' on {db}"
- async with Client(mcp) as client:
- result = await client.call_tool("query_db", {"sql": "SELECT * FROM users"})
- assert len(result.content) == 1
- content = result.content[0]
- assert isinstance(content, TextContent)
- assert "Executing 'SELECT * FROM users' on db_connection" in content.text
- assert cleanup_called
+ result = await mcp.call_tool("query_db", {"sql": "SELECT * FROM users"})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content is not None
+ assert (
+ "Executing 'SELECT * FROM users' on db_connection"
+ in result.structured_content["result"]
+ )
+ assert cleanup_called
async def test_nested_dependencies(mcp: FastMCP):
@@ -120,12 +121,13 @@ async def test_nested_dependencies(mcp: FastMCP):
) -> str:
return f"Calling {client['base_url']}/{client['version']}/{endpoint}"
- async with Client(mcp) as client:
- result = await client.call_tool("call_api", {"endpoint": "users"})
- assert len(result.content) == 1
- content = result.content[0]
- assert isinstance(content, TextContent)
- assert content.text == "Calling https://api.example.com/v1/users"
+ result = await mcp.call_tool("call_api", {"endpoint": "users"})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content is not None
+ assert (
+ result.structured_content["result"]
+ == "Calling https://api.example.com/v1/users"
+ )
async def test_dependencies_excluded_from_schema(mcp: FastMCP):
@@ -157,9 +159,10 @@ async def test_current_context_dependency(mcp: FastMCP):
assert isinstance(ctx, Context)
return HUZZAH
- async with Client(mcp) as client:
- result = await client.call_tool("use_context", {})
- assert HUZZAH in str(result)
+ result = await mcp.call_tool("use_context", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content is not None
+ assert result.structured_content["result"] == HUZZAH
async def test_current_context_and_legacy_context_coexist(mcp: FastMCP):
@@ -175,9 +178,10 @@ async def test_current_context_and_legacy_context_coexist(mcp: FastMCP):
assert legacy_ctx is dep_ctx
return HUZZAH
- async with Client(mcp) as client:
- result = await client.call_tool("use_both_contexts", {})
- assert HUZZAH in str(result)
+ result = await mcp.call_tool("use_both_contexts", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content is not None
+ assert result.structured_content["result"] == HUZZAH
async def test_backward_compat_context_still_works(mcp: FastMCP):
@@ -205,12 +209,10 @@ async def test_sync_tool_with_async_dependency(mcp: FastMCP):
def process_data(value: int, config: str = Depends(fetch_config)) -> str: # type: ignore[assignment]
return f"Processing {value} with {config}"
- async with Client(mcp) as client:
- result = await client.call_tool("process_data", {"value": 100})
- assert len(result.content) == 1
- content = result.content[0]
- assert isinstance(content, TextContent)
- assert content.text == "Processing 100 with loaded_config"
+ result = await mcp.call_tool("process_data", {"value": 100})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content is not None
+ assert result.structured_content["result"] == "Processing 100 with loaded_config"
async def test_dependency_caching(mcp: FastMCP):
@@ -229,13 +231,11 @@ async def test_dependency_caching(mcp: FastMCP):
) -> str:
return f"{dep1} + {dep2} = {dep1 + dep2}"
- async with Client(mcp) as client:
- result = await client.call_tool("tool_with_cached_dep", {})
- assert len(result.content) == 1
- content = result.content[0]
- assert isinstance(content, TextContent)
- assert content.text == "42 + 42 = 84"
- assert call_count == 1
+ result = await mcp.call_tool("tool_with_cached_dep", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content is not None
+ assert result.structured_content["result"] == "42 + 42 = 84"
+ assert call_count == 1
async def test_context_and_depends_together(mcp: FastMCP):
@@ -274,12 +274,10 @@ async def test_resource_with_dependency(mcp: FastMCP):
async def get_settings(storage: str = Depends(get_storage_path)) -> str:
return f"Settings loaded from {storage}"
- async with Client(mcp) as client:
- result = await client.read_resource("config://settings")
- assert len(result) == 1
- content = result[0]
- assert isinstance(content, TextResourceContents)
- assert content.text == "Settings loaded from /data/config"
+ result = await mcp.read_resource("config://settings")
+ assert isinstance(result, ResourceResult)
+ assert len(result.contents) == 1
+ assert result.contents[0].content == "Settings loaded from /data/config"
async def test_resource_with_context_and_dependency(mcp: FastMCP):
@@ -311,13 +309,13 @@ async def test_prompt_with_dependency(mcp: FastMCP):
async def custom_prompt(topic: str, tone: str = Depends(get_tone)) -> str:
return f"Write about {topic} in a {tone} tone"
- async with Client(mcp) as client:
- result = await client.get_prompt("custom_prompt", {"topic": "Python"})
- assert len(result.messages) == 1
- message = result.messages[0]
- content = message.content
- assert isinstance(content, TextContent)
- assert content.text == "Write about Python in a friendly and helpful tone"
+ result = await mcp.render_prompt("custom_prompt", {"topic": "Python"})
+ assert isinstance(result, PromptResult)
+ assert len(result.messages) == 1
+ message = result.messages[0]
+ content = message.content
+ assert isinstance(content, TextContent)
+ assert content.text == "Write about Python in a friendly and helpful tone"
async def test_prompt_with_context_and_dependency(mcp: FastMCP):
@@ -353,12 +351,10 @@ async def test_resource_template_with_dependency(mcp: FastMCP):
async def get_file(filename: str, base_path: str = Depends(get_base_path)) -> str:
return f"Reading {base_path}/{filename}"
- async with Client(mcp) as client:
- result = await client.read_resource("data://config.txt")
- assert len(result) == 1
- content = result[0]
- assert isinstance(content, TextResourceContents)
- assert content.text == "Reading /var/data/config.txt"
+ result = await mcp.read_resource("data://config.txt")
+ assert isinstance(result, ResourceResult)
+ assert len(result.contents) == 1
+ assert result.contents[0].content == "Reading /var/data/config.txt"
async def test_resource_template_with_context_and_dependency(mcp: FastMCP):
@@ -398,11 +394,10 @@ async def test_async_tool_context_manager_stays_open(mcp: FastMCP):
assert connection.is_open
return f"open={connection.is_open}"
- async with Client(mcp) as client:
- result = await client.call_tool("query_data", {"query": "test"})
- content = result.content[0]
- assert isinstance(content, TextContent)
- assert content.text == "open=True"
+ result = await mcp.call_tool("query_data", {"query": "test"})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content is not None
+ assert result.structured_content["result"] == "open=True"
async def test_async_resource_context_manager_stays_open(mcp: FastMCP):
@@ -413,11 +408,9 @@ async def test_async_resource_context_manager_stays_open(mcp: FastMCP):
assert connection.is_open
return f"open={connection.is_open}"
- async with Client(mcp) as client:
- result = await client.read_resource("data://config")
- content = result[0]
- assert isinstance(content, TextResourceContents)
- assert content.text == "open=True"
+ result = await mcp.read_resource("data://config")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "open=True"
async def test_async_resource_template_context_manager_stays_open(mcp: FastMCP):
@@ -431,11 +424,10 @@ async def test_async_resource_template_context_manager_stays_open(mcp: FastMCP):
assert connection.is_open
return f"open={connection.is_open},user={user_id}"
- async with Client(mcp) as client:
- result = await client.read_resource("user://123")
- content = result[0]
- assert isinstance(content, TextResourceContents)
- assert "open=True" in content.text
+ result = await mcp.read_resource("user://123")
+ assert isinstance(result, ResourceResult)
+ assert isinstance(result.contents[0].content, str)
+ assert "open=True" in result.contents[0].content
async def test_async_prompt_context_manager_stays_open(mcp: FastMCP):
@@ -449,12 +441,12 @@ async def test_async_prompt_context_manager_stays_open(mcp: FastMCP):
assert connection.is_open
return f"open={connection.is_open},topic={topic}"
- async with Client(mcp) as client:
- result = await client.get_prompt("research_prompt", {"topic": "AI"})
- message = result.messages[0]
- content = message.content
- assert isinstance(content, TextContent)
- assert "open=True" in content.text
+ result = await mcp.render_prompt("research_prompt", {"topic": "AI"})
+ assert isinstance(result, PromptResult)
+ message = result.messages[0]
+ content = message.content
+ assert isinstance(content, TextContent)
+ assert "open=True" in content.text
async def test_argument_validation_with_dependencies(mcp: FastMCP):
@@ -470,16 +462,17 @@ async def test_argument_validation_with_dependencies(mcp: FastMCP):
) -> str:
return f"age={age}"
- async with Client(mcp) as client:
- # Valid argument
- result = await client.call_tool("validated_tool", {"age": 25})
- content = result.content[0]
- assert isinstance(content, TextContent)
- assert content.text == "age=25"
+ # Valid argument
+ result = await mcp.call_tool("validated_tool", {"age": 25})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content is not None
+ assert result.structured_content["result"] == "age=25"
- # Invalid argument type should fail validation
- with pytest.raises(Exception): # Will be ToolError wrapping validation error
- await client.call_tool("validated_tool", {"age": "not a number"})
+ # Invalid argument type should fail validation
+ import pydantic
+
+ with pytest.raises(pydantic.ValidationError):
+ await mcp.call_tool("validated_tool", {"age": "not a number"})
async def test_connection_dependency_excluded_from_tool_schema(mcp: FastMCP):
@@ -519,12 +512,11 @@ async def test_sync_tool_context_manager_stays_open(mcp: FastMCP):
assert connection.is_open
return f"open={connection.is_open}"
- async with Client(mcp) as client:
- result = await client.call_tool("query_sync", {"query": "test"})
- content = result.content[0]
- assert isinstance(content, TextContent)
- assert content.text == "open=True"
- assert not conn.is_open
+ result = await mcp.call_tool("query_sync", {"query": "test"})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content is not None
+ assert result.structured_content["result"] == "open=True"
+ assert not conn.is_open
async def test_sync_resource_context_manager_stays_open(mcp: FastMCP):
@@ -544,12 +536,10 @@ async def test_sync_resource_context_manager_stays_open(mcp: FastMCP):
assert connection.is_open
return f"open={connection.is_open}"
- async with Client(mcp) as client:
- result = await client.read_resource("data://sync")
- content = result[0]
- assert isinstance(content, TextResourceContents)
- assert content.text == "open=True"
- assert not conn.is_open
+ result = await mcp.read_resource("data://sync")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "open=True"
+ assert not conn.is_open
async def test_sync_resource_template_context_manager_stays_open(mcp: FastMCP):
@@ -572,12 +562,11 @@ async def test_sync_resource_template_context_manager_stays_open(mcp: FastMCP):
assert connection.is_open
return f"open={connection.is_open},item={item_id}"
- async with Client(mcp) as client:
- result = await client.read_resource("item://456")
- content = result[0]
- assert isinstance(content, TextResourceContents)
- assert "open=True" in content.text
- assert not conn.is_open
+ result = await mcp.read_resource("item://456")
+ assert isinstance(result, ResourceResult)
+ assert isinstance(result.contents[0].content, str)
+ assert "open=True" in result.contents[0].content
+ assert not conn.is_open
async def test_sync_prompt_context_manager_stays_open(mcp: FastMCP):
@@ -600,13 +589,13 @@ async def test_sync_prompt_context_manager_stays_open(mcp: FastMCP):
assert connection.is_open
return f"open={connection.is_open},topic={topic}"
- async with Client(mcp) as client:
- result = await client.get_prompt("sync_prompt", {"topic": "test"})
- message = result.messages[0]
- content = message.content
- assert isinstance(content, TextContent)
- assert "open=True" in content.text
- assert not conn.is_open
+ result = await mcp.render_prompt("sync_prompt", {"topic": "test"})
+ assert isinstance(result, PromptResult)
+ message = result.messages[0]
+ content = message.content
+ assert isinstance(content, TextContent)
+ assert "open=True" in content.text
+ assert not conn.is_open
async def test_external_user_cannot_override_dependency(mcp: FastMCP):
@@ -626,18 +615,17 @@ async def test_external_user_cannot_override_dependency(mcp: FastMCP):
tool = next(t for t in tools if t.name == "check_permission")
assert "admin" not in tool.inputSchema["properties"]
- async with Client(mcp) as client:
- # Normal call - dependency is resolved
- result = await client.call_tool("check_permission", {"action": "read"})
- content = result.content[0]
- assert isinstance(content, TextContent)
- assert "admin=not_admin" in content.text
+ # Normal call - dependency is resolved
+ result = await mcp.call_tool("check_permission", {"action": "read"})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content is not None
+ assert "admin=not_admin" in result.structured_content["result"]
- # Try to override dependency - rejected (not in schema)
- with pytest.raises(Exception):
- await client.call_tool(
- "check_permission", {"action": "read", "admin": "hacker"}
- )
+ # Try to override dependency - rejected (not in schema)
+ import pydantic
+
+ with pytest.raises(pydantic.ValidationError):
+ await mcp.call_tool("check_permission", {"action": "read", "admin": "hacker"})
async def test_prompt_dependency_cannot_be_overridden_externally(mcp: FastMCP):
@@ -654,25 +642,26 @@ async def test_prompt_dependency_cannot_be_overridden_externally(mcp: FastMCP):
async def secure_prompt(topic: str, secret: str = Depends(get_secret)) -> str:
return f"Topic: {topic}, Secret: {secret}"
- async with Client(mcp) as client:
- # Normal call - should use dependency
- result = await client.get_prompt("secure_prompt", {"topic": "test"})
- message = result.messages[0]
- content = message.content
- assert isinstance(content, TextContent)
- assert "Secret: real_secret" in content.text
-
- # Try to override dependency - should be ignored/rejected
- result = await client.get_prompt(
- "secure_prompt",
- {"topic": "test", "secret": "HACKED"}, # Attempt override
- )
- message = result.messages[0]
- content = message.content
- assert isinstance(content, TextContent)
- # Should still use real dependency, not hacked value
- assert "Secret: real_secret" in content.text
- assert "HACKED" not in content.text
+ # Normal call - should use dependency
+ result = await mcp.render_prompt("secure_prompt", {"topic": "test"})
+ assert isinstance(result, PromptResult)
+ message = result.messages[0]
+ content = message.content
+ assert isinstance(content, TextContent)
+ assert "Secret: real_secret" in content.text
+
+ # Try to override dependency - should be ignored/rejected
+ result = await mcp.render_prompt(
+ "secure_prompt",
+ {"topic": "test", "secret": "HACKED"}, # Attempt override
+ )
+ assert isinstance(result, PromptResult)
+ message = result.messages[0]
+ content = message.content
+ assert isinstance(content, TextContent)
+ # Should still use real dependency, not hacked value
+ assert "Secret: real_secret" in content.text
+ assert "HACKED" not in content.text
async def test_resource_dependency_cannot_be_overridden_externally(mcp: FastMCP):
@@ -685,15 +674,14 @@ async def test_resource_dependency_cannot_be_overridden_externally(mcp: FastMCP)
async def get_config(api_key: str = Depends(get_api_key)) -> str:
return f"API Key: {api_key}"
- async with Client(mcp) as client:
- # Normal call
- result = await client.read_resource("data://config")
- content = result[0]
- assert isinstance(content, TextResourceContents)
- assert "API Key: real_api_key" in content.text
+ # Normal call
+ result = await mcp.read_resource("data://config")
+ assert isinstance(result, ResourceResult)
+ assert isinstance(result.contents[0].content, str)
+ assert "API Key: real_api_key" in result.contents[0].content
- # Resources don't accept arguments from clients (static URI)
- # so this scenario is less of a concern, but documenting it
+ # Resources don't accept arguments from clients (static URI)
+ # so this scenario is less of a concern, but documenting it
async def test_resource_template_dependency_cannot_be_overridden_externally(
@@ -712,15 +700,14 @@ async def test_resource_template_dependency_cannot_be_overridden_externally(
async def get_user(user_id: str, token: str = Depends(get_auth_token)) -> str:
return f"User: {user_id}, Token: {token}"
- async with Client(mcp) as client:
- # Normal call
- result = await client.read_resource("user://123")
- content = result[0]
- assert isinstance(content, TextResourceContents)
- assert "User: 123, Token: real_token" in content.text
+ # Normal call
+ result = await mcp.read_resource("user://123")
+ assert isinstance(result, ResourceResult)
+ assert isinstance(result.contents[0].content, str)
+ assert "User: 123, Token: real_token" in result.contents[0].content
- # Try to inject token via URI (shouldn't be possible with this pattern)
- # But if URI was user://{token}, it could extract it
+ # Try to inject token via URI (shouldn't be possible with this pattern)
+ # But if URI was user://{token}, it could extract it
async def test_resource_template_uri_cannot_match_dependency_name(mcp: FastMCP):
diff --git a/tests/server/test_mount.py b/tests/server/test_mount.py
index eec59187a..4470d7885 100644
--- a/tests/server/test_mount.py
+++ b/tests/server/test_mount.py
@@ -3,14 +3,17 @@ import sys
from contextlib import asynccontextmanager
import pytest
-from mcp.types import TextContent, TextResourceContents
+from mcp.types import TextContent
from fastmcp import FastMCP
from fastmcp.client import Client
from fastmcp.client.transports import FastMCPTransport, SSETransport
+from fastmcp.exceptions import NotFoundError
+from fastmcp.prompts import PromptResult
+from fastmcp.resources import ResourceResult
from fastmcp.server.providers import FastMCPProvider, TransformingProvider
from fastmcp.server.providers.proxy import FastMCPProxy
-from fastmcp.tools.tool import Tool
+from fastmcp.tools.tool import Tool, ToolResult
from fastmcp.tools.tool_transform import TransformedTool
from fastmcp.utilities.tests import caplog_for_fastmcp
@@ -43,9 +46,9 @@ class TestBasicMount:
assert any(t.name == "sub_tool" for t in tools)
assert any(t.name == "sub_transformed_tool" for t in tools)
- async with Client(main_app) as client:
- result = await client.call_tool("sub_tool", {})
- assert result.data == "This is from the sub app"
+ result = await main_app.call_tool("sub_tool", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "This is from the sub app"}
async def test_mount_with_custom_separator(self):
"""Test mounting with a custom tool separator (deprecated but still supported)."""
@@ -64,9 +67,9 @@ class TestBasicMount:
assert any(t.name == "sub_greet" for t in tools)
# Call the tool
- async with Client(main_app) as client:
- result = await client.call_tool("sub_greet", {"name": "World"})
- assert result.data == "Hello, World!"
+ result = await main_app.call_tool("sub_greet", {"name": "World"})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "Hello, World!"}
@pytest.mark.parametrize("prefix", ["", None])
async def test_mount_with_no_prefix(self, prefix):
@@ -101,9 +104,9 @@ class TestBasicMount:
assert any(t.name == "sub_tool" for t in tools)
# Call the tool to verify it works
- async with Client(main_app) as client:
- result = await client.call_tool("sub_tool", {})
- assert result.data == "This is from the sub app"
+ result = await main_app.call_tool("sub_tool", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "This is from the sub app"}
async def test_mount_tools_no_prefix(self):
"""Test mounting a server with tools without prefix."""
@@ -122,9 +125,9 @@ class TestBasicMount:
assert any(t.name == "sub_tool" for t in tools)
# Test actual functionality
- async with Client(main_app) as client:
- tool_result = await client.call_tool("sub_tool", {})
- assert tool_result.data == "Sub tool result"
+ tool_result = await main_app.call_tool("sub_tool", {})
+ assert isinstance(tool_result, ToolResult)
+ assert tool_result.structured_content == {"result": "Sub tool result"}
async def test_mount_resources_no_prefix(self):
"""Test mounting a server with resources without prefix."""
@@ -143,10 +146,9 @@ class TestBasicMount:
assert any(str(r.uri) == "data://config" for r in resources)
# Test actual functionality
- async with Client(main_app) as client:
- resource_result = await client.read_resource("data://config")
- assert isinstance(resource_result[0], TextResourceContents)
- assert resource_result[0].text == "Sub resource data"
+ resource_result = await main_app.read_resource("data://config")
+ assert isinstance(resource_result, ResourceResult)
+ assert resource_result.contents[0].content == "Sub resource data"
async def test_mount_resource_templates_no_prefix(self):
"""Test mounting a server with resource templates without prefix."""
@@ -165,10 +167,9 @@ class TestBasicMount:
assert any(t.uri_template == "users://{user_id}/info" for t in templates)
# Test actual functionality
- async with Client(main_app) as client:
- template_result = await client.read_resource("users://123/info")
- assert isinstance(template_result[0], TextResourceContents)
- assert template_result[0].text == "Sub template for user 123"
+ template_result = await main_app.read_resource("users://123/info")
+ assert isinstance(template_result, ResourceResult)
+ assert template_result.contents[0].content == "Sub template for user 123"
async def test_mount_prompts_no_prefix(self):
"""Test mounting a server with prompts without prefix."""
@@ -187,9 +188,9 @@ class TestBasicMount:
assert any(p.name == "sub_prompt" for p in prompts)
# Test actual functionality
- async with Client(main_app) as client:
- prompt_result = await client.get_prompt("sub_prompt", {})
- assert prompt_result.messages is not None
+ prompt_result = await main_app.render_prompt("sub_prompt")
+ assert isinstance(prompt_result, PromptResult)
+ assert prompt_result.messages is not None
class TestMultipleServerMount:
@@ -219,11 +220,12 @@ class TestMultipleServerMount:
assert any(t.name == "news_get_headlines" for t in tools)
# Call tools from both mounted servers
- async with Client(main_app) as client:
- result1 = await client.call_tool("weather_get_forecast", {})
- assert result1.data == "Weather forecast"
- result2 = await client.call_tool("news_get_headlines", {})
- assert result2.data == "News headlines"
+ result1 = await main_app.call_tool("weather_get_forecast", {})
+ assert isinstance(result1, ToolResult)
+ assert result1.structured_content == {"result": "Weather forecast"}
+ result2 = await main_app.call_tool("news_get_headlines", {})
+ assert isinstance(result2, ToolResult)
+ assert result2.structured_content == {"result": "News headlines"}
async def test_mount_same_prefix(self):
"""Test that mounting with the same prefix replaces the previous mount."""
@@ -349,16 +351,16 @@ class TestPrefixConflictResolution:
main_app.mount(first_app)
main_app.mount(second_app)
- async with Client(main_app) as client:
- # Test that list_tools shows the tool
- tools = await client.list_tools()
- tool_names = [t.name for t in tools]
- assert "shared_tool" in tool_names
- assert tool_names.count("shared_tool") == 1 # Should only appear once
+ # Test that get_tools shows the tool
+ tools = await main_app.get_tools()
+ tool_names = [t.name for t in tools]
+ assert "shared_tool" in tool_names
+ assert tool_names.count("shared_tool") == 1 # Should only appear once
- # Test that calling the tool uses the first server's implementation
- result = await client.call_tool("shared_tool", {})
- assert result.data == "First app tool"
+ # Test that calling the tool uses the first server's implementation
+ result = await main_app.call_tool("shared_tool", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "First app tool"}
async def test_first_server_wins_tools_same_prefix(self):
"""Test that first mounted server wins for tools when same prefix is used."""
@@ -378,16 +380,16 @@ class TestPrefixConflictResolution:
main_app.mount(first_app, "api")
main_app.mount(second_app, "api")
- async with Client(main_app) as client:
- # Test that list_tools shows the tool
- tools = await client.list_tools()
- tool_names = [t.name for t in tools]
- assert "api_shared_tool" in tool_names
- assert tool_names.count("api_shared_tool") == 1 # Should only appear once
+ # Test that get_tools shows the tool
+ tools = await main_app.get_tools()
+ tool_names = [t.name for t in tools]
+ assert "api_shared_tool" in tool_names
+ assert tool_names.count("api_shared_tool") == 1 # Should only appear once
- # Test that calling the tool uses the first server's implementation
- result = await client.call_tool("api_shared_tool", {})
- assert result.data == "First app tool"
+ # Test that calling the tool uses the first server's implementation
+ result = await main_app.call_tool("api_shared_tool", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "First app tool"}
async def test_first_server_wins_resources_no_prefix(self):
"""Test that first mounted server wins for resources when no prefix is used."""
@@ -407,17 +409,16 @@ class TestPrefixConflictResolution:
main_app.mount(first_app)
main_app.mount(second_app)
- async with Client(main_app) as client:
- # Test that list_resources shows the resource
- resources = await client.list_resources()
- resource_uris = [str(r.uri) for r in resources]
- assert "shared://data" in resource_uris
- assert resource_uris.count("shared://data") == 1 # Should only appear once
+ # Test that get_resources shows the resource
+ resources = await main_app.get_resources()
+ resource_uris = [str(r.uri) for r in resources]
+ assert "shared://data" in resource_uris
+ assert resource_uris.count("shared://data") == 1 # Should only appear once
- # Test that reading the resource uses the first server's implementation
- result = await client.read_resource("shared://data")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "First app data"
+ # Test that reading the resource uses the first server's implementation
+ result = await main_app.read_resource("shared://data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "First app data"
async def test_first_server_wins_resources_same_prefix(self):
"""Test that first mounted server wins for resources when same prefix is used."""
@@ -437,19 +438,16 @@ class TestPrefixConflictResolution:
main_app.mount(first_app, "api")
main_app.mount(second_app, "api")
- async with Client(main_app) as client:
- # Test that list_resources shows the resource
- resources = await client.list_resources()
- resource_uris = [str(r.uri) for r in resources]
- assert "shared://api/data" in resource_uris
- assert (
- resource_uris.count("shared://api/data") == 1
- ) # Should only appear once
-
- # Test that reading the resource uses the first server's implementation
- result = await client.read_resource("shared://api/data")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "First app data"
+ # Test that get_resources shows the resource
+ resources = await main_app.get_resources()
+ resource_uris = [str(r.uri) for r in resources]
+ assert "shared://api/data" in resource_uris
+ assert resource_uris.count("shared://api/data") == 1 # Should only appear once
+
+ # Test that reading the resource uses the first server's implementation
+ result = await main_app.read_resource("shared://api/data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "First app data"
async def test_first_server_wins_resource_templates_no_prefix(self):
"""Test that first mounted server wins for resource templates when no prefix is used."""
@@ -469,19 +467,18 @@ class TestPrefixConflictResolution:
main_app.mount(first_app)
main_app.mount(second_app)
- async with Client(main_app) as client:
- # Test that list_resource_templates shows the template
- templates = await client.list_resource_templates()
- template_uris = [t.uriTemplate for t in templates]
- assert "users://{user_id}/profile" in template_uris
- assert (
- template_uris.count("users://{user_id}/profile") == 1
- ) # Should only appear once
-
- # Test that reading the resource uses the first server's implementation
- result = await client.read_resource("users://123/profile")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "First app user 123"
+ # Test that get_resource_templates shows the template
+ templates = await main_app.get_resource_templates()
+ template_uris = [t.uri_template for t in templates]
+ assert "users://{user_id}/profile" in template_uris
+ assert (
+ template_uris.count("users://{user_id}/profile") == 1
+ ) # Should only appear once
+
+ # Test that reading the resource uses the first server's implementation
+ result = await main_app.read_resource("users://123/profile")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "First app user 123"
async def test_first_server_wins_resource_templates_same_prefix(self):
"""Test that first mounted server wins for resource templates when same prefix is used."""
@@ -501,19 +498,18 @@ class TestPrefixConflictResolution:
main_app.mount(first_app, "api")
main_app.mount(second_app, "api")
- async with Client(main_app) as client:
- # Test that list_resource_templates shows the template
- templates = await client.list_resource_templates()
- template_uris = [t.uriTemplate for t in templates]
- assert "users://api/{user_id}/profile" in template_uris
- assert (
- template_uris.count("users://api/{user_id}/profile") == 1
- ) # Should only appear once
-
- # Test that reading the resource uses the first server's implementation
- result = await client.read_resource("users://api/123/profile")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "First app user 123"
+ # Test that get_resource_templates shows the template
+ templates = await main_app.get_resource_templates()
+ template_uris = [t.uri_template for t in templates]
+ assert "users://api/{user_id}/profile" in template_uris
+ assert (
+ template_uris.count("users://api/{user_id}/profile") == 1
+ ) # Should only appear once
+
+ # Test that reading the resource uses the first server's implementation
+ result = await main_app.read_resource("users://api/123/profile")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "First app user 123"
async def test_first_server_wins_prompts_no_prefix(self):
"""Test that first mounted server wins for prompts when no prefix is used."""
@@ -533,18 +529,18 @@ class TestPrefixConflictResolution:
main_app.mount(first_app)
main_app.mount(second_app)
- async with Client(main_app) as client:
- # Test that list_prompts shows the prompt
- prompts = await client.list_prompts()
- prompt_names = [p.name for p in prompts]
- assert "shared_prompt" in prompt_names
- assert prompt_names.count("shared_prompt") == 1 # Should only appear once
-
- # Test that getting the prompt uses the first server's implementation
- result = await client.get_prompt("shared_prompt", {})
- assert result.messages is not None
- assert isinstance(result.messages[0].content, TextContent)
- assert result.messages[0].content.text == "First app prompt"
+ # Test that get_prompts shows the prompt
+ prompts = await main_app.get_prompts()
+ prompt_names = [p.name for p in prompts]
+ assert "shared_prompt" in prompt_names
+ assert prompt_names.count("shared_prompt") == 1 # Should only appear once
+
+ # Test that getting the prompt uses the first server's implementation
+ result = await main_app.render_prompt("shared_prompt")
+ assert isinstance(result, PromptResult)
+ assert result.messages is not None
+ assert isinstance(result.messages[0].content, TextContent)
+ assert result.messages[0].content.text == "First app prompt"
async def test_first_server_wins_prompts_same_prefix(self):
"""Test that first mounted server wins for prompts when same prefix is used."""
@@ -564,20 +560,18 @@ class TestPrefixConflictResolution:
main_app.mount(first_app, "api")
main_app.mount(second_app, "api")
- async with Client(main_app) as client:
- # Test that list_prompts shows the prompt
- prompts = await client.list_prompts()
- prompt_names = [p.name for p in prompts]
- assert "api_shared_prompt" in prompt_names
- assert (
- prompt_names.count("api_shared_prompt") == 1
- ) # Should only appear once
+ # Test that get_prompts shows the prompt
+ prompts = await main_app.get_prompts()
+ prompt_names = [p.name for p in prompts]
+ assert "api_shared_prompt" in prompt_names
+ assert prompt_names.count("api_shared_prompt") == 1 # Should only appear once
- # Test that getting the prompt uses the first server's implementation
- result = await client.get_prompt("api_shared_prompt", {})
- assert result.messages is not None
- assert isinstance(result.messages[0].content, TextContent)
- assert result.messages[0].content.text == "First app prompt"
+ # Test that getting the prompt uses the first server's implementation
+ result = await main_app.render_prompt("api_shared_prompt")
+ assert isinstance(result, PromptResult)
+ assert result.messages is not None
+ assert isinstance(result.messages[0].content, TextContent)
+ assert result.messages[0].content.text == "First app prompt"
class TestDynamicChanges:
@@ -605,9 +599,9 @@ class TestDynamicChanges:
assert any(t.name == "sub_dynamic_tool" for t in tools)
# Call the dynamically added tool
- async with Client(main_app) as client:
- result = await client.call_tool("sub_dynamic_tool", {})
- assert result.data == "Added after mounting"
+ result = await main_app.call_tool("sub_dynamic_tool", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "Added after mounting"}
async def test_removing_tool_after_mounting(self):
"""Test that tools removed from mounted servers are no longer accessible."""
@@ -653,11 +647,12 @@ class TestResourcesAndTemplates:
assert any(str(r.uri) == "data://data/users" for r in resources)
# Check that resource can be accessed
- async with Client(main_app) as client:
- result = await client.read_resource("data://data/users")
- assert len(result) == 1
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "user1, user2"
+ result = await main_app.read_resource("data://data/users")
+ assert isinstance(result, ResourceResult)
+ assert len(result.contents) == 1
+ # Note: The function returns "user1, user2" which is not valid JSON
+ # This test should be updated to return proper JSON or check the string directly
+ assert result.contents[0].content == "user1, user2"
async def test_mount_with_resource_templates(self):
"""Test mounting a server with resource templates."""
@@ -676,12 +671,12 @@ class TestResourcesAndTemplates:
assert any(t.uri_template == "users://api/{user_id}/profile" for t in templates)
# Check template instantiation
- async with Client(main_app) as client:
- result = await client.read_resource("users://api/123/profile")
- assert isinstance(result[0], TextResourceContents)
- profile = json.loads(result[0].text)
- assert profile["id"] == "123"
- assert profile["name"] == "User 123"
+ result = await main_app.read_resource("users://api/123/profile")
+ assert isinstance(result, ResourceResult)
+ assert len(result.contents) == 1
+ profile = json.loads(result.contents[0].content)
+ assert profile["id"] == "123"
+ assert profile["name"] == "User 123"
async def test_adding_resource_after_mounting(self):
"""Test adding a resource after mounting."""
@@ -701,11 +696,11 @@ class TestResourcesAndTemplates:
assert any(str(r.uri) == "data://data/config" for r in resources)
# Check access to the resource
- async with Client(main_app) as client:
- result = await client.read_resource("data://data/config")
- assert isinstance(result[0], TextResourceContents)
- config = json.loads(result[0].text)
- assert config["version"] == "1.0"
+ result = await main_app.read_resource("data://data/config")
+ assert isinstance(result, ResourceResult)
+ assert len(result.contents) == 1
+ config = json.loads(result.contents[0].content)
+ assert config["version"] == "1.0"
class TestPrompts:
@@ -728,9 +723,9 @@ class TestPrompts:
assert any(p.name == "assistant_greeting" for p in prompts)
# Render the prompt
- async with Client(main_app) as client:
- result = await client.get_prompt("assistant_greeting", {"name": "World"})
- assert result.messages is not None
+ result = await main_app.render_prompt("assistant_greeting", {"name": "World"})
+ assert isinstance(result, PromptResult)
+ assert result.messages is not None
# The message should contain our greeting text
async def test_adding_prompt_after_mounting(self):
@@ -751,9 +746,9 @@ class TestPrompts:
assert any(p.name == "assistant_farewell" for p in prompts)
# Render the prompt
- async with Client(main_app) as client:
- result = await client.get_prompt("assistant_farewell", {"name": "World"})
- assert result.messages is not None
+ result = await main_app.render_prompt("assistant_farewell", {"name": "World"})
+ assert isinstance(result, PromptResult)
+ assert result.messages is not None
# The message should contain our farewell text
@@ -781,9 +776,9 @@ class TestProxyServer:
assert any(t.name == "proxy_get_data" for t in tools)
# Call the tool
- async with Client(main_app) as client:
- result = await client.call_tool("proxy_get_data", {"query": "test"})
- assert result.data == "Data for test"
+ result = await main_app.call_tool("proxy_get_data", {"query": "test"})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "Data for test"}
async def test_dynamically_adding_to_proxied_server(self):
"""Test that changes to the original server are reflected in the mounted proxy."""
@@ -807,9 +802,9 @@ class TestProxyServer:
assert any(t.name == "proxy_dynamic_data" for t in tools)
# Call the tool
- async with Client(main_app) as client:
- result = await client.call_tool("proxy_dynamic_data", {})
- assert result.data == "Dynamic data"
+ result = await main_app.call_tool("proxy_dynamic_data", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "Dynamic data"}
async def test_proxy_server_with_resources(self):
"""Test mounting a proxy server with resources."""
@@ -828,11 +823,11 @@ class TestProxyServer:
main_app.mount(proxy_server, "proxy")
# Resource should be accessible through main app
- async with Client(main_app) as client:
- result = await client.read_resource("config://proxy/settings")
- assert isinstance(result[0], TextResourceContents)
- config = json.loads(result[0].text)
- assert config["api_key"] == "12345"
+ result = await main_app.read_resource("config://proxy/settings")
+ assert isinstance(result, ResourceResult)
+ assert len(result.contents) == 1
+ config = json.loads(result.contents[0].content)
+ assert config["api_key"] == "12345"
async def test_proxy_server_with_prompts(self):
"""Test mounting a proxy server with prompts."""
@@ -851,9 +846,9 @@ class TestProxyServer:
main_app.mount(proxy_server, "proxy")
# Prompt should be accessible through main app
- async with Client(main_app) as client:
- result = await client.get_prompt("proxy_welcome", {"name": "World"})
- assert result.messages is not None
+ result = await main_app.render_prompt("proxy_welcome", {"name": "World"})
+ assert isinstance(result, PromptResult)
+ assert result.messages is not None
# The message should contain our welcome text
@@ -1077,18 +1072,18 @@ class TestParentTagFiltering:
parent.mount(mounted)
- async with Client(parent) as client:
- tools = await client.list_tools()
- tool_names = {t.name for t in tools}
- assert "allowed_tool" in tool_names
- assert "blocked_tool" not in tool_names
+ tools = await parent.get_tools()
+ tool_names = {t.name for t in tools}
+ assert "allowed_tool" in tool_names
+ assert "blocked_tool" not in tool_names
- # Verify execution also respects filters
- result = await client.call_tool("allowed_tool", {})
- assert result.data == "allowed"
+ # Verify execution also respects filters
+ result = await parent.call_tool("allowed_tool", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "allowed"}
- with pytest.raises(Exception, match="Unknown tool"):
- await client.call_tool("blocked_tool", {})
+ with pytest.raises(NotFoundError, match="Unknown tool"):
+ await parent.call_tool("blocked_tool", {})
async def test_parent_exclude_tags_filters_mounted_tools(self):
"""Test that parent exclude_tags filters out matching mounted tools."""
@@ -1105,11 +1100,10 @@ class TestParentTagFiltering:
parent.mount(mounted)
- async with Client(parent) as client:
- tools = await client.list_tools()
- tool_names = {t.name for t in tools}
- assert "production_tool" in tool_names
- assert "blocked_tool" not in tool_names
+ tools = await parent.get_tools()
+ tool_names = {t.name for t in tools}
+ assert "production_tool" in tool_names
+ assert "blocked_tool" not in tool_names
async def test_parent_filters_apply_to_mounted_resources(self):
"""Test that parent tag filters apply to mounted resources."""
@@ -1126,11 +1120,10 @@ class TestParentTagFiltering:
parent.mount(mounted)
- async with Client(parent) as client:
- resources = await client.list_resources()
- resource_uris = {str(r.uri) for r in resources}
- assert "resource://allowed" in resource_uris
- assert "resource://blocked" not in resource_uris
+ resources = await parent.get_resources()
+ resource_uris = {str(r.uri) for r in resources}
+ assert "resource://allowed" in resource_uris
+ assert "resource://blocked" not in resource_uris
async def test_parent_filters_apply_to_mounted_prompts(self):
"""Test that parent tag filters apply to mounted prompts."""
@@ -1147,11 +1140,10 @@ class TestParentTagFiltering:
parent.mount(mounted)
- async with Client(parent) as client:
- prompts = await client.list_prompts()
- prompt_names = {p.name for p in prompts}
- assert "allowed_prompt" in prompt_names
- assert "blocked_prompt" not in prompt_names
+ prompts = await parent.get_prompts()
+ prompt_names = {p.name for p in prompts}
+ assert "allowed_prompt" in prompt_names
+ assert "blocked_prompt" not in prompt_names
class TestCustomRouteForwarding:
@@ -1257,14 +1249,15 @@ class TestDeeplyNestedMount:
middle.mount(leaf, namespace="leaf")
root.mount(middle, namespace="middle")
- async with Client(root) as client:
- # Tool at level 2 should work
- result = await client.call_tool("middle_multiply", {"a": 3, "b": 4})
- assert result.data == 12
+ # Tool at level 2 should work
+ result = await root.call_tool("middle_multiply", {"a": 3, "b": 4})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": 12}
- # Tool at level 3 should also work (this was the bug)
- result = await client.call_tool("middle_leaf_add", {"a": 5, "b": 7})
- assert result.data == 12
+ # Tool at level 3 should also work (this was the bug)
+ result = await root.call_tool("middle_leaf_add", {"a": 5, "b": 7})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": 12}
async def test_three_level_nested_resource_invocation(self):
"""Test reading resources from servers mounted 3 levels deep."""
@@ -1283,14 +1276,15 @@ class TestDeeplyNestedMount:
middle.mount(leaf, namespace="leaf")
root.mount(middle, namespace="middle")
- async with Client(root) as client:
- # Resource at level 2 should work
- result = await client.read_resource("middle://middle/data")
- assert result[0].text == "middle data"
+ # Resource at level 2 should work
+ result = await root.read_resource("middle://middle/data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "middle data"
- # Resource at level 3 should also work
- result = await client.read_resource("leaf://middle/leaf/data")
- assert result[0].text == "leaf data"
+ # Resource at level 3 should also work
+ result = await root.read_resource("leaf://middle/leaf/data")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "leaf data"
async def test_three_level_nested_resource_template_invocation(self):
"""Test reading resource templates from servers mounted 3 levels deep."""
@@ -1309,14 +1303,15 @@ class TestDeeplyNestedMount:
middle.mount(leaf, namespace="leaf")
root.mount(middle, namespace="middle")
- async with Client(root) as client:
- # Resource template at level 2 should work
- result = await client.read_resource("middle://middle/item/42")
- assert result[0].text == "middle item 42"
+ # Resource template at level 2 should work
+ result = await root.read_resource("middle://middle/item/42")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "middle item 42"
- # Resource template at level 3 should also work
- result = await client.read_resource("leaf://middle/leaf/item/99")
- assert result[0].text == "leaf item 99"
+ # Resource template at level 3 should also work
+ result = await root.read_resource("leaf://middle/leaf/item/99")
+ assert isinstance(result, ResourceResult)
+ assert result.contents[0].content == "leaf item 99"
async def test_three_level_nested_prompt_invocation(self):
"""Test getting prompts from servers mounted 3 levels deep."""
@@ -1335,18 +1330,17 @@ class TestDeeplyNestedMount:
middle.mount(leaf, namespace="leaf")
root.mount(middle, namespace="middle")
- async with Client(root) as client:
- # Prompt at level 2 should work
- result = await client.get_prompt("middle_middle_prompt", {"name": "World"})
- assert isinstance(result.messages[0].content, TextContent)
- assert "Hello from middle: World" in result.messages[0].content.text
+ # Prompt at level 2 should work
+ result = await root.render_prompt("middle_middle_prompt", {"name": "World"})
+ assert isinstance(result, PromptResult)
+ assert isinstance(result.messages[0].content, TextContent)
+ assert "Hello from middle: World" in result.messages[0].content.text
- # Prompt at level 3 should also work
- result = await client.get_prompt(
- "middle_leaf_leaf_prompt", {"name": "Test"}
- )
- assert isinstance(result.messages[0].content, TextContent)
- assert "Hello from leaf: Test" in result.messages[0].content.text
+ # Prompt at level 3 should also work
+ result = await root.render_prompt("middle_leaf_leaf_prompt", {"name": "Test"})
+ assert isinstance(result, PromptResult)
+ assert isinstance(result.messages[0].content, TextContent)
+ assert "Hello from leaf: Test" in result.messages[0].content.text
async def test_four_level_nested_tool_invocation(self):
"""Test invoking tools from servers mounted 4 levels deep."""
@@ -1363,15 +1357,15 @@ class TestDeeplyNestedMount:
level1.mount(level2, namespace="l2")
root.mount(level1, namespace="l1")
- async with Client(root) as client:
- # Verify tool is listed
- tools = await client.list_tools()
- tool_names = [t.name for t in tools]
- assert "l1_l2_l3_deep_tool" in tool_names
+ # Verify tool is listed
+ tools = await root.get_tools()
+ tool_names = [t.name for t in tools]
+ assert "l1_l2_l3_deep_tool" in tool_names
- # Tool at level 4 should work
- result = await client.call_tool("l1_l2_l3_deep_tool", {})
- assert result.data == "very deep"
+ # Tool at level 4 should work
+ result = await root.call_tool("l1_l2_l3_deep_tool", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "very deep"}
class TestToolNameOverrides:
@@ -1400,16 +1394,10 @@ class TestToolNameOverrides:
# Server introspection shows transformed names
tools = await main.get_tools()
- assert any(t.name == "custom_name" for t in tools)
- assert not any(t.name == "original_tool" for t in tools)
- assert not any(t.name == "prefix_original_tool" for t in tools)
-
- # Client-facing API shows the same transformed names
- async with Client(main) as client:
- client_tools = await client.list_tools()
- tool_names = [t.name for t in client_tools]
- assert "custom_name" in tool_names
- assert "prefix_original_tool" not in tool_names
+ tool_names = [t.name for t in tools]
+ assert "custom_name" in tool_names
+ assert "original_tool" not in tool_names
+ assert "prefix_original_tool" not in tool_names
async def test_tool_names_override_applied_in_list_tools(self):
"""Test that tool_names override is reflected in list_tools()."""
@@ -1426,11 +1414,10 @@ class TestToolNameOverrides:
tool_names={"original_tool": "custom_name"},
)
- async with Client(main) as client:
- tools = await client.list_tools()
- tool_names = [t.name for t in tools]
- assert "custom_name" in tool_names
- assert "prefix_original_tool" not in tool_names
+ tools = await main.get_tools()
+ tool_names = [t.name for t in tools]
+ assert "custom_name" in tool_names
+ assert "prefix_original_tool" not in tool_names
async def test_tool_call_with_overridden_name(self):
"""Test that overridden tool can be called by its new name."""
@@ -1447,9 +1434,9 @@ class TestToolNameOverrides:
tool_names={"original_tool": "renamed"},
)
- async with Client(main) as client:
- result = await client.call_tool("renamed", {})
- assert result.data == "success"
+ result = await main.call_tool("renamed", {})
+ assert isinstance(result, ToolResult)
+ assert result.structured_content == {"result": "success"}
def test_duplicate_tool_rename_targets_raises_error(self):
"""Test that duplicate target names in tool_renames raises ValueError."""
diff --git a/tests/server/test_providers.py b/tests/server/test_providers.py
index 9fe2d3bbe..70a2973c0 100644
--- a/tests/server/test_providers.py
+++ b/tests/server/test_providers.py
@@ -5,12 +5,10 @@ from typing import Any
import pytest
from mcp.types import AnyUrl, TextContent
-from mcp.types import Tool as MCPTool
from fastmcp import FastMCP
-from fastmcp.client import Client
-from fastmcp.client.client import CallToolResult
-from fastmcp.prompts.prompt import FunctionPrompt, Prompt
+from fastmcp.prompts.prompt import FunctionPrompt, Prompt, PromptResult
+from fastmcp.resources import ResourceResult
from fastmcp.resources.resource import FunctionResource, Resource
from fastmcp.resources.template import FunctionResourceTemplate, ResourceTemplate
from fastmcp.server.providers import Provider
@@ -128,8 +126,7 @@ class TestProvider:
provider = SimpleToolProvider(tools=dynamic_tools)
base_server.add_provider(provider)
- async with Client(base_server) as client:
- tools: list[MCPTool] = await client.list_tools()
+ tools = await base_server.get_tools()
# Should have all tools: 2 static + 2 dynamic
assert len(tools) == 4
@@ -146,15 +143,13 @@ class TestProvider:
provider = SimpleToolProvider(tools=dynamic_tools)
base_server.add_provider(provider)
- async with Client(base_server) as client:
- # Call list_tools multiple times
- await client.list_tools()
- await client.list_tools()
- await client.list_tools()
+ # Call get_tools multiple times
+ await base_server.get_tools()
+ await base_server.get_tools()
+ await base_server.get_tools()
- # Provider should have been called 4 times
- # (1 from get_tasks() during docket registration + 3 from client)
- assert provider.list_tools_call_count == 4
+ # Provider should have been called 3 times (once per get_tools call)
+ assert provider.list_tools_call_count == 3
async def test_call_dynamic_tool(
self, base_server: FastMCP, dynamic_tools: list[Tool]
@@ -163,11 +158,11 @@ class TestProvider:
provider = SimpleToolProvider(tools=dynamic_tools)
base_server.add_provider(provider)
- async with Client(base_server) as client:
- result: CallToolResult = await client.call_tool(
- name="dynamic_multiply", arguments={"a": 7, "b": 6}
- )
+ result = await base_server.call_tool(
+ name="dynamic_multiply", arguments={"a": 7, "b": 6}
+ )
+ assert isinstance(result, ToolResult)
assert result.structured_content is not None
assert isinstance(result.structured_content, dict)
assert result.structured_content["result"] == 42
@@ -180,11 +175,11 @@ class TestProvider:
provider = SimpleToolProvider(tools=dynamic_tools)
base_server.add_provider(provider)
- async with Client(base_server) as client:
- result: CallToolResult = await client.call_tool(
- name="dynamic_add", arguments={"a": 5, "b": 3}
- )
+ result = await base_server.call_tool(
+ name="dynamic_add", arguments={"a": 5, "b": 3}
+ )
+ assert isinstance(result, ToolResult)
assert result.structured_content is not None
# 5 + 3 + 100 (value offset) = 108
assert isinstance(result.structured_content, dict)
@@ -197,11 +192,11 @@ class TestProvider:
provider = SimpleToolProvider(tools=dynamic_tools)
base_server.add_provider(provider)
- async with Client(base_server) as client:
- result: CallToolResult = await client.call_tool(
- name="static_add", arguments={"a": 10, "b": 5}
- )
+ result = await base_server.call_tool(
+ name="static_add", arguments={"a": 10, "b": 5}
+ )
+ assert isinstance(result, ToolResult)
assert result.structured_content is not None
assert isinstance(result.structured_content, dict)
assert result.structured_content["result"] == 15
@@ -213,12 +208,10 @@ class TestProvider:
provider = SimpleToolProvider(tools=dynamic_tools)
base_server.add_provider(provider)
- async with Client(base_server) as client:
- await client.call_tool(name="dynamic_multiply", arguments={"a": 2, "b": 3})
+ await base_server.call_tool(name="dynamic_multiply", arguments={"a": 2, "b": 3})
# get_tool is called once for efficient lookup:
- # _call_tool() calls provider.get_tool() to get the tool and execute it
- # (task config is checked inside the tool's _run() method, not via a separate lookup)
+ # call_tool() calls provider.get_tool() to get the tool and execute it
# Key point: list_tools is NOT called during tool execution (efficient lookup)
assert provider.get_tool_call_count == 1
@@ -235,11 +228,11 @@ class TestProvider:
provider = ListOnlyProvider(tools=tools)
base_server.add_provider(provider)
- async with Client(base_server) as client:
- result = await client.call_tool(
- name="test_tool", arguments={"a": 1, "b": 2}
- )
+ result = await base_server.call_tool(
+ name="test_tool", arguments={"a": 1, "b": 2}
+ )
+ assert isinstance(result, ToolResult)
assert result.structured_content is not None
# Default get_tool should have called list_tools
assert provider.list_tools_call_count >= 1
@@ -251,8 +244,7 @@ class TestProvider:
provider = SimpleToolProvider(tools=dynamic_tools)
base_server.add_provider(provider)
- async with Client(base_server) as client:
- tools: list[MCPTool] = await client.list_tools()
+ tools = await base_server.get_tools()
tool_names = [tool.name for tool in tools]
# Local tools should come first (LocalProvider is first in _providers)
@@ -263,8 +255,7 @@ class TestProvider:
provider = SimpleToolProvider(tools=[])
base_server.add_provider(provider)
- async with Client(base_server) as client:
- tools: list[MCPTool] = await client.list_tools()
+ tools = await base_server.get_tools()
# Should only have static tools
assert len(tools) == 2
@@ -276,12 +267,12 @@ class TestProvider:
provider = SimpleToolProvider(tools=dynamic_tools)
base_server.add_provider(provider)
- async with Client(base_server) as client:
- # This tool is static, not in the dynamic provider
- result: CallToolResult = await client.call_tool(
- name="static_subtract", arguments={"a": 10, "b": 3}
- )
+ # This tool is static, not in the dynamic provider
+ result = await base_server.call_tool(
+ name="static_subtract", arguments={"a": 10, "b": 3}
+ )
+ assert isinstance(result, ToolResult)
assert result.structured_content is not None
assert isinstance(result.structured_content, dict)
assert result.structured_content["result"] == 7
@@ -334,34 +325,33 @@ class TestDynamicToolUpdates:
provider = SimpleToolProvider(tools=initial_tools)
mcp.add_provider(provider)
- async with Client(mcp) as client:
- tools = await client.list_tools()
- assert len(tools) == 1
- assert tools[0].name == "tool_v1"
-
- # Update the provider's tools (simulating DB update)
- provider._tools = [
- SimpleTool(
- name="tool_v2",
- description="Version 2",
- parameters={"type": "object", "properties": {}},
- operation="multiply",
- ),
- SimpleTool(
- name="tool_v3",
- description="Version 3",
- parameters={"type": "object", "properties": {}},
- operation="add",
- ),
- ]
-
- # List tools again - should see new tools
- tools = await client.list_tools()
- assert len(tools) == 2
- tool_names = [t.name for t in tools]
- assert "tool_v1" not in tool_names
- assert "tool_v2" in tool_names
- assert "tool_v3" in tool_names
+ tools = await mcp.get_tools()
+ assert len(tools) == 1
+ assert tools[0].name == "tool_v1"
+
+ # Update the provider's tools (simulating DB update)
+ provider._tools = [
+ SimpleTool(
+ name="tool_v2",
+ description="Version 2",
+ parameters={"type": "object", "properties": {}},
+ operation="multiply",
+ ),
+ SimpleTool(
+ name="tool_v3",
+ description="Version 3",
+ parameters={"type": "object", "properties": {}},
+ operation="add",
+ ),
+ ]
+
+ # List tools again - should see new tools
+ tools = await mcp.get_tools()
+ assert len(tools) == 2
+ tool_names = [t.name for t in tools]
+ assert "tool_v1" not in tool_names
+ assert "tool_v2" in tool_names
+ assert "tool_v3" in tool_names
class TestProviderExecutionMethods:
@@ -379,9 +369,9 @@ class TestProviderExecutionMethods:
mcp = FastMCP("TestServer")
mcp.add_provider(provider)
- async with Client(mcp) as client:
- result = await client.call_tool("test_tool", {"a": 1, "b": 2})
+ result = await mcp.call_tool("test_tool", {"a": 1, "b": 2})
+ assert isinstance(result, ToolResult)
assert result.structured_content is not None
assert isinstance(result.structured_content, dict)
assert result.structured_content["result"] == 3
@@ -403,11 +393,11 @@ class TestProviderExecutionMethods:
mcp = FastMCP("TestServer")
mcp.add_provider(provider)
- async with Client(mcp) as client:
- result = await client.read_resource("test://data")
+ result = await mcp.read_resource("test://data")
- assert len(result) == 1
- assert result[0].text == "hello world"
+ assert isinstance(result, ResourceResult)
+ assert len(result.contents) == 1
+ assert result.contents[0].content == "hello world"
async def test_read_resource_template_default(self):
"""Test that read_resource_template handles template-based resources."""
@@ -426,11 +416,11 @@ class TestProviderExecutionMethods:
mcp = FastMCP("TestServer")
mcp.add_provider(provider)
- async with Client(mcp) as client:
- result = await client.read_resource("data://files/test.txt")
+ result = await mcp.read_resource("data://files/test.txt")
- assert len(result) == 1
- assert result[0].text == "content of test.txt"
+ assert isinstance(result, ResourceResult)
+ assert len(result.contents) == 1
+ assert result.contents[0].content == "content of test.txt"
async def test_render_prompt_default_implementation(self):
"""Test that default render_prompt uses get_prompt and renders it."""
@@ -449,9 +439,9 @@ class TestProviderExecutionMethods:
mcp = FastMCP("TestServer")
mcp.add_provider(provider)
- async with Client(mcp) as client:
- result = await client.get_prompt("greeting", {"name": "World"})
+ result = await mcp.render_prompt("greeting", {"name": "World"})
+ assert isinstance(result, PromptResult)
assert len(result.messages) == 1
assert isinstance(result.messages[0].content, TextContent)
assert result.messages[0].content.text == "Hello, World!"
diff --git a/tests/server/test_server.py b/tests/server/test_server.py
index 772e1599b..725e2a041 100644
--- a/tests/server/test_server.py
+++ b/tests/server/test_server.py
@@ -2,13 +2,12 @@ from pathlib import Path
from tempfile import TemporaryDirectory
from textwrap import dedent
-import pytest
from mcp.types import TextContent, TextResourceContents
from fastmcp import Client, FastMCP
-from fastmcp.exceptions import NotFoundError
from fastmcp.tools import FunctionTool
from fastmcp.tools.tool import Tool
+from fastmcp.utilities.tests import temporary_settings
class TestCreateServer:
@@ -48,73 +47,6 @@ class TestCreateServer:
assert result.data == "Β‘Hola, δΈ–η•Œ! πŸ‘‹"
-class TestTools:
- async def test_mcp_tool_name(self):
- """Test MCPTool name for add_tool (key != tool.name)."""
-
- mcp = FastMCP()
-
- @mcp.tool
- def fn(x: int) -> int:
- return x + 1
-
- mcp_tools = await mcp._list_tools_mcp()
- assert len(mcp_tools) == 1
- assert mcp_tools[0].name == "fn"
-
- async def test_mcp_tool_custom_name(self):
- """Test MCPTool name for add_tool (key != tool.name)."""
-
- mcp = FastMCP()
-
- @mcp.tool(name="custom_name")
- def fn(x: int) -> int:
- return x + 1
-
- mcp_tools = await mcp._list_tools_mcp()
- assert len(mcp_tools) == 1
- assert mcp_tools[0].name == "custom_name"
-
- async def test_remove_tool_successfully(self):
- """Test that FastMCP.remove_tool removes the tool from the registry."""
-
- mcp = FastMCP()
-
- @mcp.tool(name="adder")
- def add(a: int, b: int) -> int:
- return a + b
-
- mcp_tools = await mcp.get_tools()
- assert any(t.name == "adder" for t in mcp_tools)
-
- mcp.remove_tool("adder")
- mcp_tools = await mcp.get_tools()
- assert not any(t.name == "adder" for t in mcp_tools)
-
- with pytest.raises(NotFoundError, match="Unknown tool: 'adder'"):
- await mcp._call_tool_mcp("adder", {"a": 1, "b": 2})
-
- async def test_add_tool_at_init(self):
- def f(x: int) -> int:
- return x + 1
-
- def g(x: int) -> int:
- """add two to a number"""
- return x + 2
-
- g_tool = FunctionTool.from_function(g, name="g-tool")
-
- mcp = FastMCP(tools=[f, g_tool])
-
- tools = await mcp.get_tools()
- assert len(tools) == 2
- f_tool = next(t for t in tools if t.name == "f")
- g_tool = next(t for t in tools if t.name == "g-tool")
- assert f_tool.name == "f"
- assert g_tool.name == "g-tool"
- assert g_tool.description == "add two to a number"
-
-
class TestServerDelegation:
"""Test that FastMCP properly delegates to LocalProvider."""
@@ -331,3 +263,179 @@ class TestAbstractCollectionTypes:
result = await client.call_tool("greet", {"name": "World"})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "Hello, World!"
+
+
+class TestMeta:
+ """Test that include_fastmcp_meta controls whether _fastmcp key is present in meta."""
+
+ async def test_tool_tags_in_meta_with_default_setting(self):
+ """Test that tool tags appear in meta under _fastmcp key with default setting."""
+ mcp = FastMCP()
+
+ @mcp.tool(tags={"tool-example", "test-tool-tag"})
+ def sample_tool(x: int) -> int:
+ """A sample tool."""
+ return x * 2
+
+ async with Client(mcp) as client:
+ tools = await client.list_tools()
+ tool = next(t for t in tools if t.name == "sample_tool")
+ assert tool.meta is not None
+ assert set(tool.meta["_fastmcp"]["tags"]) == {
+ "tool-example",
+ "test-tool-tag",
+ }
+
+ async def test_resource_tags_in_meta_with_default_setting(self):
+ """Test that resource tags appear in meta under _fastmcp key with default setting."""
+ mcp = FastMCP()
+
+ @mcp.resource(
+ uri="test://resource", tags={"resource-example", "test-resource-tag"}
+ )
+ def sample_resource() -> str:
+ """A sample resource."""
+ return "resource content"
+
+ async with Client(mcp) as client:
+ resources = await client.list_resources()
+ resource = next(r for r in resources if str(r.uri) == "test://resource")
+ assert resource.meta is not None
+ assert set(resource.meta["_fastmcp"]["tags"]) == {
+ "resource-example",
+ "test-resource-tag",
+ }
+
+ async def test_resource_template_tags_in_meta_with_default_setting(self):
+ """Test that resource template tags appear in meta under _fastmcp key with default setting."""
+ mcp = FastMCP()
+
+ @mcp.resource(
+ "test://template/{id}", tags={"template-example", "test-template-tag"}
+ )
+ def sample_template(id: str) -> str:
+ """A sample resource template."""
+ return f"template content for {id}"
+
+ async with Client(mcp) as client:
+ templates = await client.list_resource_templates()
+ template = next(
+ t for t in templates if t.uriTemplate == "test://template/{id}"
+ )
+ assert template.meta is not None
+ assert set(template.meta["_fastmcp"]["tags"]) == {
+ "template-example",
+ "test-template-tag",
+ }
+
+ async def test_prompt_tags_in_meta_with_default_setting(self):
+ """Test that prompt tags appear in meta under _fastmcp key with default setting."""
+ mcp = FastMCP()
+
+ @mcp.prompt(tags={"example", "test-tag"})
+ def sample_prompt() -> str:
+ return "Hello, world!"
+
+ async with Client(mcp) as client:
+ prompts = await client.list_prompts()
+ prompt = next(p for p in prompts if p.name == "sample_prompt")
+ assert prompt.meta is not None
+ assert set(prompt.meta["_fastmcp"]["tags"]) == {"example", "test-tag"}
+
+ async def test_tool_meta_with_include_fastmcp_meta_false(self):
+ mcp = FastMCP(include_fastmcp_meta=False)
+
+ @mcp.tool(tags={"tool-example", "test-tool-tag"})
+ def sample_tool(x: int) -> int:
+ """A sample tool."""
+ return x * 2
+
+ async with Client(mcp) as client:
+ tools = await client.list_tools()
+ tool = next(t for t in tools if t.name == "sample_tool")
+ # Meta should be None when include_fastmcp_meta is False
+ assert tool.meta is None
+
+ async def test_resource_meta_with_include_fastmcp_meta_false(self):
+ mcp = FastMCP(include_fastmcp_meta=False)
+
+ @mcp.resource(
+ uri="test://resource", tags={"resource-example", "test-resource-tag"}
+ )
+ def sample_resource() -> str:
+ """A sample resource."""
+ return "resource content"
+
+ async with Client(mcp) as client:
+ resources = await client.list_resources()
+ resource = next(r for r in resources if str(r.uri) == "test://resource")
+ # Meta should be None when include_fastmcp_meta is False
+ assert resource.meta is None
+
+ async def test_resource_template_meta_with_include_fastmcp_meta_false(self):
+ mcp = FastMCP(include_fastmcp_meta=False)
+
+ @mcp.resource(
+ "test://template/{id}", tags={"template-example", "test-template-tag"}
+ )
+ def sample_template(id: str) -> str:
+ """A sample resource template."""
+ return f"template content for {id}"
+
+ async with Client(mcp) as client:
+ templates = await client.list_resource_templates()
+ template = next(
+ t for t in templates if t.uriTemplate == "test://template/{id}"
+ )
+ # Meta should be None when include_fastmcp_meta is False
+ assert template.meta is None
+
+ async def test_prompt_meta_with_include_fastmcp_meta_false(self):
+ mcp = FastMCP(include_fastmcp_meta=False)
+
+ @mcp.prompt(tags={"example", "test-tag"})
+ def sample_prompt() -> str:
+ return "Hello, world!"
+
+ async with Client(mcp) as client:
+ prompts = await client.list_prompts()
+ prompt = next(p for p in prompts if p.name == "sample_prompt")
+ # Meta should be None when include_fastmcp_meta is False
+ assert prompt.meta is None
+
+ async def test_temporary_include_fastmcp_meta_setting(self):
+ """Test that temporary_settings can toggle include_fastmcp_meta for new servers."""
+
+ def make_server() -> FastMCP:
+ mcp = FastMCP()
+
+ @mcp.tool(tags={"test-tag"})
+ def sample_tool(x: int) -> int:
+ """A sample tool."""
+ return x * 2
+
+ return mcp
+
+ # Default: meta should be present
+ mcp = make_server()
+ async with Client(mcp) as client:
+ tools = await client.list_tools()
+ tool = next(t for t in tools if t.name == "sample_tool")
+ assert tool.meta is not None
+ assert set(tool.meta["_fastmcp"]["tags"]) == {"test-tag"}
+
+ # With setting disabled: new server should not include meta
+ with temporary_settings(include_fastmcp_meta=False):
+ mcp = make_server()
+ async with Client(mcp) as client:
+ tools = await client.list_tools()
+ tool = next(t for t in tools if t.name == "sample_tool")
+ assert tool.meta is None
+
+ # After context: new server should have meta again
+ mcp = make_server()
+ async with Client(mcp) as client:
+ tools = await client.list_tools()
+ tool = next(t for t in tools if t.name == "sample_tool")
+ assert tool.meta is not None
+ assert set(tool.meta["_fastmcp"]["tags"]) == {"test-tag"}
diff --git a/tests/server/test_server_interactions.py b/tests/server/test_server_interactions.py
deleted file mode 100644
index 2470f61c9..000000000
--- a/tests/server/test_server_interactions.py
+++ /dev/null
@@ -1,1455 +0,0 @@
-import base64
-from dataclasses import dataclass
-from pathlib import Path
-
-import pytest
-from mcp import McpError
-from mcp.types import (
- BlobResourceContents,
- EmbeddedResource,
- ImageContent,
- TextContent,
- TextResourceContents,
-)
-from pydantic import AnyUrl, BaseModel
-from typing_extensions import TypedDict
-
-from fastmcp import Client, FastMCP
-from fastmcp.client.transports import FastMCPTransport
-from fastmcp.exceptions import ToolError
-from fastmcp.prompts.prompt import Message
-from fastmcp.resources import FileResource
-from fastmcp.resources.resource import FunctionResource
-from fastmcp.utilities.tests import temporary_settings
-from fastmcp.utilities.types import Audio, File, Image
-
-
-def _normalize_anyof_order(schema):
- """Normalize the order of items in anyOf arrays for consistent comparison."""
- if isinstance(schema, dict):
- if "anyOf" in schema:
- # Sort anyOf items by their string representation for consistent ordering
- schema = schema.copy()
- schema["anyOf"] = sorted(schema["anyOf"], key=str)
- # Recursively normalize nested objects
- return {k: _normalize_anyof_order(v) for k, v in schema.items()}
- elif isinstance(schema, list):
- return [_normalize_anyof_order(item) for item in schema]
- return schema
-
-
-class PersonTypedDict(TypedDict):
- name: str
- age: int
-
-
-class PersonModel(BaseModel):
- name: str
- age: int
-
-
-@dataclass
-class PersonDataclass:
- name: str
- age: int
-
-
-def tool_server():
- mcp = FastMCP()
-
- @mcp.tool
- def add(x: int, y: int) -> int:
- return x + y
-
- @mcp.tool
- def list_tool() -> list[str | int]:
- return ["x", 2]
-
- @mcp.tool
- def error_tool() -> None:
- raise ValueError("Test error")
-
- @mcp.tool
- def image_tool(path: str) -> Image:
- return Image(path)
-
- @mcp.tool
- def audio_tool(path: str) -> Audio:
- return Audio(path)
-
- @mcp.tool
- def file_tool(path: str) -> File:
- return File(path)
-
- @mcp.tool
- def mixed_content_tool() -> list[TextContent | ImageContent | EmbeddedResource]:
- return [
- TextContent(type="text", text="Hello"),
- ImageContent(type="image", data="abc", mimeType="application/octet-stream"),
- EmbeddedResource(
- type="resource",
- resource=BlobResourceContents(
- blob=base64.b64encode(b"abc").decode(),
- mimeType="application/octet-stream",
- uri=AnyUrl("file:///test.bin"),
- ),
- ),
- ]
-
- @mcp.tool(output_schema=None)
- def mixed_list_fn(image_path: str) -> list:
- return [
- "text message",
- Image(image_path),
- {"key": "value"},
- TextContent(type="text", text="direct content"),
- ]
-
- @mcp.tool(output_schema=None)
- def mixed_audio_list_fn(audio_path: str) -> list:
- return [
- "text message",
- Audio(audio_path),
- {"key": "value"},
- TextContent(type="text", text="direct content"),
- ]
-
- @mcp.tool(output_schema=None)
- def mixed_file_list_fn(file_path: str) -> list:
- return [
- "text message",
- File(file_path),
- {"key": "value"},
- TextContent(type="text", text="direct content"),
- ]
-
- @mcp.tool
- def file_text_tool() -> File:
- # Return a File with text data and text/plain format
- return File(data=b"hello world", format="plain")
-
- return mcp
-
-
-class TestTools:
- async def test_add_tool_exists(self, tool_server: FastMCP):
- async with Client(tool_server) as client:
- tools = await client.list_tools()
- assert "add" in [t.name for t in tools]
-
- async def test_list_tools(self, tool_server: FastMCP):
- async with Client(tool_server) as client:
- assert len(await client.list_tools()) == 11
-
- async def test_call_tool_mcp(self, tool_server: FastMCP):
- async with Client(tool_server) as client:
- result = await client.call_tool_mcp("add", {"x": 1, "y": 2})
- assert isinstance(result.content[0], TextContent)
- assert result.content[0].text == "3"
- assert result.structuredContent == {"result": 3}
-
- async def test_call_tool(self, tool_server: FastMCP):
- async with Client(tool_server) as client:
- result = await client.call_tool("add", {"x": 1, "y": 2})
- assert isinstance(result.content[0], TextContent)
- assert result.content[0].text == "3"
- assert result.structured_content == {"result": 3}
- assert result.data == 3
-
- async def test_call_tool_error(self, tool_server: FastMCP):
- async with Client(tool_server) as client:
- with pytest.raises(Exception):
- await client.call_tool("error_tool", {})
-
- async def test_call_tool_error_as_client_raw(self):
- """Test raising and catching errors from a tool."""
- mcp = FastMCP()
- client = Client(transport=FastMCPTransport(mcp))
-
- @mcp.tool
- def error_tool():
- raise ValueError("Test error")
-
- async with client:
- with pytest.raises(Exception) as excinfo:
- await client.call_tool("error_tool", {})
- assert "Error calling tool 'error_tool'" in str(excinfo.value)
-
- async def test_tool_returns_list(self, tool_server: FastMCP):
- async with Client(tool_server) as client:
- result = await client.call_tool("list_tool", {})
- # Adjacent non-MCP list items are combined into single content block
- assert len(result.content) == 1
- assert isinstance(result.content[0], TextContent)
- assert result.content[0].text == '["x",2]'
- assert result.data == ["x", 2]
-
- async def test_file_text_tool(self, tool_server: FastMCP):
- async with Client(tool_server) as client:
- result = await client.call_tool("file_text_tool", {})
- assert len(result.content) == 1
- embedded = result.content[0]
- assert isinstance(embedded, EmbeddedResource)
- resource = embedded.resource
- assert isinstance(resource, TextResourceContents)
- assert resource.mimeType == "text/plain"
- assert resource.text == "hello world"
-
-
-class TestToolTags:
- def create_server(self, include_tags=None, exclude_tags=None):
- mcp = FastMCP(include_tags=include_tags, exclude_tags=exclude_tags)
-
- @mcp.tool(tags={"a", "b"})
- def tool_1() -> int:
- return 1
-
- @mcp.tool(tags={"b", "c"})
- def tool_2() -> int:
- return 2
-
- return mcp
-
- async def test_include_tags_all_tools(self):
- mcp = self.create_server(include_tags={"a", "b"})
-
- async with Client(mcp) as client:
- tools = await client.list_tools()
- assert {t.name for t in tools} == {"tool_1", "tool_2"}
-
- async def test_include_tags_some_tools(self):
- mcp = self.create_server(include_tags={"a", "z"})
-
- async with Client(mcp) as client:
- tools = await client.list_tools()
- assert {t.name for t in tools} == {"tool_1"}
-
- async def test_exclude_tags_all_tools(self):
- mcp = self.create_server(exclude_tags={"a", "b"})
-
- async with Client(mcp) as client:
- tools = await client.list_tools()
- assert {t.name for t in tools} == set()
-
- async def test_exclude_tags_some_tools(self):
- mcp = self.create_server(exclude_tags={"a", "z"})
-
- async with Client(mcp) as client:
- tools = await client.list_tools()
- assert {t.name for t in tools} == {"tool_2"}
-
- async def test_exclude_precedence(self):
- mcp = self.create_server(exclude_tags={"a"}, include_tags={"b"})
-
- async with Client(mcp) as client:
- tools = await client.list_tools()
- assert {t.name for t in tools} == {"tool_2"}
-
- async def test_call_included_tool(self):
- mcp = self.create_server(include_tags={"a"})
-
- async with Client(mcp) as client:
- result_1 = await client.call_tool("tool_1", {})
- assert result_1.data == 1
-
- with pytest.raises(ToolError, match="Unknown tool"):
- await client.call_tool("tool_2", {})
-
- async def test_call_excluded_tool(self):
- mcp = self.create_server(exclude_tags={"a"})
-
- async with Client(mcp) as client:
- with pytest.raises(ToolError, match="Unknown tool"):
- await client.call_tool("tool_1", {})
-
- result_2 = await client.call_tool("tool_2", {})
- assert result_2.data == 2
-
-
-class TestToolEnabled:
- async def test_toggle_enabled(self):
- mcp = FastMCP()
-
- @mcp.tool
- def sample_tool(x: int) -> int:
- return x * 2
-
- # Tool is enabled by default
- tools = await mcp.get_tools()
- assert any(t.name == "sample_tool" for t in tools)
-
- # Disable via server
- mcp.disable(keys=["tool:sample_tool"])
-
- # Tool should not be in list when disabled
- tools = await mcp.get_tools()
- assert not any(t.name == "sample_tool" for t in tools)
-
- # Re-enable via server
- mcp.enable(keys=["tool:sample_tool"])
- tools = await mcp.get_tools()
- assert any(t.name == "sample_tool" for t in tools)
-
- async def test_tool_disabled_via_server(self):
- mcp = FastMCP()
-
- @mcp.tool
- def sample_tool(x: int) -> int:
- return x * 2
-
- # Disable the tool via server
- mcp.disable(keys=["tool:sample_tool"])
-
- async with Client(mcp) as client:
- tools = await client.list_tools()
- assert len(tools) == 0
-
- with pytest.raises(ToolError, match="Unknown tool"):
- await client.call_tool("sample_tool", {"x": 5})
-
- async def test_tool_toggle_enabled(self):
- mcp = FastMCP()
-
- @mcp.tool
- def sample_tool(x: int) -> int:
- return x * 2
-
- # Disable then re-enable
- mcp.disable(keys=["tool:sample_tool"])
- mcp.enable(keys=["tool:sample_tool"])
-
- async with Client(mcp) as client:
- tools = await client.list_tools()
- assert len(tools) == 1
-
- async def test_tool_toggle_disabled(self):
- mcp = FastMCP()
-
- @mcp.tool
- def sample_tool(x: int) -> int:
- return x * 2
-
- mcp.disable(keys=["tool:sample_tool"])
-
- async with Client(mcp) as client:
- tools = await client.list_tools()
- assert len(tools) == 0
-
- with pytest.raises(ToolError, match="Unknown tool"):
- await client.call_tool("sample_tool", {"x": 5})
-
- async def test_get_tool_and_disable(self):
- mcp = FastMCP()
-
- @mcp.tool
- def sample_tool(x: int) -> int:
- return x * 2
-
- tool = await mcp.get_tool(name="sample_tool")
- assert tool is not None
-
- mcp.disable(keys=["tool:sample_tool"])
-
- async with Client(mcp) as client:
- result = await client.list_tools()
- assert len(result) == 0
-
- with pytest.raises(ToolError, match="Unknown tool"):
- await client.call_tool("sample_tool", {"x": 5})
-
- async def test_cant_call_disabled_tool(self):
- mcp = FastMCP()
-
- @mcp.tool
- def sample_tool(x: int) -> int:
- return x * 2
-
- mcp.disable(keys=["tool:sample_tool"])
-
- with pytest.raises(Exception, match="Unknown tool"):
- async with Client(mcp) as client:
- await client.call_tool("sample_tool", {"x": 5})
-
-
-class TestResource:
- async def test_text_resource(self):
- mcp = FastMCP()
-
- def get_text():
- return "Hello, world!"
-
- resource = FunctionResource(
- uri=AnyUrl("resource://test"), name="test", fn=get_text
- )
- mcp.add_resource(resource)
-
- async with Client(mcp) as client:
- result = await client.read_resource(AnyUrl("resource://test"))
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Hello, world!"
-
- async def test_binary_resource(self):
- mcp = FastMCP()
-
- def get_binary():
- return b"Binary data"
-
- resource = FunctionResource(
- uri=AnyUrl("resource://binary"),
- name="binary",
- fn=get_binary,
- mime_type="application/octet-stream",
- )
- mcp.add_resource(resource)
-
- async with Client(mcp) as client:
- result = await client.read_resource(AnyUrl("resource://binary"))
- assert isinstance(result[0], BlobResourceContents)
- assert result[0].blob == base64.b64encode(b"Binary data").decode()
-
- async def test_file_resource_text(self, tmp_path: Path):
- mcp = FastMCP()
-
- # Create a text file
- text_file = tmp_path / "test.txt"
- text_file.write_text("Hello from file!")
-
- resource = FileResource(
- uri=AnyUrl("file://test.txt"), name="test.txt", path=text_file
- )
- mcp.add_resource(resource)
-
- async with Client(mcp) as client:
- result = await client.read_resource(AnyUrl("file://test.txt"))
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Hello from file!"
-
- async def test_file_resource_binary(self, tmp_path: Path):
- mcp = FastMCP()
-
- # Create a binary file
- binary_file = tmp_path / "test.bin"
- binary_file.write_bytes(b"Binary file data")
-
- resource = FileResource(
- uri=AnyUrl("file://test.bin"),
- name="test.bin",
- path=binary_file,
- mime_type="application/octet-stream",
- )
- mcp.add_resource(resource)
-
- async with Client(mcp) as client:
- result = await client.read_resource(AnyUrl("file://test.bin"))
- assert isinstance(result[0], BlobResourceContents)
- assert result[0].blob == base64.b64encode(b"Binary file data").decode()
-
- async def test_resource_with_annotations(self):
- mcp = FastMCP()
-
- @mcp.resource(
- "http://example.com/data",
- name="test",
- annotations={
- "httpMethod": "GET",
- "Cache-Control": "max-age=3600",
- },
- )
- def get_data() -> str:
- return "Hello, world!"
-
- async with Client(mcp) as client:
- resources = await client.list_resources()
- assert len(resources) == 1
-
- resource = resources[0]
- assert str(resource.uri) == "http://example.com/data"
-
- assert resource.annotations is not None
- assert hasattr(resource.annotations, "httpMethod")
- assert getattr(resource.annotations, "httpMethod") == "GET"
- assert hasattr(resource.annotations, "Cache-Control")
- assert getattr(resource.annotations, "Cache-Control") == "max-age=3600"
-
-
-class TestResourceTags:
- def create_server(self, include_tags=None, exclude_tags=None):
- mcp = FastMCP(include_tags=include_tags, exclude_tags=exclude_tags)
-
- @mcp.resource("resource://1", tags={"a", "b"})
- def resource_1() -> str:
- return "1"
-
- @mcp.resource("resource://2", tags={"b", "c"})
- def resource_2() -> str:
- return "2"
-
- return mcp
-
- async def test_include_tags_all_resources(self):
- mcp = self.create_server(include_tags={"a", "b"})
-
- async with Client(mcp) as client:
- resources = await client.list_resources()
- assert {r.name for r in resources} == {"resource_1", "resource_2"}
-
- async def test_include_tags_some_resources(self):
- mcp = self.create_server(include_tags={"a", "z"})
-
- async with Client(mcp) as client:
- resources = await client.list_resources()
- assert {r.name for r in resources} == {"resource_1"}
-
- async def test_exclude_tags_all_resources(self):
- mcp = self.create_server(exclude_tags={"a", "b"})
-
- async with Client(mcp) as client:
- resources = await client.list_resources()
- assert {r.name for r in resources} == set()
-
- async def test_exclude_tags_some_resources(self):
- mcp = self.create_server(exclude_tags={"a"})
-
- async with Client(mcp) as client:
- resources = await client.list_resources()
- assert {r.name for r in resources} == {"resource_2"}
-
- async def test_exclude_precedence(self):
- mcp = self.create_server(exclude_tags={"a"}, include_tags={"b"})
-
- async with Client(mcp) as client:
- resources = await client.list_resources()
- assert {r.name for r in resources} == {"resource_2"}
-
- async def test_read_included_resource(self):
- mcp = self.create_server(include_tags={"a"})
-
- async with Client(mcp) as client:
- result = await client.read_resource(AnyUrl("resource://1"))
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "1"
-
- with pytest.raises(McpError, match="Unknown resource"):
- await client.read_resource(AnyUrl("resource://2"))
-
- async def test_read_excluded_resource(self):
- mcp = self.create_server(exclude_tags={"a"})
-
- async with Client(mcp) as client:
- with pytest.raises(McpError, match="Unknown resource"):
- await client.read_resource(AnyUrl("resource://1"))
-
-
-class TestResourceEnabled:
- async def test_toggle_enabled(self):
- mcp = FastMCP()
-
- @mcp.resource("resource://data")
- def sample_resource() -> str:
- return "Hello, world!"
-
- resources = await mcp.get_resources()
- assert any(str(r.uri) == "resource://data" for r in resources)
-
- mcp.disable(keys=["resource:resource://data"])
-
- resources = await mcp.get_resources()
- assert not any(str(r.uri) == "resource://data" for r in resources)
-
- mcp.enable(keys=["resource:resource://data"])
-
- resources = await mcp.get_resources()
- assert any(str(r.uri) == "resource://data" for r in resources)
-
- async def test_resource_disabled(self):
- mcp = FastMCP()
-
- @mcp.resource("resource://data")
- def sample_resource() -> str:
- return "Hello, world!"
-
- mcp.disable(keys=["resource:resource://data"])
-
- async with Client(mcp) as client:
- resources = await client.list_resources()
- assert len(resources) == 0
-
- with pytest.raises(McpError, match="Unknown resource"):
- await client.read_resource(AnyUrl("resource://data"))
-
- async def test_resource_toggle_enabled(self):
- mcp = FastMCP()
-
- @mcp.resource("resource://data")
- def sample_resource() -> str:
- return "Hello, world!"
-
- mcp.disable(keys=["resource:resource://data"])
-
- resources = await mcp.get_resources()
- assert not any(str(r.uri) == "resource://data" for r in resources)
-
- mcp.enable(keys=["resource:resource://data"])
-
- async with Client(mcp) as client:
- resources = await client.list_resources()
- assert len(resources) == 1
-
- async def test_resource_toggle_disabled(self):
- mcp = FastMCP()
-
- @mcp.resource("resource://data")
- def sample_resource() -> str:
- return "Hello, world!"
-
- mcp.disable(keys=["resource:resource://data"])
-
- async with Client(mcp) as client:
- resources = await client.list_resources()
- assert len(resources) == 0
-
- with pytest.raises(McpError, match="Unknown resource"):
- await client.read_resource(AnyUrl("resource://data"))
-
- async def test_get_resource_and_disable(self):
- mcp = FastMCP()
-
- @mcp.resource("resource://data")
- def sample_resource() -> str:
- return "Hello, world!"
-
- resource = await mcp.get_resource("resource://data")
- assert resource is not None
-
- mcp.disable(keys=["resource:resource://data"])
-
- async with Client(mcp) as client:
- result = await client.list_resources()
- assert len(result) == 0
-
- with pytest.raises(McpError, match="Unknown resource"):
- await client.read_resource(AnyUrl("resource://data"))
-
- async def test_cant_read_disabled_resource(self):
- mcp = FastMCP()
-
- @mcp.resource("resource://data")
- def sample_resource() -> str:
- return "Hello, world!"
-
- mcp.disable(keys=["resource:resource://data"])
-
- with pytest.raises(McpError, match="Unknown resource"):
- async with Client(mcp) as client:
- await client.read_resource(AnyUrl("resource://data"))
-
-
-class TestResourceTemplatesTags:
- def create_server(self, include_tags=None, exclude_tags=None):
- mcp = FastMCP(include_tags=include_tags, exclude_tags=exclude_tags)
-
- @mcp.resource("resource://1/{param}", tags={"a", "b"})
- def template_resource_1(param: str) -> str:
- return f"Template resource 1: {param}"
-
- @mcp.resource("resource://2/{param}", tags={"b", "c"})
- def template_resource_2(param: str) -> str:
- return f"Template resource 2: {param}"
-
- return mcp
-
- async def test_include_tags_all_resources(self):
- mcp = self.create_server(include_tags={"a", "b"})
-
- async with Client(mcp) as client:
- resources = await client.list_resource_templates()
- assert {r.name for r in resources} == {
- "template_resource_1",
- "template_resource_2",
- }
-
- async def test_include_tags_some_resources(self):
- mcp = self.create_server(include_tags={"a"})
-
- async with Client(mcp) as client:
- resources = await client.list_resource_templates()
- assert {r.name for r in resources} == {"template_resource_1"}
-
- async def test_exclude_tags_all_resources(self):
- mcp = self.create_server(exclude_tags={"a", "b"})
-
- async with Client(mcp) as client:
- resources = await client.list_resource_templates()
- assert {r.name for r in resources} == set()
-
- async def test_exclude_tags_some_resources(self):
- mcp = self.create_server(exclude_tags={"a"})
-
- async with Client(mcp) as client:
- resources = await client.list_resource_templates()
- assert {r.name for r in resources} == {"template_resource_2"}
-
- async def test_exclude_takes_precedence_over_include(self):
- mcp = self.create_server(exclude_tags={"a"}, include_tags={"b"})
-
- async with Client(mcp) as client:
- resources = await client.list_resource_templates()
- assert {r.name for r in resources} == {"template_resource_2"}
-
- async def test_read_resource_template_includes_tags(self):
- mcp = self.create_server(include_tags={"a"})
-
- async with Client(mcp) as client:
- result = await client.read_resource("resource://1/x")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Template resource 1: x"
-
- with pytest.raises(McpError, match="Unknown resource"):
- await client.read_resource("resource://2/x")
-
- async def test_read_resource_template_excludes_tags(self):
- mcp = self.create_server(exclude_tags={"a"})
-
- async with Client(mcp) as client:
- with pytest.raises(McpError, match="Unknown resource"):
- await client.read_resource("resource://1/x")
-
- result = await client.read_resource("resource://2/x")
- assert isinstance(result[0], TextResourceContents)
- assert result[0].text == "Template resource 2: x"
-
-
-class TestResourceTemplateEnabled:
- async def test_toggle_enabled(self):
- mcp = FastMCP()
-
- @mcp.resource("resource://{param}")
- def sample_template(param: str) -> str:
- return f"Template: {param}"
-
- templates = await mcp.get_resource_templates()
- assert any(t.uri_template == "resource://{param}" for t in templates)
-
- mcp.disable(keys=["template:resource://{param}"])
-
- templates = await mcp.get_resource_templates()
- assert not any(t.uri_template == "resource://{param}" for t in templates)
-
- mcp.enable(keys=["template:resource://{param}"])
-
- templates = await mcp.get_resource_templates()
- assert any(t.uri_template == "resource://{param}" for t in templates)
-
- async def test_template_disabled(self):
- mcp = FastMCP()
-
- @mcp.resource("resource://{param}")
- def sample_template(param: str) -> str:
- return f"Template: {param}"
-
- mcp.disable(keys=["template:resource://{param}"])
-
- async with Client(mcp) as client:
- templates = await client.list_resource_templates()
- assert len(templates) == 0
-
- with pytest.raises(McpError, match="Unknown resource"):
- await client.read_resource(AnyUrl("resource://test"))
-
- async def test_template_toggle_enabled(self):
- mcp = FastMCP()
-
- @mcp.resource("resource://{param}")
- def sample_template(param: str) -> str:
- return f"Template: {param}"
-
- mcp.disable(keys=["template:resource://{param}"])
-
- templates = await mcp.get_resource_templates()
- assert not any(t.uri_template == "resource://{param}" for t in templates)
-
- mcp.enable(keys=["template:resource://{param}"])
-
- async with Client(mcp) as client:
- templates = await client.list_resource_templates()
- assert len(templates) == 1
-
- async def test_template_toggle_disabled(self):
- mcp = FastMCP()
-
- @mcp.resource("resource://{param}")
- def sample_template(param: str) -> str:
- return f"Template: {param}"
-
- mcp.disable(keys=["template:resource://{param}"])
-
- async with Client(mcp) as client:
- templates = await client.list_resource_templates()
- assert len(templates) == 0
-
- with pytest.raises(McpError, match="Unknown resource"):
- await client.read_resource(AnyUrl("resource://test"))
-
- async def test_get_template_and_disable(self):
- mcp = FastMCP()
-
- @mcp.resource("resource://{param}")
- def sample_template(param: str) -> str:
- return f"Template: {param}"
-
- template = await mcp.get_resource_template("resource://{param}")
- assert template is not None
-
- mcp.disable(keys=["template:resource://{param}"])
-
- async with Client(mcp) as client:
- result = await client.list_resource_templates()
- assert len(result) == 0
-
- with pytest.raises(McpError, match="Unknown resource"):
- await client.read_resource(AnyUrl("resource://test"))
-
- async def test_cant_read_disabled_template(self):
- mcp = FastMCP()
-
- @mcp.resource("resource://{param}")
- def sample_template(param: str) -> str:
- return f"Template: {param}"
-
- mcp.disable(keys=["template:resource://{param}"])
-
- with pytest.raises(McpError, match="Unknown resource"):
- async with Client(mcp) as client:
- await client.read_resource(AnyUrl("resource://test"))
-
-
-class TestPrompts:
- """Test prompt functionality in FastMCP server."""
-
- async def test_prompt_decorator(self):
- """Test that the prompt decorator registers prompts correctly."""
- mcp = FastMCP()
-
- @mcp.prompt
- def fn() -> str:
- return "Hello, world!"
-
- prompts = await mcp.get_prompts()
- assert len(prompts) == 1
- prompt = next(p for p in prompts if p.name == "fn")
- assert prompt.name == "fn"
- # Don't compare functions directly since validate_call wraps them
- content = await prompt.render()
- assert isinstance(content.messages[0].content, TextContent)
- assert content.messages[0].content.text == "Hello, world!"
-
- async def test_prompt_decorator_with_name(self):
- """Test prompt decorator with custom name."""
- mcp = FastMCP()
-
- @mcp.prompt(name="custom_name")
- def fn() -> str:
- return "Hello, world!"
-
- prompts = await mcp.get_prompts()
- assert len(prompts) == 1
- prompt = next(p for p in prompts if p.name == "custom_name")
- assert prompt.name == "custom_name"
- content = await prompt.render()
- assert isinstance(content.messages[0].content, TextContent)
- assert content.messages[0].content.text == "Hello, world!"
-
- async def test_prompt_decorator_with_description(self):
- """Test prompt decorator with custom description."""
- mcp = FastMCP()
-
- @mcp.prompt(description="A custom description")
- def fn() -> str:
- return "Hello, world!"
-
- prompts = await mcp.get_prompts()
- assert len(prompts) == 1
- prompt = next(p for p in prompts if p.name == "fn")
- assert prompt.description == "A custom description"
- content = await prompt.render()
- assert isinstance(content.messages[0].content, TextContent)
- assert content.messages[0].content.text == "Hello, world!"
-
- async def test_prompt_decorator_with_parens(self):
- mcp = FastMCP()
-
- @mcp.prompt
- def fn() -> str:
- return "Hello, world!"
-
- prompts = await mcp.get_prompts()
- assert len(prompts) == 1
- prompt = next(p for p in prompts if p.name == "fn")
- assert prompt.name == "fn"
-
- async def test_list_prompts(self):
- """Test listing prompts through MCP protocol."""
- mcp = FastMCP()
-
- @mcp.prompt
- def fn(name: str, optional: str = "default") -> str:
- return f"Hello, {name}! {optional}"
-
- prompts_dict = await mcp.get_prompts()
- assert len(prompts_dict) == 1
-
- async with Client(mcp) as client:
- prompts = await client.list_prompts()
- assert len(prompts) == 1
- assert prompts[0].name == "fn"
- assert prompts[0].description is None
- assert prompts[0].arguments is not None
- assert len(prompts[0].arguments) == 2
- assert prompts[0].arguments[0].name == "name"
- assert prompts[0].arguments[0].required is True
- assert prompts[0].arguments[1].name == "optional"
- assert prompts[0].arguments[1].required is False
-
- async def test_list_prompts_with_enhanced_descriptions(self):
- """Test that enhanced descriptions with JSON schema are visible via MCP protocol."""
- mcp = FastMCP()
-
- @mcp.prompt
- def analyze_data(
- name: str, numbers: list[int], metadata: dict[str, str], threshold: float
- ) -> str:
- """Analyze some data."""
- return f"Analyzed {name}"
-
- async with Client(mcp) as client:
- prompts = await client.list_prompts()
- assert len(prompts) == 1
- prompt = prompts[0]
- assert prompt.name == "analyze_data"
- assert prompt.description == "Analyze some data."
-
- # Find each argument and verify schema enhancements
- assert prompt.arguments is not None
- args_by_name = {arg.name: arg for arg in prompt.arguments}
-
- # String parameter should not have schema enhancement
- name_arg = args_by_name["name"]
- assert name_arg.description is None
-
- # Non-string parameters should have schema enhancements
- numbers_arg = args_by_name["numbers"]
- assert numbers_arg.description is not None
- assert (
- "Provide as a JSON string matching the following schema:"
- in numbers_arg.description
- )
- assert (
- '{"items":{"type":"integer"},"type":"array"}' in numbers_arg.description
- )
-
- metadata_arg = args_by_name["metadata"]
- assert metadata_arg.description is not None
- assert (
- "Provide as a JSON string matching the following schema:"
- in metadata_arg.description
- )
- assert (
- '{"additionalProperties":{"type":"string"},"type":"object"}'
- in metadata_arg.description
- )
-
- threshold_arg = args_by_name["threshold"]
- assert threshold_arg.description is not None
- assert (
- "Provide as a JSON string matching the following schema:"
- in threshold_arg.description
- )
- assert '{"type":"number"}' in threshold_arg.description
-
- async def test_get_prompt(self):
- """Test getting a prompt through MCP protocol."""
- mcp = FastMCP()
-
- @mcp.prompt
- def fn(name: str) -> str:
- return f"Hello, {name}!"
-
- async with Client(mcp) as client:
- result = await client.get_prompt("fn", {"name": "World"})
- assert len(result.messages) == 1
- 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."""
- mcp = FastMCP()
-
- @mcp.prompt
- def fn() -> list[Message]:
- return [
- Message(
- content=EmbeddedResource(
- type="resource",
- resource=TextResourceContents(
- uri=AnyUrl("file://file.txt"),
- text="File contents",
- mimeType="text/plain",
- ),
- ),
- role="user",
- )
- ]
-
- async with Client(mcp) as client:
- result = await client.get_prompt("fn")
- assert result.messages[0].role == "user"
- content = result.messages[0].content
- assert isinstance(content, EmbeddedResource)
- assert isinstance(content.resource, TextResourceContents)
- assert content.resource.text == "File contents"
- assert content.resource.mimeType == "text/plain"
-
- async def test_get_prompt_with_meta(self):
- """Test that PromptResult meta is passed through to client."""
- from fastmcp.prompts import PromptResult
-
- mcp = FastMCP()
-
- @mcp.prompt
- def fn() -> PromptResult:
- return PromptResult(
- "Hello!",
- description="A greeting",
- meta={"priority": "high", "category": "greeting"},
- )
-
- async with Client(mcp) as client:
- result = await client.get_prompt("fn")
- assert result.description == "A greeting"
- assert result.meta is not None
- assert result.meta["priority"] == "high"
- assert result.meta["category"] == "greeting"
-
- async def test_get_unknown_prompt(self):
- """Test error when getting unknown prompt."""
- mcp = FastMCP()
- with pytest.raises(McpError, match="Unknown prompt"):
- async with Client(mcp) as client:
- await client.get_prompt("unknown")
-
- async def test_get_prompt_missing_args(self):
- """Test error when required arguments are missing."""
- mcp = FastMCP()
-
- @mcp.prompt
- def prompt_fn(name: str) -> str:
- return f"Hello, {name}!"
-
- with pytest.raises(McpError, match="Missing required arguments"):
- async with Client(mcp) as client:
- await client.get_prompt("prompt_fn")
-
- async def test_resource_decorator_with_tags(self):
- """Test that the resource decorator supports tags."""
- mcp = FastMCP()
-
- @mcp.resource("resource://data", tags={"example", "test-tag"})
- def get_data() -> str:
- return "Hello, world!"
-
- resources = await mcp.get_resources()
- assert len(resources) == 1
- assert resources[0].tags == {"example", "test-tag"}
-
- async def test_template_decorator_with_tags(self):
- """Test that the template decorator properly sets tags."""
- mcp = FastMCP()
-
- @mcp.resource("resource://{param}", tags={"template", "test-tag"})
- def template_resource(param: str) -> str:
- return f"Template resource: {param}"
-
- templates = await mcp.get_resource_templates()
- template = next(t for t in templates if t.uri_template == "resource://{param}")
- assert template.tags == {"template", "test-tag"}
-
- async def test_prompt_decorator_with_tags(self):
- """Test that the prompt decorator properly sets tags."""
- mcp = FastMCP()
-
- @mcp.prompt(tags={"example", "test-tag"})
- def sample_prompt() -> str:
- return "Hello, world!"
-
- prompts = await mcp.get_prompts()
- assert len(prompts) == 1
- prompt = next(p for p in prompts if p.name == "sample_prompt")
- assert prompt.tags == {"example", "test-tag"}
-
-
-class TestPromptEnabled:
- async def test_toggle_enabled(self):
- mcp = FastMCP()
-
- @mcp.prompt
- def sample_prompt() -> str:
- return "Hello, world!"
-
- prompts = await mcp.get_prompts()
- assert any(p.name == "sample_prompt" for p in prompts)
-
- mcp.disable(keys=["prompt:sample_prompt"])
-
- prompts = await mcp.get_prompts()
- assert not any(p.name == "sample_prompt" for p in prompts)
-
- mcp.enable(keys=["prompt:sample_prompt"])
-
- prompts = await mcp.get_prompts()
- assert any(p.name == "sample_prompt" for p in prompts)
-
- async def test_prompt_disabled(self):
- mcp = FastMCP()
-
- @mcp.prompt
- def sample_prompt() -> str:
- return "Hello, world!"
-
- mcp.disable(keys=["prompt:sample_prompt"])
-
- async with Client(mcp) as client:
- prompts = await client.list_prompts()
- assert len(prompts) == 0
-
- with pytest.raises(McpError, match="Unknown prompt"):
- await client.get_prompt("sample_prompt")
-
- async def test_prompt_toggle_enabled(self):
- mcp = FastMCP()
-
- @mcp.prompt
- def sample_prompt() -> str:
- return "Hello, world!"
-
- mcp.disable(keys=["prompt:sample_prompt"])
-
- prompts = await mcp.get_prompts()
- assert not any(p.name == "sample_prompt" for p in prompts)
-
- mcp.enable(keys=["prompt:sample_prompt"])
-
- async with Client(mcp) as client:
- prompts = await client.list_prompts()
- assert len(prompts) == 1
-
- async def test_prompt_toggle_disabled(self):
- mcp = FastMCP()
-
- @mcp.prompt
- def sample_prompt() -> str:
- return "Hello, world!"
-
- mcp.disable(keys=["prompt:sample_prompt"])
-
- async with Client(mcp) as client:
- prompts = await client.list_prompts()
- assert len(prompts) == 0
-
- with pytest.raises(McpError, match="Unknown prompt"):
- await client.get_prompt("sample_prompt")
-
- async def test_get_prompt_and_disable(self):
- mcp = FastMCP()
-
- @mcp.prompt
- def sample_prompt() -> str:
- return "Hello, world!"
-
- prompt = await mcp.get_prompt("sample_prompt")
- assert prompt is not None
-
- mcp.disable(keys=["prompt:sample_prompt"])
-
- async with Client(mcp) as client:
- result = await client.list_prompts()
- assert len(result) == 0
-
- with pytest.raises(McpError, match="Unknown prompt"):
- await client.get_prompt("sample_prompt")
-
- async def test_cant_get_disabled_prompt(self):
- mcp = FastMCP()
-
- @mcp.prompt
- def sample_prompt() -> str:
- return "Hello, world!"
-
- mcp.disable(keys=["prompt:sample_prompt"])
-
- with pytest.raises(McpError, match="Unknown prompt"):
- async with Client(mcp) as client:
- await client.get_prompt("sample_prompt")
-
-
-class TestPromptTags:
- def create_server(self, include_tags=None, exclude_tags=None):
- mcp = FastMCP(include_tags=include_tags, exclude_tags=exclude_tags)
-
- @mcp.prompt(tags={"a", "b"})
- def prompt_1() -> str:
- return "1"
-
- @mcp.prompt(tags={"b", "c"})
- def prompt_2() -> str:
- return "2"
-
- return mcp
-
- async def test_include_tags_all_prompts(self):
- mcp = self.create_server(include_tags={"a", "b"})
-
- async with Client(mcp) as client:
- prompts = await client.list_prompts()
- assert {p.name for p in prompts} == {"prompt_1", "prompt_2"}
-
- async def test_include_tags_some_prompts(self):
- mcp = self.create_server(include_tags={"a"})
-
- async with Client(mcp) as client:
- prompts = await client.list_prompts()
- assert {p.name for p in prompts} == {"prompt_1"}
-
- async def test_exclude_tags_all_prompts(self):
- mcp = self.create_server(exclude_tags={"a", "b"})
-
- async with Client(mcp) as client:
- prompts = await client.list_prompts()
- assert {p.name for p in prompts} == set()
-
- async def test_exclude_tags_some_prompts(self):
- mcp = self.create_server(exclude_tags={"a"})
-
- async with Client(mcp) as client:
- prompts = await client.list_prompts()
- assert {p.name for p in prompts} == {"prompt_2"}
-
- async def test_exclude_takes_precedence_over_include(self):
- mcp = self.create_server(exclude_tags={"a"}, include_tags={"b"})
-
- async with Client(mcp) as client:
- prompts = await client.list_prompts()
- assert {p.name for p in prompts} == {"prompt_2"}
-
- async def test_read_prompt_includes_tags(self):
- mcp = self.create_server(include_tags={"a"})
-
- async with Client(mcp) as client:
- result = await client.get_prompt("prompt_1")
- assert isinstance(result.messages[0].content, TextContent)
- assert result.messages[0].content.text == "1"
-
- with pytest.raises(McpError, match="Unknown prompt"):
- await client.get_prompt("prompt_2")
-
- async def test_read_prompt_excludes_tags(self):
- mcp = self.create_server(exclude_tags={"a"})
-
- async with Client(mcp) as client:
- with pytest.raises(McpError, match="Unknown prompt"):
- await client.get_prompt("prompt_1")
-
- result = await client.get_prompt("prompt_2")
- assert isinstance(result.messages[0].content, TextContent)
- assert result.messages[0].content.text == "2"
-
-
-class TestMeta:
- """Test that include_fastmcp_meta controls whether _fastmcp key is present in meta."""
-
- async def test_tool_tags_in_meta_with_default_setting(self):
- """Test that tool tags appear in meta under _fastmcp key with default setting."""
- mcp = FastMCP()
-
- @mcp.tool(tags={"tool-example", "test-tool-tag"})
- def sample_tool(x: int) -> int:
- """A sample tool."""
- return x * 2
-
- async with Client(mcp) as client:
- tools = await client.list_tools()
- tool = next(t for t in tools if t.name == "sample_tool")
- assert tool.meta is not None
- assert set(tool.meta["_fastmcp"]["tags"]) == {
- "tool-example",
- "test-tool-tag",
- }
-
- async def test_resource_tags_in_meta_with_default_setting(self):
- """Test that resource tags appear in meta under _fastmcp key with default setting."""
- mcp = FastMCP()
-
- @mcp.resource(
- uri="test://resource", tags={"resource-example", "test-resource-tag"}
- )
- def sample_resource() -> str:
- """A sample resource."""
- return "resource content"
-
- async with Client(mcp) as client:
- resources = await client.list_resources()
- resource = next(r for r in resources if str(r.uri) == "test://resource")
- assert resource.meta is not None
- assert set(resource.meta["_fastmcp"]["tags"]) == {
- "resource-example",
- "test-resource-tag",
- }
-
- async def test_resource_template_tags_in_meta_with_default_setting(self):
- """Test that resource template tags appear in meta under _fastmcp key with default setting."""
- mcp = FastMCP()
-
- @mcp.resource(
- "test://template/{id}", tags={"template-example", "test-template-tag"}
- )
- def sample_template(id: str) -> str:
- """A sample resource template."""
- return f"template content for {id}"
-
- async with Client(mcp) as client:
- templates = await client.list_resource_templates()
- template = next(
- t for t in templates if t.uriTemplate == "test://template/{id}"
- )
- assert template.meta is not None
- assert set(template.meta["_fastmcp"]["tags"]) == {
- "template-example",
- "test-template-tag",
- }
-
- async def test_prompt_tags_in_meta_with_default_setting(self):
- """Test that prompt tags appear in meta under _fastmcp key with default setting."""
- mcp = FastMCP()
-
- @mcp.prompt(tags={"example", "test-tag"})
- def sample_prompt() -> str:
- return "Hello, world!"
-
- async with Client(mcp) as client:
- prompts = await client.list_prompts()
- prompt = next(p for p in prompts if p.name == "sample_prompt")
- assert prompt.meta is not None
- assert set(prompt.meta["_fastmcp"]["tags"]) == {"example", "test-tag"}
-
- async def test_tool_meta_with_include_fastmcp_meta_false(self):
- mcp = FastMCP(include_fastmcp_meta=False)
-
- @mcp.tool(tags={"tool-example", "test-tool-tag"})
- def sample_tool(x: int) -> int:
- """A sample tool."""
- return x * 2
-
- async with Client(mcp) as client:
- tools = await client.list_tools()
- tool = next(t for t in tools if t.name == "sample_tool")
- # Meta should be None when include_fastmcp_meta is False and no explicit meta is set
- assert tool.meta is None
-
- async def test_resource_meta_with_include_fastmcp_meta_false(self):
- mcp = FastMCP(include_fastmcp_meta=False)
-
- @mcp.resource(
- uri="test://resource", tags={"resource-example", "test-resource-tag"}
- )
- def sample_resource() -> str:
- """A sample resource."""
- return "resource content"
-
- async with Client(mcp) as client:
- resources = await client.list_resources()
- resource = next(r for r in resources if str(r.uri) == "test://resource")
- # Meta should be None when include_fastmcp_meta is False and no explicit meta is set
- assert resource.meta is None
-
- async def test_resource_template_meta_with_include_fastmcp_meta_false(self):
- mcp = FastMCP(include_fastmcp_meta=False)
-
- @mcp.resource(
- "test://template/{id}", tags={"template-example", "test-template-tag"}
- )
- def sample_template(id: str) -> str:
- """A sample resource template."""
- return f"template content for {id}"
-
- async with Client(mcp) as client:
- templates = await client.list_resource_templates()
- template = next(
- t for t in templates if t.uriTemplate == "test://template/{id}"
- )
- # Meta should be None when include_fastmcp_meta is False and no explicit meta is set
- assert template.meta is None
-
- async def test_prompt_meta_with_include_fastmcp_meta_false(self):
- mcp = FastMCP(include_fastmcp_meta=False)
-
- @mcp.prompt(tags={"example", "test-tag"})
- def sample_prompt() -> str:
- return "Hello, world!"
-
- async with Client(mcp) as client:
- prompts = await client.list_prompts()
- prompt = next(p for p in prompts if p.name == "sample_prompt")
- # Meta should be None when include_fastmcp_meta is False and no explicit meta is set
- assert prompt.meta is None
-
- async def test_global_settings_inheritance(self):
- """Test that servers inherit the global include_fastmcp_meta setting."""
- with temporary_settings(include_fastmcp_meta=False):
- # Server should inherit global setting
- mcp = FastMCP()
-
- @mcp.tool(tags={"test-tag"})
- def sample_tool(x: int) -> int:
- return x * 2
-
- async with Client(mcp) as client:
- tools = await client.list_tools()
- tool = next(t for t in tools if t.name == "sample_tool")
- # Meta should be None because global setting is False
- assert tool.meta is None
-
- # Verify that default behavior is restored
- mcp2 = FastMCP()
-
- @mcp2.tool(tags={"test-tag"})
- def another_tool(x: int) -> int:
- return x * 2
-
- async with Client(mcp2) as client:
- tools = await client.list_tools()
- tool = next(t for t in tools if t.name == "another_tool")
- # Meta should have _fastmcp key because global setting is back to default (True)
- assert tool.meta is not None
- assert "_fastmcp" in tool.meta
- assert tool.meta["_fastmcp"]["tags"] == ["test-tag"]
-
- async def test_explicit_override_of_global_setting(self):
- """Test that explicit include_fastmcp_meta parameter overrides global setting."""
- with temporary_settings(include_fastmcp_meta=False):
- # Explicitly override global setting to True
- mcp = FastMCP(include_fastmcp_meta=True)
-
- @mcp.tool(tags={"test-tag"})
- def sample_tool(x: int) -> int:
- return x * 2
-
- async with Client(mcp) as client:
- tools = await client.list_tools()
- tool = next(t for t in tools if t.name == "sample_tool")
- # Meta should have _fastmcp key because explicit setting overrides global
- assert tool.meta is not None
- assert "_fastmcp" in tool.meta
- assert tool.meta["_fastmcp"]["tags"] == ["test-tag"]