Spaces:
Running
Running
File size: 97,116 Bytes
137b0c2 0ce024d 137b0c2 0ce024d aa46c09 ae3ce72 137b0c2 3a9d761 137b0c2 177d39a 137b0c2 8ad9001 1b1304a 8dc263e 137b0c2 aa46c09 137b0c2 2c75133 177d39a 8dc263e 4757dcb 582f82a aa46c09 677a8fb 957b451 2dc14d6 137b0c2 3ab4db9 aa46c09 137b0c2 09438a8 137b0c2 09438a8 137b0c2 09438a8 137b0c2 09438a8 137b0c2 8ad9001 09438a8 2dc14d6 137b0c2 2dc14d6 1b1304a 137b0c2 aa46c09 137b0c2 aa46c09 8ad9001 aa46c09 2dc14d6 135c70a 137b0c2 135c70a 137b0c2 aa46c09 137b0c2 aa46c09 137b0c2 aa46c09 137b0c2 aa46c09 137b0c2 2c75133 09438a8 2c75133 137b0c2 ff32168 aa46c09 137b0c2 135c70a aa46c09 135c70a e71392d 1175ac0 aa46c09 1175ac0 aa46c09 1175ac0 e71392d 09438a8 e71392d aa46c09 e71392d 09438a8 e71392d aa46c09 e71392d 09438a8 e71392d aa46c09 e71392d 09438a8 e71392d aa46c09 e71392d 09438a8 e71392d aa46c09 e71392d 09438a8 e71392d 137b0c2 e71392d 137b0c2 aa46c09 137b0c2 8ad9001 aa46c09 8ad9001 2dc14d6 aa46c09 2dc14d6 137b0c2 aa46c09 137b0c2 2dc14d6 137b0c2 2dc14d6 137b0c2 aa46c09 137b0c2 aa46c09 137b0c2 aa46c09 137b0c2 aa46c09 137b0c2 8ad9001 aa46c09 8ad9001 aa46c09 8ad9001 aa46c09 8ad9001 aa46c09 8ad9001 2dc14d6 aa46c09 2dc14d6 aa46c09 2dc14d6 aa46c09 2dc14d6 aa46c09 2dc14d6 0ce024d ae3ce72 09438a8 ae3ce72 137b0c2 09438a8 137b0c2 ae3ce72 137b0c2 2dc7995 09438a8 2dc7995 aa46c09 2dc7995 120f8eb 09438a8 120f8eb 177d39a 77b11ea 120f8eb ae3ce72 77b11ea ae3ce72 09438a8 ae3ce72 77b11ea ae3ce72 77b11ea ae3ce72 09438a8 ae3ce72 77b11ea ae3ce72 77b11ea ae3ce72 09438a8 ae3ce72 77b11ea ae3ce72 09438a8 ae3ce72 77b11ea ae3ce72 09438a8 ae3ce72 77b11ea ae3ce72 09438a8 ae3ce72 77b11ea ae3ce72 09438a8 ae3ce72 aa46c09 ae3ce72 09438a8 ae3ce72 77b11ea ae3ce72 09438a8 ae3ce72 aa46c09 ae3ce72 09438a8 ae3ce72 aa46c09 ae3ce72 aa46c09 ae3ce72 77b11ea ae3ce72 0ce024d 09438a8 0ce024d d8d02f6 0ce024d d8d02f6 aa46c09 0ce024d 09438a8 0ce024d 77b11ea 0ce024d 09438a8 0ce024d aa46c09 0ce024d 09438a8 0ce024d 177d39a 0ce024d 09438a8 0ce024d dfd1df8 0ce024d dfd1df8 aa46c09 0ce024d 09438a8 0ce024d aa46c09 0ce024d 09438a8 0ce024d 177d39a 0ce024d 09438a8 0ce024d aa46c09 0ce024d 09438a8 0ce024d aa46c09 0ce024d 09438a8 0ce024d aa46c09 0ce024d 77b11ea 0ce024d 09438a8 0ce024d 77b11ea 0ce024d 0e1f06a 137b0c2 11ebe03 aa46c09 11ebe03 aa46c09 11ebe03 aa46c09 677a8fb aa46c09 743f189 aa46c09 677a8fb aa46c09 3ab4db9 aa46c09 d4466da aa46c09 d4466da aa46c09 11ebe03 3a9d761 c7c6360 3a9d761 743f189 c7c6360 3a9d761 c7c6360 3a9d761 677a8fb 3a9d761 677a8fb 3a9d761 677a8fb 3a9d761 743f189 3a9d761 743f189 3a9d761 11ebe03 31e3fd3 09438a8 31e3fd3 09438a8 31e3fd3 aa46c09 31e3fd3 09438a8 31e3fd3 aa46c09 31e3fd3 09438a8 31e3fd3 aa46c09 31e3fd3 09438a8 31e3fd3 aa46c09 31e3fd3 acef890 a853a78 acef890 aa46c09 acef890 31e3fd3 788b7e2 55471df 788b7e2 55471df 788b7e2 55471df 788b7e2 acef890 31e3fd3 137b0c2 d4fceae 137b0c2 d4fceae 137b0c2 d4fceae 137b0c2 d4fceae 137b0c2 e3f57a4 137b0c2 1175ac0 8ad9001 1175ac0 31e3fd3 c04707c 31e3fd3 55471df 31e3fd3 137b0c2 d4fceae 137b0c2 ef81ec0 137b0c2 d4fceae 137b0c2 ef81ec0 137b0c2 d4fceae 137b0c2 ef81ec0 d4fceae ef81ec0 137b0c2 d4fceae 137b0c2 d4fceae 137b0c2 d4fceae 137b0c2 d4fceae 137b0c2 d4fceae 137b0c2 d4fceae 137b0c2 d4fceae 137b0c2 d4fceae 137b0c2 e3f57a4 137b0c2 1175ac0 8ad9001 1175ac0 31e3fd3 137b0c2 31e3fd3 137b0c2 31e3fd3 c04707c 137b0c2 acef890 4757dcb acef890 c04707c acef890 137b0c2 55471df 8ad9001 55471df acef890 137b0c2 f6c5553 137b0c2 d4fceae 137b0c2 d4fceae 137b0c2 d4fceae 137b0c2 f6c5553 137b0c2 26b329e f6c5553 137b0c2 f6c5553 137b0c2 65ead06 cd7d4ca 65ead06 cd7d4ca 65ead06 cd7d4ca 65ead06 cd7d4ca 65ead06 137b0c2 f6c5553 137b0c2 3becd4d 137b0c2 d4fceae 137b0c2 f6c5553 3becd4d 137b0c2 3becd4d 137b0c2 3becd4d 8dc263e 137b0c2 177d39a 137b0c2 f6c5553 137b0c2 177d39a 137b0c2 31e3fd3 8604c71 55471df 8604c71 55471df 8604c71 55471df 8604c71 31e3fd3 f6c5553 31e3fd3 3becd4d 31e3fd3 acef890 a853a78 acef890 c04707c 1175ac0 957b451 | 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 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 | import base64
import datetime
import json
import uuid
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import Annotated, Any, Literal
import pytest
from mcp import McpError
from mcp.types import (
AudioContent,
BlobResourceContents,
EmbeddedResource,
ImageContent,
TextContent,
TextResourceContents,
)
from pydantic import AnyUrl, BaseModel, Field, TypeAdapter
from typing_extensions import TypedDict
from fastmcp import Client, Context, FastMCP
from fastmcp.client.transports import FastMCPTransport
from fastmcp.exceptions import ToolError
from fastmcp.prompts.prompt import Prompt, PromptMessage
from fastmcp.resources import FileResource, ResourceTemplate
from fastmcp.resources.resource import FunctionResource
from fastmcp.tools.tool import Tool, ToolResult
from fastmcp.utilities.json_schema import compress_schema
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
@pytest.fixture
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 result.content[0].text == "3" # type: ignore[attr-defined]
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 result.content[0].text == "3" # type: ignore[attr-defined]
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", {})
assert result.content[0].text == '["x",2]' # type: ignore[attr-defined]
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 TestToolReturnTypes:
async def test_string(self):
mcp = FastMCP()
@mcp.tool
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!"
async def test_bytes(self, tmp_path: Path):
mcp = FastMCP()
@mcp.tool
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!"
async def test_uuid(self):
mcp = FastMCP()
test_uuid = uuid.uuid4()
@mcp.tool
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)
async def test_path(self):
mcp = FastMCP()
test_path = Path("/tmp/test.txt")
@mcp.tool
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)
async def test_datetime(self):
mcp = FastMCP()
dt = datetime.datetime(2025, 4, 25, 1, 2, 3)
@mcp.tool
def datetime_tool() -> datetime.datetime:
return dt
async with Client(mcp) as client:
result = await client.call_tool("datetime_tool", {})
assert result.data == dt
async def test_image(self, tmp_path: Path):
mcp = FastMCP()
@mcp.tool
def image_tool(path: str) -> Image:
return Image(path)
# Create a test image
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"
# Verify base64 encoding
decoded = base64.b64decode(content.data)
assert decoded == b"fake png data"
async def test_audio(self, tmp_path: Path):
mcp = FastMCP()
@mcp.tool
def audio_tool(path: str) -> Audio:
return Audio(path)
# Create a test audio file
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"
# Verify base64 encoding
decoded = base64.b64decode(content.data)
assert decoded == b"fake wav data"
async def test_file(self, tmp_path: Path):
mcp = FastMCP()
@mcp.tool
def file_tool(path: str) -> File:
return File(path)
# Create a test file
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"
# Verify base64 encoding
assert hasattr(resource, "blob")
blob_data = getattr(resource, "blob")
decoded = base64.b64decode(blob_data)
assert decoded == b"test file data"
# Verify URI points to the file
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"
async def test_tool_mixed_list_with_image(
self, tool_server: FastMCP, tmp_path: Path
):
"""Test that lists containing Image objects and other types are handled
correctly. Note that the non-MCP content will be grouped together."""
# Create a test image
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) == 3
# Check text conversion
content1 = result.content[0]
assert isinstance(content1, TextContent)
assert json.loads(content1.text) == ["text message", {"key": "value"}]
# Check image conversion
content2 = result.content[1]
assert isinstance(content2, ImageContent)
assert content2.mimeType == "image/png"
assert base64.b64decode(content2.data) == b"test image data"
# Check direct TextContent
content3 = result.content[2]
assert isinstance(content3, TextContent)
assert content3.text == "direct content"
async def test_tool_mixed_list_with_audio(
self, tool_server: FastMCP, tmp_path: Path
):
"""Test that lists containing Audio objects and other types are handled
correctly. Note that the non-MCP content will be grouped together."""
# Create a test audio file
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) == 3
# Check text conversion
content1 = result.content[0]
assert isinstance(content1, TextContent)
assert json.loads(content1.text) == ["text message", {"key": "value"}]
# Check audio conversion
content2 = result.content[1]
assert isinstance(content2, AudioContent)
assert content2.mimeType == "audio/wav"
assert base64.b64decode(content2.data) == b"test audio data"
# Check direct TextContent
content3 = result.content[2]
assert isinstance(content3, TextContent)
assert content3.text == "direct content"
async def test_tool_mixed_list_with_file(
self, tool_server: FastMCP, tmp_path: Path
):
"""Test that lists containing File objects and other types are handled
correctly. Note that the non-MCP content will be grouped together."""
# Create a test file
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) == 3
# Check text conversion
content1 = result.content[0]
assert isinstance(content1, TextContent)
assert json.loads(content1.text) == ["text message", {"key": "value"}]
# Check file conversion
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"
# Check direct TextContent
content3 = result.content[2]
assert isinstance(content3, TextContent)
assert content3.text == "direct content"
class TestToolParameters:
async def test_parameter_descriptions_with_field_annotations(self):
mcp = FastMCP("Test Server")
@mcp.tool
def greet(
name: Annotated[str, Field(description="The name to greet")],
title: Annotated[str, Field(description="Optional title", default="")],
) -> str:
"""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]
# Check that parameter descriptions are present in the schema
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"]
async def test_parameter_descriptions_with_field_defaults(self):
mcp = FastMCP("Test Server")
@mcp.tool
def greet(
name: str = Field(description="The name to greet"),
title: str = Field(description="Optional title", default=""),
) -> str:
"""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]
# Check that parameter descriptions are present in the schema
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"]
async def test_tool_with_bytes_input(self):
mcp = FastMCP()
@mcp.tool
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()
async def test_tool_with_invalid_input(self):
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 validation error: 'not an int' is not of type 'integer'",
):
await client.call_tool("my_tool", {"x": "not an int"})
async def test_tool_int_coercion(self):
"""Test that invalid int input raises validation error."""
mcp = FastMCP()
@mcp.tool
def add_one(x: int) -> int:
return x + 1
async with Client(mcp) as client:
# String input should raise validation error (no coercion)
with pytest.raises(
ToolError,
match="Input validation error: '42' is not of type 'integer'",
):
await client.call_tool("add_one", {"x": "42"})
async def test_tool_bool_coercion(self):
"""Test that invalid bool input raises validation error."""
mcp = FastMCP()
@mcp.tool
def toggle(flag: bool) -> bool:
return not flag
async with Client(mcp) as client:
# String input should raise validation error (no coercion)
with pytest.raises(
ToolError,
match="Input validation error: 'true' is not of type 'boolean'",
):
await client.call_tool("toggle", {"flag": "true"})
with pytest.raises(
ToolError,
match="Input validation error: 'false' is not of type 'boolean'",
):
await client.call_tool("toggle", {"flag": "false"})
async def test_annotated_field_validation(self):
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 validation error: 0 is less than the minimum of 1",
):
await client.call_tool("analyze", {"x": 0})
async def test_default_field_validation(self):
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 validation error: 0 is less than the minimum of 1",
):
await client.call_tool("analyze", {"x": 0})
async def test_default_field_is_still_required_if_no_default_specified(self):
mcp = FastMCP()
@mcp.tool
def analyze(x: int = Field()) -> None:
pass
async with Client(mcp) as client:
with pytest.raises(
ToolError, match="Input validation error: 'x' is a required property"
):
await client.call_tool("analyze", {})
async def test_literal_type_validation_error(self):
mcp = FastMCP()
@mcp.tool
def analyze(x: Literal["a", "b"]) -> None:
pass
async with Client(mcp) as client:
with pytest.raises(
ToolError,
match=r"Input validation error: 'c' is not one of \['a', 'b'\]",
):
await client.call_tool("analyze", {"x": "c"})
async def test_literal_type_validation_success(self):
mcp = FastMCP()
@mcp.tool
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"
async def test_enum_type_validation_error(self):
mcp = FastMCP()
class MyEnum(Enum):
RED = "red"
GREEN = "green"
BLUE = "blue"
@mcp.tool
def analyze(x: MyEnum) -> str:
return x.value
async with Client(mcp) as client:
with pytest.raises(
ToolError,
match=r"Input validation error: 'some-color' is not one of \['red', 'green', 'blue'\]",
):
await client.call_tool("analyze", {"x": "some-color"})
async def test_enum_type_validation_success(self):
mcp = FastMCP()
class MyEnum(Enum):
RED = "red"
GREEN = "green"
BLUE = "blue"
@mcp.tool
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"
async def test_union_type_validation(self):
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 client.call_tool("analyze", {"x": 1.0})
assert result.data == "1.0"
with pytest.raises(
ToolError,
match="Input validation error: 'not a number' is not valid under any of the given schemas",
):
await client.call_tool("analyze", {"x": "not a number"})
async def test_path_type(self):
mcp = FastMCP()
@mcp.tool
def send_path(path: Path) -> str:
assert isinstance(path, Path)
return str(path)
# Use a platform-independent path
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)
async def test_path_type_error(self):
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 validation error: 1 is not of type 'string'"
):
await client.call_tool("send_path", {"path": 1})
async def test_uuid_type(self):
mcp = FastMCP()
@mcp.tool
def send_uuid(x: uuid.UUID) -> str:
assert isinstance(x, uuid.UUID)
return str(x)
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)
async def test_uuid_type_error(self):
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="Error calling tool 'send_uuid'"):
await client.call_tool("send_uuid", {"x": "not a uuid"})
async def test_datetime_type(self):
mcp = FastMCP()
@mcp.tool
def send_datetime(x: datetime.datetime) -> str:
return x.isoformat()
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()
async def test_datetime_type_parse_string(self):
mcp = FastMCP()
@mcp.tool
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"
async def test_datetime_type_error(self):
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="Error calling tool 'send_datetime'"):
await client.call_tool("send_datetime", {"x": "not a datetime"})
async def test_date_type(self):
mcp = FastMCP()
@mcp.tool
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()
async def test_date_type_parse_string(self):
mcp = FastMCP()
@mcp.tool
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"
async def test_timedelta_type(self):
mcp = FastMCP()
@mcp.tool
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"
async def test_timedelta_type_parse_int(self):
"""Test that invalid timedelta input raises validation error."""
mcp = FastMCP()
@mcp.tool
def send_timedelta(x: datetime.timedelta) -> str:
return str(x)
async with Client(mcp) as client:
# Int input should raise validation error (no conversion)
with pytest.raises(
ToolError,
match="Input validation error: 1000 is not of type 'string'",
):
await client.call_tool("send_timedelta", {"x": 1000})
async def test_annotated_string_description(self):
mcp = FastMCP()
@mcp.tool
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"
class TestToolOutputSchema:
@pytest.mark.parametrize("annotation", [str, int, float, bool, list, AnyUrl])
async def test_simple_output_schema(self, annotation):
mcp = FastMCP()
@mcp.tool
def f() -> annotation: # type: ignore
return "hello"
async with Client(mcp) as client:
tools = await client.list_tools()
assert len(tools) == 1
type_schema = TypeAdapter(annotation).json_schema()
# this line will fail until MCP adds output schemas!!
assert tools[0].outputSchema == {
"type": "object",
"properties": {"result": {**type_schema, "title": "Result"}},
"required": ["result"],
"title": "_WrappedResult",
"x-fastmcp-wrap-result": True,
}
@pytest.mark.parametrize(
"annotation",
[dict[str, int | str], PersonTypedDict, PersonModel, PersonDataclass],
)
async def test_structured_output_schema(self, annotation):
mcp = FastMCP()
@mcp.tool
def f() -> annotation: # type: ignore[valid-type]
return {"name": "John", "age": 30}
async with Client(mcp) as client:
tools = await client.list_tools()
type_schema = compress_schema(TypeAdapter(annotation).json_schema())
assert len(tools) == 1
# Normalize anyOf ordering for comparison since union type order
# can vary between environments when using annotation resolution
actual_schema = _normalize_anyof_order(tools[0].outputSchema)
expected_schema = _normalize_anyof_order(type_schema)
assert actual_schema == expected_schema
async def test_disabled_output_schema_no_structured_content(self):
mcp = FastMCP()
@mcp.tool(output_schema=None)
def f() -> int:
return 42
async with Client(mcp) as client:
result = await client.call_tool("f", {})
assert result.content[0].text == "42" # type: ignore[attr-defined]
assert result.structured_content is None
assert result.data is None
async def test_manual_structured_content(self):
mcp = FastMCP()
@mcp.tool
def f() -> ToolResult:
return ToolResult(
content="Hello, world!", structured_content={"message": "Hello, world!"}
)
assert f.output_schema is None
async with Client(mcp) as client:
result = await client.call_tool("f", {})
assert result.content[0].text == "Hello, world!" # type: ignore[attr-defined]
assert result.structured_content == {"message": "Hello, world!"}
assert result.data == {"message": "Hello, world!"}
async def test_output_schema_false_full_handshake(self):
"""Test that output_schema=False works through full client/server
handshake. We test this by returning a scalar, which requires an output
schema to serialize."""
mcp = FastMCP()
@mcp.tool(output_schema=False) # type: ignore[arg-type]
def simple_tool() -> int:
return 42
async with Client(mcp) as client:
# List tools and verify output schema is None
tools = await client.list_tools()
tool = next(t for t in tools if t.name == "simple_tool")
assert tool.outputSchema is None
# Call tool and verify no structured content
result = await client.call_tool("simple_tool", {})
assert result.structured_content is None
assert result.data is None
assert result.content[0].text == "42" # type: ignore[attr-defined]
async def test_output_schema_explicit_object_full_handshake(self):
"""Test explicit object output schema through full client/server handshake."""
mcp = FastMCP()
@mcp.tool(
output_schema={
"type": "object",
"properties": {
"greeting": {"type": "string"},
"count": {"type": "integer"},
},
"required": ["greeting"],
}
)
def explicit_tool() -> dict[str, Any]:
return {"greeting": "Hello", "count": 42}
async with Client(mcp) as client:
# List tools and verify exact schema is preserved
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
# Call tool and verify structured content matches return value directly
result = await client.call_tool("explicit_tool", {})
assert result.structured_content == {"greeting": "Hello", "count": 42}
# Client deserializes according to schema, so check fields
assert result.data.greeting == "Hello" # type: ignore[attr-defined]
assert result.data.count == 42 # type: ignore[attr-defined]
async def test_output_schema_wrapped_primitive_full_handshake(self):
"""Test wrapped primitive output schema through full client/server handshake."""
mcp = FastMCP()
@mcp.tool
def primitive_tool() -> str:
return "Hello, primitives!"
async with Client(mcp) as client:
# List tools and verify schema shows wrapped structure
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", "title": "Result"}},
"required": ["result"],
"title": "_WrappedResult",
"x-fastmcp-wrap-result": True,
}
assert tool.outputSchema == expected_schema
# Call tool and verify structured content is wrapped
result = await client.call_tool("primitive_tool", {})
assert result.structured_content == {"result": "Hello, primitives!"}
assert result.data == "Hello, primitives!" # Client unwraps for convenience
async def test_output_schema_complex_type_full_handshake(self):
"""Test complex type output schema through full client/server handshake."""
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:
# List tools and verify schema shows wrapped array
tools = await client.list_tools()
tool = next(t for t in tools if t.name == "complex_tool")
expected_inner_schema = TypeAdapter(list[dict[str, int]]).json_schema()
expected_schema = {
"type": "object",
"properties": {"result": {**expected_inner_schema, "title": "Result"}},
"required": ["result"],
"title": "_WrappedResult",
"x-fastmcp-wrap-result": True,
}
assert tool.outputSchema == expected_schema
# Call tool and verify structured content is wrapped
result = await client.call_tool("complex_tool", {})
expected_data = [{"a": 1, "b": 2}, {"c": 3, "d": 4}]
assert result.structured_content == {"result": expected_data}
# Client deserializes - just verify we got data back
assert result.data is not None
async def test_output_schema_dataclass_full_handshake(self):
"""Test dataclass output schema through full client/server handshake."""
mcp = FastMCP()
@dataclass
class User:
name: str
age: int
@mcp.tool
def dataclass_tool() -> User:
return User(name="Alice", age=30)
async with Client(mcp) as client:
# List tools and verify schema is object type (not wrapped)
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())
assert tool.outputSchema == expected_schema
assert (
tool.outputSchema and "x-fastmcp-wrap-result" not in tool.outputSchema
)
# Call tool and verify structured content is direct
result = await client.call_tool("dataclass_tool", {})
assert result.structured_content == {"name": "Alice", "age": 30}
# Client deserializes according to schema
assert result.data.name == "Alice" # type: ignore[attr-defined]
assert result.data.age == 30 # type: ignore[attr-defined]
async def test_output_schema_mixed_content_types(self):
"""Test tools with mixed content and output schemas."""
mcp = FastMCP()
@mcp.tool
def mixed_output() -> list[Any]:
# Return mixed content that includes MCP types and regular data
return [
"text message",
{"structured": "data"},
TextContent(type="text", text="direct MCP content"),
]
async with Client(mcp) as client:
result = await client.call_tool("mixed_output", {})
# Should have multiple content blocks
assert len(result.content) >= 2
# Should have structured output with wrapped result
expected_data = [
"text message",
{"structured": "data"},
{
"type": "text",
"text": "direct MCP content",
"annotations": None,
"_meta": None,
},
]
assert result.structured_content == {"result": expected_data}
async def test_output_schema_serialization_edge_cases(self):
"""Test edge cases in output schema serialization."""
mcp = FastMCP()
@mcp.tool
def edge_case_tool() -> tuple[int, str]:
return (42, "hello")
async with Client(mcp) as client:
# Verify tuple gets proper schema
tools = await client.list_tools()
tool = next(t for t in tools if t.name == "edge_case_tool")
# Tuples should be wrapped since they're not object type
assert tool.outputSchema and "x-fastmcp-wrap-result" in tool.outputSchema
result = await client.call_tool("edge_case_tool", {})
# Should be wrapped with result key
assert result.structured_content == {"result": [42, "hello"]}
assert result.data == [42, "hello"]
class TestToolContextInjection:
"""Test context injection in tools."""
async def test_context_detection(self):
"""Test that context parameters are properly detected."""
mcp = FastMCP()
@mcp.tool
def tool_with_context(x: int, ctx: Context) -> str:
return f"Request {ctx.request_id}: {x}"
async with Client(mcp) as client:
tools = await client.list_tools()
assert len(tools) == 1
assert tools[0].name == "tool_with_context"
async def test_context_injection(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
async with Client(mcp) as client:
result = await client.call_tool("tool_with_context", {"x": 42})
assert result.data == "1"
async def test_async_context(self):
"""Test that context works in async functions."""
mcp = FastMCP()
@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}"
async with Client(mcp) as client:
result = await client.call_tool("async_tool", {"x": 42})
assert result.data == "Async request 1: 42"
async def test_optional_context(self):
"""Test that context is optional."""
mcp = FastMCP()
@mcp.tool
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
async def test_context_resource_access(self):
"""Test that context can access resources."""
mcp = FastMCP()
@mcp.resource("test://data")
def test_resource() -> str:
return "resource data"
@mcp.tool
async def tool_with_resource(ctx: Context) -> str:
r_iter = await ctx.read_resource("test://data")
r_list = list(r_iter)
assert len(r_list) == 1
r = r_list[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"
)
async def test_tool_decorator_with_tags(self):
"""Test that the tool decorator properly sets tags."""
mcp = FastMCP()
@mcp.tool(tags={"example", "test-tag"})
def sample_tool(x: int) -> int:
return x * 2
# Verify the tool exists
async with Client(mcp) as client:
tools = await client.list_tools()
assert len(tools) == 1
# Note: MCPTool from the client API doesn't expose tags
async def test_callable_object_with_context(self):
"""Test that a callable object can be used as a tool with context."""
mcp = FastMCP()
class MyTool:
async def __call__(self, x: int, ctx: Context) -> int:
return x + int(ctx.request_id)
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
class TestToolEnabled:
async def test_toggle_enabled(self):
mcp = FastMCP()
@mcp.tool
def sample_tool(x: int) -> int:
return x * 2
assert sample_tool.enabled
tool = await mcp.get_tool("sample_tool")
assert tool.enabled
tool.disable()
assert not tool.enabled
assert not sample_tool.enabled
tool.enable()
assert tool.enabled
assert sample_tool.enabled
async def test_tool_disabled_in_decorator(self):
mcp = FastMCP()
@mcp.tool(enabled=False)
def sample_tool(x: int) -> int:
return x * 2
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(enabled=False)
def sample_tool(x: int) -> int:
return x * 2
sample_tool.enable()
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
sample_tool.disable()
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("sample_tool")
assert tool.enabled
sample_tool.disable()
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(enabled=False)
def sample_tool(x: int) -> int:
return x * 2
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 result[0].text == "Hello, world!" # type: ignore[attr-defined]
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 result[0].blob == base64.b64encode(b"Binary data").decode() # type: ignore[attr-defined]
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 result[0].text == "Hello from file!" # type: ignore[attr-defined]
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 result[0].blob == base64.b64encode(b"Binary file data").decode() # type: ignore[attr-defined]
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 result[0].text == "1" # type: ignore[attr-defined]
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 TestResourceContext:
async def test_resource_with_context_annotation_gets_context(self):
mcp = FastMCP()
@mcp.resource("resource://test")
def resource_with_context(ctx: Context) -> str:
assert isinstance(ctx, Context)
return ctx.request_id
async with Client(mcp) as client:
result = await client.read_resource(AnyUrl("resource://test"))
assert result[0].text == "1" # type: ignore[attr-defined]
class TestResourceEnabled:
async def test_toggle_enabled(self):
mcp = FastMCP()
@mcp.resource("resource://data")
def sample_resource() -> str:
return "Hello, world!"
assert sample_resource.enabled
resource = await mcp.get_resource("resource://data")
assert resource.enabled
resource.disable()
assert not resource.enabled
assert not sample_resource.enabled
resource.enable()
assert resource.enabled
assert sample_resource.enabled
async def test_resource_disabled_in_decorator(self):
mcp = FastMCP()
@mcp.resource("resource://data", enabled=False)
def sample_resource() -> str:
return "Hello, world!"
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", enabled=False)
def sample_resource() -> str:
return "Hello, world!"
sample_resource.enable()
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!"
sample_resource.disable()
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.enabled
sample_resource.disable()
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", enabled=False)
def sample_resource() -> str:
return "Hello, world!"
with pytest.raises(McpError, match="Unknown resource"):
async with Client(mcp) as client:
await client.read_resource(AnyUrl("resource://data"))
class TestResourceTemplates:
async def test_resource_with_params_not_in_uri(self):
"""Test that a resource with function parameters raises an error if the URI
parameters don't match"""
mcp = FastMCP()
with pytest.raises(
ValueError,
match="URI template must contain at least one parameter",
):
@mcp.resource("resource://data")
def get_data_fn(param: str) -> str:
return f"Data: {param}"
async def test_resource_with_uri_params_without_args(self):
"""Test that a resource with URI parameters is automatically a template"""
mcp = FastMCP()
with pytest.raises(
ValueError,
match="URI parameters .* must be a subset of the function arguments",
):
@mcp.resource("resource://{param}")
def get_data() -> str:
return "Data"
async def test_resource_with_untyped_params(self):
"""Test that a resource with untyped parameters raises an error"""
mcp = FastMCP()
@mcp.resource("resource://{param}")
def get_data(param) -> str:
return "Data"
async def test_resource_matching_params(self):
"""Test that a resource with matching URI and function parameters works"""
mcp = FastMCP()
@mcp.resource("resource://{name}/data")
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 result[0].text == "Data for test" # type: ignore[attr-defined]
async def test_resource_mismatched_params(self):
"""Test that mismatched parameters raise an error"""
mcp = FastMCP()
with pytest.raises(
ValueError,
match="Required function arguments .* must be a subset of the URI parameters",
):
@mcp.resource("resource://{name}/data")
def get_data(user: str) -> str:
return f"Data for {user}"
async def test_resource_multiple_params(self):
"""Test that multiple parameters work correctly"""
mcp = FastMCP()
@mcp.resource("resource://{org}/{repo}/data")
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 result[0].text == "Data for cursor/fastmcp" # type: ignore[attr-defined]
async def test_resource_multiple_mismatched_params(self):
"""Test that mismatched parameters raise an error"""
mcp = FastMCP()
with pytest.raises(
ValueError,
match="Required function arguments .* must be a subset of the URI parameters",
):
@mcp.resource("resource://{org}/{repo}/data")
def get_data_mismatched(org: str, repo_2: str) -> str:
return f"Data for {org}"
"""Test that a resource with no parameters works as a regular resource"""
mcp = FastMCP()
@mcp.resource("resource://static")
def get_static_data() -> str:
return "Static data"
async with Client(mcp) as client:
result = await client.read_resource(AnyUrl("resource://static"))
assert result[0].text == "Static data" # type: ignore[attr-defined]
async def test_template_with_varkwargs(self):
"""Test that a template can have **kwargs."""
mcp = FastMCP()
@mcp.resource("test://{x}/{y}/{z}")
def func(**kwargs: int) -> int:
return sum(kwargs.values())
async with Client(mcp) as client:
result = await client.read_resource(AnyUrl("test://1/2/3"))
assert result[0].text == "6" # type: ignore[attr-defined]
async def test_template_with_default_params(self):
"""Test that a template can have default parameters."""
mcp = FastMCP()
@mcp.resource("math://add/{x}")
def add(x: int, y: int = 10) -> int:
return x + y
# Verify it's registered as a template
templates_dict = await mcp.get_resource_templates()
templates = list(templates_dict.values())
assert len(templates) == 1
assert templates[0].uri_template == "math://add/{x}"
# Call the template and verify it uses the default value
async with Client(mcp) as client:
result = await client.read_resource(AnyUrl("math://add/5"))
assert result[0].text == "15" # type: ignore[attr-defined]
# Can also call with explicit params
result2 = await client.read_resource(AnyUrl("math://add/7"))
assert result2[0].text == "17" # type: ignore[attr-defined]
async def test_template_to_resource_conversion(self):
"""Test that a template can be converted to a resource."""
mcp = FastMCP()
@mcp.resource("resource://{name}/data")
def get_data(name: str) -> str:
return f"Data for {name}"
# Verify it's registered as a template
templates_dict = await mcp.get_resource_templates()
templates = list(templates_dict.values())
assert len(templates) == 1
assert templates[0].uri_template == "resource://{name}/data"
# When accessed, should create a concrete resource
async with Client(mcp) as client:
result = await client.read_resource(AnyUrl("resource://test/data"))
assert result[0].text == "Data for test" # type: ignore[attr-defined]
async def test_template_decorator_with_tags(self):
mcp = FastMCP()
@mcp.resource("resource://{param}", tags={"template", "test-tag"})
def template_resource(param: str) -> str:
return f"Template resource: {param}"
templates_dict = await mcp.get_resource_templates()
template = templates_dict["resource://{param}"]
assert template.tags == {"template", "test-tag"}
async def test_template_decorator_wildcard_param(self):
mcp = FastMCP()
@mcp.resource("resource://{param*}")
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 result[0].text == "Template resource: test/data" # type: ignore[attr-defined]
async def test_templates_match_in_order_of_definition(self):
"""
If a wildcard template is defined first, it will take priority over another
matching template.
"""
mcp = FastMCP()
@mcp.resource("resource://{param*}")
def template_resource(param: str) -> str:
return f"Template resource 1: {param}"
@mcp.resource("resource://{x}/{y}")
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 result[0].text == "Template resource 1: a/b/c" # type: ignore[attr-defined]
result = await client.read_resource(AnyUrl("resource://a/b"))
assert result[0].text == "Template resource 1: a/b" # type: ignore[attr-defined]
async def test_templates_shadow_each_other_reorder(self):
"""
If a wildcard template is defined second, it will *not* take priority over
another matching template.
"""
mcp = FastMCP()
@mcp.resource("resource://{x}/{y}")
def template_resource_with_params(x: str, y: str) -> str:
return f"Template resource 1: {x}/{y}"
@mcp.resource("resource://{param*}")
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 result[0].text == "Template resource 2: a/b/c" # type: ignore[attr-defined]
result = await client.read_resource(AnyUrl("resource://a/b"))
assert result[0].text == "Template resource 1: a/b" # type: ignore[attr-defined]
async def test_resource_template_with_annotations(self):
"""Test that resource template annotations are visible to clients."""
mcp = FastMCP()
@mcp.resource(
"api://users/{user_id}",
annotations={"httpMethod": "GET", "Cache-Control": "no-cache"},
)
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
template = templates[0]
assert template.uriTemplate == "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"
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 result[0].text == "Template resource 1: x" # type: ignore[attr-defined]
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 result[0].text == "Template resource 2: x" # type: ignore[attr-defined]
class TestResourceTemplateContext:
async def test_resource_template_context(self):
mcp = FastMCP()
@mcp.resource("resource://{param}")
def resource_template(param: str, ctx: Context) -> str:
assert isinstance(ctx, Context)
return f"Resource template: {param} {ctx.request_id}"
async with Client(mcp) as client:
result = await client.read_resource(AnyUrl("resource://test"))
assert result[0].text.startswith("Resource template: test 1") # type: ignore[attr-defined]
async def test_resource_template_context_with_callable_object(self):
mcp = FastMCP()
class MyResource:
def __call__(self, param: str, ctx: Context) -> str:
return f"Resource template: {param} {ctx.request_id}"
template = ResourceTemplate.from_function(
MyResource(), uri_template="resource://{param}"
)
mcp.add_template(template)
async with Client(mcp) as client:
result = await client.read_resource(AnyUrl("resource://test"))
assert result[0].text.startswith("Resource template: test 1") # type: ignore[attr-defined]
class TestResourceTemplateEnabled:
async def test_toggle_enabled(self):
mcp = FastMCP()
@mcp.resource("resource://{param}")
def sample_template(param: str) -> str:
return f"Template: {param}"
assert sample_template.enabled
template = await mcp.get_resource_template("resource://{param}")
assert template.enabled
template.disable()
assert not template.enabled
assert not sample_template.enabled
template.enable()
assert template.enabled
assert sample_template.enabled
async def test_template_disabled_in_decorator(self):
mcp = FastMCP()
@mcp.resource("resource://{param}", enabled=False)
def sample_template(param: str) -> str:
return f"Template: {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}", enabled=False)
def sample_template(param: str) -> str:
return f"Template: {param}"
sample_template.enable()
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}"
sample_template.disable()
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.enabled
sample_template.disable()
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}", enabled=False)
def sample_template(param: str) -> str:
return f"Template: {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_dict = await mcp.get_prompts()
assert len(prompts_dict) == 1
prompt = prompts_dict["fn"]
assert prompt.name == "fn"
# Don't compare functions directly since validate_call wraps them
content = await prompt.render()
assert content[0].content.text == "Hello, world!" # type: ignore[attr-defined]
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_dict = await mcp.get_prompts()
assert len(prompts_dict) == 1
prompt = prompts_dict["custom_name"]
assert prompt.name == "custom_name"
content = await prompt.render()
assert content[0].content.text == "Hello, world!" # type: ignore[attr-defined]
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_dict = await mcp.get_prompts()
assert len(prompts_dict) == 1
prompt = prompts_dict["fn"]
assert prompt.description == "A custom description"
content = await prompt.render()
assert content[0].content.text == "Hello, world!" # type: ignore[attr-defined]
async def test_prompt_decorator_with_parens(self):
mcp = FastMCP()
@mcp.prompt
def fn() -> str:
return "Hello, world!"
prompts_dict = await mcp.get_prompts()
assert len(prompts_dict) == 1
prompt = prompts_dict["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 content.text == "Hello, World!" # type: ignore[attr-defined]
async def test_get_prompt_with_resource(self):
"""Test getting a prompt that returns resource content."""
mcp = FastMCP()
@mcp.prompt
def fn() -> PromptMessage:
return PromptMessage(
role="user",
content=EmbeddedResource(
type="resource",
resource=TextResourceContents(
uri=AnyUrl("file://file.txt"),
text="File contents",
mimeType="text/plain",
),
),
)
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_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_dict = await mcp.get_resources()
resources = list(resources_dict.values())
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_dict = await mcp.get_resource_templates()
template = templates_dict["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_dict = await mcp.get_prompts()
assert len(prompts_dict) == 1
prompt = prompts_dict["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!"
assert sample_prompt.enabled
prompt = await mcp.get_prompt("sample_prompt")
assert prompt.enabled
prompt.disable()
assert not prompt.enabled
assert not sample_prompt.enabled
prompt.enable()
assert prompt.enabled
assert sample_prompt.enabled
async def test_prompt_disabled_in_decorator(self):
mcp = FastMCP()
@mcp.prompt(enabled=False)
def sample_prompt() -> str:
return "Hello, world!"
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(enabled=False)
def sample_prompt() -> str:
return "Hello, world!"
sample_prompt.enable()
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!"
sample_prompt.disable()
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.enabled
sample_prompt.disable()
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(enabled=False)
def sample_prompt() -> str:
return "Hello, world!"
with pytest.raises(McpError, match="Unknown prompt"):
async with Client(mcp) as client:
await client.get_prompt("sample_prompt")
class TestPromptContext:
async def test_prompt_context(self):
mcp = FastMCP()
@mcp.prompt
def prompt_fn(name: str, ctx: Context) -> str:
assert isinstance(ctx, Context)
return f"Hello, {name}! {ctx.request_id}"
async with Client(mcp) as client:
result = await client.get_prompt("prompt_fn", {"name": "World"})
assert len(result.messages) == 1
message = result.messages[0]
assert message.role == "user"
async def test_prompt_context_with_callable_object(self):
mcp = FastMCP()
class MyPrompt:
def __call__(self, name: str, ctx: Context) -> str:
return f"Hello, {name}! {ctx.request_id}"
mcp.add_prompt(Prompt.from_function(MyPrompt(), name="my_prompt")) # noqa: F821
async with Client(mcp) as client:
result = await client.get_prompt("my_prompt", {"name": "World"})
assert len(result.messages) == 1
message = result.messages[0]
assert message.role == "user"
assert message.content.text == "Hello, World! 1" # type: ignore[attr-defined]
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 result.messages[0].content.text == "1" # type: ignore[attr-defined]
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 result.messages[0].content.text == "2" # type: ignore[attr-defined]
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"]
|