Spaces:
Running
Running
File size: 20,104 Bytes
17763eb a01a818 4a12d22 17763eb bacf327 a01a818 bacf327 17763eb bacf327 a01a818 b86019e a01a818 a922f59 a9cea6e bacf327 a9cea6e bacf327 a9cea6e 17763eb a9cea6e bacf327 a9cea6e 7e7d69e a9cea6e 7e7d69e a9cea6e 7b03b73 a9cea6e 7b03b73 a9cea6e 7b03b73 a9cea6e c1b2054 a9cea6e a01a818 09438a8 a01a818 aa46c09 b86019e 17763eb b86019e 7b03b73 b86019e a922f59 4a12d22 a922f59 4a12d22 a922f59 4a12d22 a922f59 4a12d22 a922f59 4a12d22 a922f59 bacf327 a922f59 bacf327 | 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 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 | import asyncio
import gc
import inspect
import logging
import os
import tempfile
from collections.abc import AsyncGenerator
from pathlib import Path
from typing import Any
import psutil
import pytest
from fastmcp.client.auth.bearer import BearerAuth
from fastmcp.client.auth.oauth import OAuthClientProvider
from fastmcp.client.client import Client
from fastmcp.client.logging import LogMessage
from fastmcp.client.transports import (
MCPConfigTransport,
SSETransport,
StdioTransport,
StreamableHttpTransport,
)
from fastmcp.mcp_config import (
CanonicalMCPConfig,
CanonicalMCPServerTypes,
MCPConfig,
MCPServerTypes,
RemoteMCPServer,
StdioMCPServer,
TransformingStdioMCPServer,
)
from fastmcp.tools.tool import Tool as FastMCPTool
def running_under_debugger():
return os.environ.get("DEBUGPY_RUNNING") == "true"
def gc_collect_harder():
gc.collect()
gc.collect()
gc.collect()
gc.collect()
gc.collect()
gc.collect()
def test_parse_single_stdio_config():
config = {
"mcpServers": {
"test_server": {
"command": "echo",
"args": ["hello"],
}
}
}
mcp_config = MCPConfig.from_dict(config)
transport = mcp_config.mcpServers["test_server"].to_transport()
assert isinstance(transport, StdioTransport)
assert transport.command == "echo"
assert transport.args == ["hello"]
def test_parse_extra_keys():
config = {
"mcpServers": {
"test_server": {
"command": "echo",
"args": ["hello"],
"leaf_extra": "leaf_extra",
}
},
"root_extra": "root_extra",
}
mcp_config = MCPConfig.from_dict(config)
serialized_mcp_config = mcp_config.to_dict()
assert serialized_mcp_config["root_extra"] == "root_extra"
assert (
serialized_mcp_config["mcpServers"]["test_server"]["leaf_extra"] == "leaf_extra"
)
def test_parse_mcpservers_at_root():
config = {
"test_server": {
"command": "echo",
"args": ["hello"],
}
}
mcp_config = MCPConfig.from_dict(config)
serialized_mcp_config = mcp_config.model_dump()
assert serialized_mcp_config["mcpServers"]["test_server"]["command"] == "echo"
assert serialized_mcp_config["mcpServers"]["test_server"]["args"] == ["hello"]
def test_parse_mcpservers_discriminator():
"""Test that the MCPConfig discriminator produces StdioMCPServer for a non-transforming server
and TransformingStdioMCPServer for a transforming server."""
config = {
"test_server": {
"command": "echo",
"args": ["hello"],
},
"test_server_two": {"command": "echo", "args": ["hello"], "tools": {}},
}
mcp_config = MCPConfig.from_dict(config)
test_server: MCPServerTypes = mcp_config.mcpServers["test_server"]
assert isinstance(test_server, StdioMCPServer)
test_server_two: MCPServerTypes = mcp_config.mcpServers["test_server_two"]
assert isinstance(test_server_two, TransformingStdioMCPServer)
canonical_mcp_config = CanonicalMCPConfig.from_dict(config)
canonical_test_server: CanonicalMCPServerTypes = canonical_mcp_config.mcpServers[
"test_server"
]
assert isinstance(canonical_test_server, StdioMCPServer)
canonical_test_server_two: CanonicalMCPServerTypes = (
canonical_mcp_config.mcpServers["test_server_two"]
)
assert isinstance(canonical_test_server_two, StdioMCPServer)
def test_parse_single_remote_config():
config = {
"mcpServers": {
"test_server": {
"url": "http://localhost:8000",
}
}
}
mcp_config = MCPConfig.from_dict(config)
transport = mcp_config.mcpServers["test_server"].to_transport()
assert isinstance(transport, StreamableHttpTransport)
assert transport.url == "http://localhost:8000"
def test_parse_remote_config_with_transport():
config = {
"mcpServers": {
"test_server": {
"url": "http://localhost:8000",
"transport": "sse",
}
}
}
mcp_config = MCPConfig.from_dict(config)
transport = mcp_config.mcpServers["test_server"].to_transport()
assert isinstance(transport, SSETransport)
assert transport.url == "http://localhost:8000"
def test_parse_remote_config_with_url_inference():
config = {
"mcpServers": {
"test_server": {
"url": "http://localhost:8000/sse/",
}
}
}
mcp_config = MCPConfig.from_dict(config)
transport = mcp_config.mcpServers["test_server"].to_transport()
assert isinstance(transport, SSETransport)
assert transport.url == "http://localhost:8000/sse/"
def test_parse_multiple_servers():
config = {
"mcpServers": {
"test_server": {
"url": "http://localhost:8000/sse/",
},
"test_server_2": {
"command": "echo",
"args": ["hello"],
"env": {"TEST": "test"},
},
}
}
mcp_config = MCPConfig.from_dict(config)
assert len(mcp_config.mcpServers) == 2
assert isinstance(mcp_config.mcpServers["test_server"], RemoteMCPServer)
assert isinstance(mcp_config.mcpServers["test_server"].to_transport(), SSETransport)
assert isinstance(mcp_config.mcpServers["test_server_2"], StdioMCPServer)
assert isinstance(
mcp_config.mcpServers["test_server_2"].to_transport(), StdioTransport
)
assert mcp_config.mcpServers["test_server_2"].command == "echo"
assert mcp_config.mcpServers["test_server_2"].args == ["hello"]
assert mcp_config.mcpServers["test_server_2"].env == {"TEST": "test"}
async def test_multi_client(tmp_path: Path):
server_script = inspect.cleandoc("""
from fastmcp import FastMCP
mcp = FastMCP()
@mcp.tool
def add(a: int, b: int) -> int:
return a + b
if __name__ == '__main__':
mcp.run()
""")
script_path = tmp_path / "test.py"
script_path.write_text(server_script)
config = {
"mcpServers": {
"test_1": {
"command": "python",
"args": [str(script_path)],
},
"test_2": {
"command": "python",
"args": [str(script_path)],
},
}
}
client = Client(config)
async with client:
tools = await client.list_tools()
assert len(tools) == 2
result_1 = await client.call_tool("test_1_add", {"a": 1, "b": 2})
result_2 = await client.call_tool("test_2_add", {"a": 1, "b": 2})
assert result_1.data == 3
assert result_2.data == 3
@pytest.mark.skipif(
running_under_debugger(), reason="Debugger holds a reference to the transport"
)
async def test_multi_client_lifespan(tmp_path: Path):
pid_1: int | None = None
pid_2: int | None = None
async def test_server():
server_script = inspect.cleandoc("""
from fastmcp import FastMCP
import os
mcp = FastMCP()
@mcp.tool
def pid() -> int:
return os.getpid()
if __name__ == '__main__':
mcp.run()
""")
script_path = tmp_path / "test.py"
script_path.write_text(server_script)
config = {
"mcpServers": {
"test_1": {
"command": "python",
"args": [str(script_path)],
},
"test_2": {
"command": "python",
"args": [str(script_path)],
},
}
}
transport = MCPConfigTransport(config)
client = Client(transport)
async with client:
nonlocal pid_1
pid_1 = (await client.call_tool("test_1_pid")).data
nonlocal pid_2
pid_2 = (await client.call_tool("test_2_pid")).data
await test_server()
gc_collect_harder()
# This test will fail while debugging because the debugger holds a reference to the underlying transport
with pytest.raises(psutil.NoSuchProcess):
while True:
psutil.Process(pid_1)
await asyncio.sleep(0.1)
with pytest.raises(psutil.NoSuchProcess):
while True:
psutil.Process(pid_2)
await asyncio.sleep(0.1)
async def test_multi_client_force_close(tmp_path: Path):
server_script = inspect.cleandoc("""
from fastmcp import FastMCP
import os
mcp = FastMCP()
@mcp.tool
def pid() -> int:
return os.getpid()
if __name__ == '__main__':
mcp.run()
""")
script_path = tmp_path / "test.py"
script_path.write_text(server_script)
config = {
"mcpServers": {
"test_1": {
"command": "python",
"args": [str(script_path)],
},
"test_2": {
"command": "python",
"args": [str(script_path)],
},
}
}
transport = MCPConfigTransport(config)
client = Client(transport)
async with client:
pid_1 = (await client.call_tool("test_1_pid")).data
pid_2 = (await client.call_tool("test_2_pid")).data
await client.close()
gc_collect_harder()
with pytest.raises(psutil.NoSuchProcess):
process = psutil.Process(pid_1)
assert not process
with pytest.raises(psutil.NoSuchProcess):
process = psutil.Process(pid_2)
assert not process
async def test_remote_config_default_no_auth():
config = {
"mcpServers": {
"test_server": {
"url": "http://localhost:8000",
}
}
}
client = Client(config)
assert isinstance(client.transport.transport, StreamableHttpTransport)
assert client.transport.transport.auth is None
async def test_remote_config_with_auth_token():
config = {
"mcpServers": {
"test_server": {
"url": "http://localhost:8000",
"auth": "test_token",
}
}
}
client = Client(config)
assert isinstance(client.transport.transport, StreamableHttpTransport)
assert isinstance(client.transport.transport.auth, BearerAuth)
assert client.transport.transport.auth.token.get_secret_value() == "test_token"
async def test_remote_config_sse_with_auth_token():
config = {
"mcpServers": {
"test_server": {
"url": "http://localhost:8000/sse/",
"auth": "test_token",
}
}
}
client = Client(config)
assert isinstance(client.transport.transport, SSETransport)
assert isinstance(client.transport.transport.auth, BearerAuth)
assert client.transport.transport.auth.token.get_secret_value() == "test_token"
async def test_remote_config_with_oauth_literal():
config = {
"mcpServers": {
"test_server": {
"url": "http://localhost:8000",
"auth": "oauth",
}
}
}
client = Client(config)
assert isinstance(client.transport.transport, StreamableHttpTransport)
assert isinstance(client.transport.transport.auth, OAuthClientProvider)
async def test_multi_client_with_logging(tmp_path: Path, caplog):
"""
Tests that logging is properly forwarded to the ultimate client.
"""
caplog.set_level(logging.INFO, logger=__name__)
server_script = inspect.cleandoc("""
from fastmcp import FastMCP, Context
mcp = FastMCP()
@mcp.tool
async def log_test(message: str, ctx: Context) -> int:
await ctx.log(message)
return 42
if __name__ == '__main__':
mcp.run()
""")
script_path = tmp_path / "test.py"
script_path.write_text(server_script)
config = {
"mcpServers": {
"test_server": {
"command": "python",
"args": [str(script_path)],
},
"test_server_2": {
"command": "python",
"args": [str(script_path)],
},
}
}
MESSAGES = []
logger = logging.getLogger(__name__)
# Backwards-compatible way to get the log level mapping
if hasattr(logging, "getLevelNamesMapping"):
# For Python 3.11+
LOGGING_LEVEL_MAP = logging.getLevelNamesMapping() # pyright: ignore [reportAttributeAccessIssue]
else:
# For older Python versions
LOGGING_LEVEL_MAP = logging._nameToLevel
async def log_handler(message: LogMessage):
MESSAGES.append(message)
level = LOGGING_LEVEL_MAP[message.level.upper()]
msg = message.data.get("msg")
extra = message.data.get("extra")
logger.log(level, msg, extra=extra)
async with Client(config, log_handler=log_handler) as client:
result = await client.call_tool("test_server_log_test", {"message": "test 42"})
assert result.data == 42
assert len(MESSAGES) == 1
assert MESSAGES[0].data["msg"] == "test 42"
assert len(caplog.records) == 1
assert caplog.records[0].msg == "test 42"
async def test_multi_client_with_transforms(tmp_path: Path):
"""
Tests that transforms are properly applied to the tools.
"""
server_script = inspect.cleandoc("""
from fastmcp import FastMCP
mcp = FastMCP()
@mcp.tool
def add(a: int, b: int) -> int:
return a + b
if __name__ == '__main__':
mcp.run()
""")
script_path = tmp_path / "test.py"
script_path.write_text(server_script)
config = {
"mcpServers": {
"test_1": {
"command": "python",
"args": [str(script_path)],
"tools": {
"add": {
"name": "transformed_add",
"arguments": {
"a": {"name": "transformed_a"},
"b": {"name": "transformed_b"},
},
}
},
},
"test_2": {
"command": "python",
"args": [str(script_path)],
},
}
}
client = Client[MCPConfigTransport](config)
async with client:
tools = await client.list_tools()
tools_by_name = {tool.name: tool for tool in tools}
assert len(tools) == 2
assert "test_1_transformed_add" in tools_by_name
result = await client.call_tool(
"test_1_transformed_add", {"transformed_a": 1, "transformed_b": 2}
)
assert result.data == 3
async def test_canonical_multi_client_with_transforms(tmp_path: Path):
"""Test that transforms are not applied to servers in a canonical MCPConfig."""
server_script = inspect.cleandoc("""
from fastmcp import FastMCP
mcp = FastMCP()
@mcp.tool
def add(a: int, b: int) -> int:
return a + b
if __name__ == '__main__':
mcp.run()
""")
script_path = tmp_path / "test.py"
script_path.write_text(server_script)
config = CanonicalMCPConfig(
mcpServers={
"test_1": {
"command": "python",
"args": [str(script_path)],
"tools": { # <--- Will be ignored as its not valid for a canonical MCPConfig
"add": {
"name": "transformed_add",
"arguments": {
"a": {"name": "transformed_a"},
"b": {"name": "transformed_b"},
},
}
},
},
"test_2": {
"command": "python",
"args": [str(script_path)],
},
} # type: ignore[reportUnknownArgumentType]
)
client = Client(config)
async with client:
tools = await client.list_tools()
tools_by_name = {tool.name: tool for tool in tools}
assert len(tools) == 2
assert "test_1_transformed_add" not in tools_by_name
async def test_multi_client_transform_with_filtering(tmp_path: Path):
"""
Tests that tag-based filtering works when using a transforming MCPConfig.
"""
server_script = inspect.cleandoc("""
from fastmcp import FastMCP
mcp = FastMCP()
@mcp.tool
def add(a: int, b: int) -> int:
return a + b
@mcp.tool
def subtract(a: int, b: int) -> int:
return a - b
if __name__ == '__main__':
mcp.run()
""")
script_path = tmp_path / "test.py"
script_path.write_text(server_script)
config = {
"mcpServers": {
"test_1": {
"command": "python",
"args": [str(script_path)],
"tools": {
"add": {
"name": "transformed_add",
"tags": ["keep"],
"arguments": {
"a": {"name": "transformed_a"},
"b": {"name": "transformed_b"},
},
},
},
"include_tags": ["keep"],
},
"test_2": {
"command": "python",
"args": [str(script_path)],
},
}
}
client = Client[MCPConfigTransport](config)
async with client:
tools = await client.list_tools()
tools_by_name = {tool.name: tool for tool in tools}
assert len(tools) == 3
assert "test_1_transformed_add" in tools_by_name
assert "test_1_add" not in tools_by_name
assert "test_1_subtract" not in tools_by_name
assert "test_2_add" in tools_by_name
assert "test_2_subtract" in tools_by_name
async def test_multi_client_with_elicitation(tmp_path: Path):
"""
Tests that elicitation is properly forwarded to the ultimate client.
"""
server_script = inspect.cleandoc("""
from fastmcp import FastMCP, Context
mcp = FastMCP()
@mcp.tool
async def elicit_test(ctx: Context) -> int:
result = await ctx.elicit('Pick a number', response_type=int)
return result.data
if __name__ == '__main__':
mcp.run()
""")
script_path = tmp_path / "test.py"
script_path.write_text(server_script)
config = {
"mcpServers": {
"test_server": {
"command": "python",
"args": [str(script_path)],
},
"test_server_2": {
"command": "python",
"args": [str(script_path)],
},
}
}
async def elicitation_handler(message, response_type, params, ctx):
return response_type(value=42)
async with Client(config, elicitation_handler=elicitation_handler) as client:
result = await client.call_tool("test_server_elicit_test", {})
assert result.data == 42
def sample_tool_fn(arg1: int, arg2: str) -> str:
return f"Hello, world! {arg1} {arg2}"
@pytest.fixture
def sample_tool() -> FastMCPTool:
return FastMCPTool.from_function(sample_tool_fn, name="sample_tool")
@pytest.fixture
async def test_script(tmp_path: Path) -> AsyncGenerator[Path, Any]:
with tempfile.NamedTemporaryFile() as f:
f.write(b"""
from fastmcp import FastMCP
mcp = FastMCP()
@mcp.tool
def fetch(url: str) -> str:
return f"Hello, world! {url}"
if __name__ == '__main__':
mcp.run()
""")
yield Path(f.name)
pass
|