Spaces:
Running
Running
File size: 13,494 Bytes
c151bc3 957b451 c151bc3 53a91d7 c151bc3 957b451 c151bc3 53a91d7 c151bc3 53a91d7 c151bc3 53a91d7 c151bc3 53a91d7 c151bc3 53a91d7 c151bc3 53a91d7 c151bc3 53a91d7 c151bc3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 | import base64
import json
import re
import httpx
from dirty_equals import IsStr
from fastapi import FastAPI
from mcp.types import BlobResourceContents
from pydantic import TypeAdapter
from pydantic.networks import AnyUrl
from fastmcp import FastMCP
from fastmcp.client import Client
from fastmcp.server.openapi import (
FastMCPOpenAPI,
MCPType,
OpenAPIResource,
OpenAPIResourceTemplate,
OpenAPITool,
RouteMap,
)
from .conftest import GET_ROUTE_MAPS, User
async def test_create_openapi_server(
fastapi_app: FastAPI, api_client: httpx.AsyncClient
):
openapi_spec = fastapi_app.openapi()
server = FastMCPOpenAPI(
openapi_spec=openapi_spec, client=api_client, name="Test App"
)
assert isinstance(server, FastMCP)
assert server.name == "Test App"
async def test_create_openapi_server_classmethod(
fastapi_app: FastAPI, api_client: httpx.AsyncClient
):
server = FastMCP.from_openapi(openapi_spec=fastapi_app.openapi(), client=api_client)
assert isinstance(server, FastMCPOpenAPI)
assert server.name == "OpenAPI FastMCP"
async def test_create_fastapi_server_classmethod(fastapi_app: FastAPI):
server = FastMCP.from_fastapi(fastapi_app)
assert isinstance(server, FastMCPOpenAPI)
assert server.name == "FastAPI App"
async def test_create_openapi_server_with_timeout(
fastapi_app: FastAPI, api_client: httpx.AsyncClient
):
server = FastMCPOpenAPI(
openapi_spec=fastapi_app.openapi(),
client=api_client,
name="Test App",
timeout=1.0,
route_maps=GET_ROUTE_MAPS,
)
assert server._timeout == 1.0
for tool in (await server.get_tools()).values():
assert isinstance(tool, OpenAPITool)
assert tool._timeout == 1.0
for resource in (await server.get_resources()).values():
assert isinstance(resource, OpenAPIResource)
assert resource._timeout == 1.0
for template in (await server.get_resource_templates()).values():
assert isinstance(template, OpenAPIResourceTemplate)
assert template._timeout == 1.0
class TestTools:
async def test_default_behavior_converts_everything_to_tools(
self, fastapi_app: FastAPI
):
"""
By default, tools exclude GET methods
"""
server = FastMCPOpenAPI.from_fastapi(fastapi_app)
assert len(await server.get_tools()) == 8
assert len(await server.get_resources()) == 0
assert len(await server.get_resource_templates()) == 0
async def test_list_tools(self, fastmcp_openapi_server: FastMCPOpenAPI):
"""
By default, tools exclude GET methods
"""
async with Client(fastmcp_openapi_server) as client:
tools = await client.list_tools()
assert len(tools) == 2
assert tools[0].model_dump() == dict(
name="create_user_users_post",
meta=dict(_fastmcp=dict(tags=["create", "users"])),
title=None,
annotations=None,
description=IsStr(regex=r"^Create a new user\..*$", regex_flags=re.DOTALL),
inputSchema={
"type": "object",
"properties": {
"name": {"type": "string", "title": "Name"},
"active": {"type": "boolean", "title": "Active"},
},
"required": ["name", "active"],
},
outputSchema={
"type": "object",
"properties": {
"id": {"type": "integer", "title": "Id"},
"name": {"type": "string", "title": "Name"},
"active": {"type": "boolean", "title": "Active"},
},
"required": ["id", "name", "active"],
"title": "User",
},
)
assert tools[1].model_dump() == dict(
name="update_user_name_users",
meta=dict(_fastmcp=dict(tags=["update", "users"])),
title=None,
annotations=None,
description=IsStr(
regex=r"^Update a user's name\..*$", regex_flags=re.DOTALL
),
inputSchema={
"type": "object",
"properties": {
"user_id": {"type": "integer", "title": "User Id"},
"name": {"type": "string", "title": "Name"},
},
"required": ["user_id", "name"],
},
outputSchema={
"type": "object",
"properties": {
"id": {"type": "integer", "title": "Id"},
"name": {"type": "string", "title": "Name"},
"active": {"type": "boolean", "title": "Active"},
},
"required": ["id", "name", "active"],
"title": "User",
},
)
async def test_call_create_user_tool(
self,
fastmcp_openapi_server: FastMCPOpenAPI,
api_client,
):
"""
The tool created by the OpenAPI server should be the same as the original
"""
async with Client(fastmcp_openapi_server) as client:
tool_response = await client.call_tool(
"create_user_users_post", {"name": "David", "active": False}
)
expected_user = User(id=4, name="David", active=False)
# Compare the data content since MCP client creates different class instances
assert tool_response.data.id == expected_user.id
assert tool_response.data.name == expected_user.name
assert tool_response.data.active == expected_user.active
# Check that the user was created via API
response = await api_client.get("/users")
assert len(response.json()) == 4
# Check that the user was created via MCP
async with Client(fastmcp_openapi_server) as client:
user_response = await client.read_resource("resource://get_user_users/4")
response_text = user_response[0].text # type: ignore[attr-defined]
user = json.loads(response_text)
assert user == expected_user.model_dump()
async def test_call_update_user_name_tool(
self,
fastmcp_openapi_server: FastMCPOpenAPI,
api_client,
):
"""
The tool created by the OpenAPI server should be the same as the original
"""
async with Client(fastmcp_openapi_server) as client:
tool_response = await client.call_tool(
"update_user_name_users",
{"user_id": 1, "name": "XYZ"},
)
expected_user = User(id=1, name="XYZ", active=True)
# Compare the data content since MCP client creates different class instances
assert tool_response.data.id == expected_user.id
assert tool_response.data.name == expected_user.name
assert tool_response.data.active == expected_user.active
# Check that the user was updated via API
response = await api_client.get("/users")
assert expected_user.model_dump() in response.json()
# Check that the user was updated via MCP
async with Client(fastmcp_openapi_server) as client:
user_response = await client.read_resource("resource://get_user_users/1")
response_text = user_response[0].text # type: ignore[attr-defined]
user = json.loads(response_text)
assert user == expected_user.model_dump()
async def test_call_tool_return_list(
self,
fastapi_app: FastAPI,
api_client: httpx.AsyncClient,
users_db: dict[int, User],
):
"""
The tool created by the OpenAPI server should return a list of content.
"""
openapi_spec = fastapi_app.openapi()
mcp_server = FastMCPOpenAPI(
openapi_spec=openapi_spec,
client=api_client,
route_maps=[
RouteMap(methods=["GET"], pattern=r".*", mcp_type=MCPType.TOOL)
],
)
async with Client(mcp_server) as client:
tool_response = await client.call_tool("get_users_users_get", {})
# The tool response should now be unwrapped since we have output schema
assert tool_response.data == [
user.model_dump()
for user in sorted(users_db.values(), key=lambda x: x.id)
]
class TestResources:
async def test_list_resources(self, fastmcp_openapi_server: FastMCPOpenAPI):
"""
By default, resources exclude GET methods without parameters
"""
async with Client(fastmcp_openapi_server) as client:
resources = await client.list_resources()
assert len(resources) == 4
assert resources[0].uri == AnyUrl("resource://get_users_users_get")
assert resources[0].name == "get_users_users_get"
async def test_get_resource(
self,
fastmcp_openapi_server: FastMCPOpenAPI,
api_client,
users_db: dict[int, User],
):
"""
The resource created by the OpenAPI server should be the same as the original
"""
json_users = TypeAdapter(list[User]).dump_python(
sorted(users_db.values(), key=lambda x: x.id)
)
async with Client(fastmcp_openapi_server) as client:
resource_response = await client.read_resource(
"resource://get_users_users_get"
)
response_text = resource_response[0].text # type: ignore[attr-defined]
resource = json.loads(response_text)
assert resource == json_users
response = await api_client.get("/users")
assert response.json() == json_users
async def test_get_bytes_resource(
self,
fastmcp_openapi_server: FastMCPOpenAPI,
api_client,
):
"""Test reading a resource that returns bytes."""
async with Client(fastmcp_openapi_server) as client:
resource_response = await client.read_resource(
"resource://ping_bytes_ping_bytes_get"
)
assert isinstance(resource_response[0], BlobResourceContents)
assert base64.b64decode(resource_response[0].blob) == b"pong"
async def test_get_str_resource(
self,
fastmcp_openapi_server: FastMCPOpenAPI,
api_client,
):
"""Test reading a resource that returns a string."""
async with Client(fastmcp_openapi_server) as client:
resource_response = await client.read_resource("resource://ping_ping_get")
assert resource_response[0].text == "pong" # type: ignore[attr-defined]
class TestResourceTemplates:
async def test_list_resource_templates(
self, fastmcp_openapi_server: FastMCPOpenAPI
):
"""
By default, resource templates exclude GET methods without parameters
"""
async with Client(fastmcp_openapi_server) as client:
resource_templates = await client.list_resource_templates()
assert len(resource_templates) == 2
assert resource_templates[0].name == "get_user_users"
assert (
resource_templates[0].uriTemplate == r"resource://get_user_users/{user_id}"
)
assert resource_templates[1].name == "get_user_active_state_users"
assert (
resource_templates[1].uriTemplate
== r"resource://get_user_active_state_users/{is_active}/{user_id}"
)
async def test_get_resource_template(
self,
fastmcp_openapi_server: FastMCPOpenAPI,
api_client,
users_db: dict[int, User],
):
"""
The resource template created by the OpenAPI server should be the same as the original
"""
user_id = 2
async with Client(fastmcp_openapi_server) as client:
resource_response = await client.read_resource(
f"resource://get_user_users/{user_id}"
)
response_text = resource_response[0].text # type: ignore[attr-defined]
resource = json.loads(response_text)
assert resource == users_db[user_id].model_dump()
response = await api_client.get(f"/users/{user_id}")
assert resource == response.json()
async def test_get_resource_template_multi_param(
self,
fastmcp_openapi_server: FastMCPOpenAPI,
api_client,
users_db: dict[int, User],
):
"""
The resource template created by the OpenAPI server should be the same as the original
"""
user_id = 2
is_active = True
async with Client(fastmcp_openapi_server) as client:
resource_response = await client.read_resource(
f"resource://get_user_active_state_users/{is_active}/{user_id}"
)
response_text = resource_response[0].text # type: ignore[attr-defined]
resource = json.loads(response_text)
assert resource == users_db[user_id].model_dump()
response = await api_client.get(f"/users/{user_id}/{is_active}")
assert resource == response.json()
class TestPrompts:
async def test_list_prompts(self, fastmcp_openapi_server: FastMCPOpenAPI):
"""
By default, there are no prompts.
"""
async with Client(fastmcp_openapi_server) as client:
prompts = await client.list_prompts()
assert len(prompts) == 0
|